package handlers import ( "encoding/json" "net/http" "github.com/julienschmidt/httprouter" "otpm/api" "otpm/middleware" "otpm/models" "otpm/services" ) // OTPHandler handles OTP-related HTTP requests type OTPHandler struct { otpService *services.OTPService } // NewOTPHandler creates a new OTPHandler func NewOTPHandler(otpService *services.OTPService) *OTPHandler { return &OTPHandler{ otpService: otpService, } } // Routes returns the routes for OTP operations func (h *OTPHandler) Routes() map[string]httprouter.Handle { return map[string]httprouter.Handle{ "POST /api/otp": h.CreateOTP, "GET /api/otps": h.ListOTPs, "GET /api/otp/:id": h.GetOTP, } } // CreateOTP handles the creation of a new OTP func (h *OTPHandler) CreateOTP(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { // Get user ID from context userID, ok := r.Context().Value(middleware.UserIDKey).(string) if !ok { api.NewResponseWriter(w).WriteError(api.ErrUnauthorized) return } // Parse request body var params models.OTPParams if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { api.NewResponseWriter(w).WriteError(api.ValidationError("Invalid request body")) return } // Validate request if err := api.Validate.Struct(params); err != nil { api.NewResponseWriter(w).WriteError(api.ValidationError(err.Error())) return } // Create OTP otp, err := h.otpService.CreateOTP(r.Context(), userID, params) if err != nil { api.NewResponseWriter(w).WriteError(api.InternalError(err)) return } // Return response api.NewResponseWriter(w).WriteSuccess(otp) } // ListOTPs handles listing all OTPs for a user func (h *OTPHandler) ListOTPs(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { // Get user ID from context userID, ok := r.Context().Value(middleware.UserIDKey).(string) if !ok { api.NewResponseWriter(w).WriteError(api.ErrUnauthorized) return } // Get OTPs otps, err := h.otpService.ListOTPs(r.Context(), userID) if err != nil { api.NewResponseWriter(w).WriteError(api.InternalError(err)) return } // Return response api.NewResponseWriter(w).WriteSuccess(otps) } // GetOTP handles getting a specific OTP func (h *OTPHandler) GetOTP(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // Get user ID from context userID, ok := r.Context().Value(middleware.UserIDKey).(string) if !ok { api.NewResponseWriter(w).WriteError(api.ErrUnauthorized) return } // Get OTP ID from URL otpID := ps.ByName("id") if otpID == "" { api.NewResponseWriter(w).WriteError(api.ValidationError("Missing OTP ID")) return } // Get OTP otp, err := h.otpService.GetOTP(r.Context(), otpID, userID) if err != nil { api.NewResponseWriter(w).WriteError(api.InternalError(err)) return } // Return response api.NewResponseWriter(w).WriteSuccess(otp) }