Spaces:
Runtime error
Runtime error
File size: 2,314 Bytes
6e293bd 8a5f1ff 6e293bd 8a5f1ff 6e293bd c4b33a8 6e293bd 8a5f1ff 6e293bd 8a5f1ff 6e293bd 8a5f1ff 6e293bd 8a5f1ff 6e293bd c4b33a8 6e293bd c4b33a8 8a5f1ff 6e293bd 8a5f1ff 6e293bd 8a5f1ff 6e293bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | package handler
import (
"fmt"
"log"
"net/http"
"time"
"github.com/alberdjuniawan/anput-api/repository"
"github.com/alberdjuniawan/anput-api/util"
chiMiddleware "github.com/go-chi/chi/v5/middleware"
"golang.org/x/crypto/bcrypt"
)
type AuthHandler struct {
Repo repository.Repository
}
func NewAuthHandler(repo repository.Repository) *AuthHandler {
return &AuthHandler{Repo: repo}
}
func (h *AuthHandler) GenerateSandboxKey(w http.ResponseWriter, r *http.Request) {
reqID := chiMiddleware.GetReqID(r.Context())
ctx := r.Context()
randSuffix, _ := util.GenerateRandomString(4)
guestEmail := fmt.Sprintf("guest_%d_%s@anput.temp", time.Now().Unix(), randSuffix)
userID, err := h.Repo.CreateUser(ctx, guestEmail)
if err != nil {
log.Printf("[%s] Error creating guest user: %v", reqID, err)
util.WriteError(w, http.StatusInternalServerError, "Failed to initialize session", reqID)
return
}
prefix := "anput_live"
publicID, err := util.GenerateRandomString(8)
if err != nil {
log.Printf("[%s] Random string gen error (publicID): %v", reqID, err)
util.WriteError(w, http.StatusInternalServerError, "Key generation failed", reqID)
return
}
secret, err := util.GenerateRandomString(16)
if err != nil {
log.Printf("[%s] Random string gen error (secret): %v", reqID, err)
util.WriteError(w, http.StatusInternalServerError, "Key generation failed", reqID)
return
}
hashedSecret, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
if err != nil {
log.Printf("[%s] Hashing error: %v", reqID, err)
util.WriteError(w, http.StatusInternalServerError, "Security processing failed", reqID)
return
}
expiresAt := time.Now().Add(30 * time.Minute)
err = h.Repo.CreateAPIKey(ctx, userID, "Guest Sandbox Session", prefix, publicID, string(hashedSecret), expiresAt)
if err != nil {
log.Printf("[%s] Repo CreateAPIKey error: %v", reqID, err)
util.WriteError(w, http.StatusInternalServerError, "Failed to save credentials", reqID)
return
}
fullApiKey := fmt.Sprintf("%s_%s_%s", prefix, publicID, secret)
responseData := map[string]interface{}{
"api_key": fullApiKey,
"expires_at": expiresAt,
"message": "Ephemeral sandbox session created. Valid for 30 minutes.",
}
util.WriteSuccess(w, http.StatusCreated, responseData, reqID)
}
|