start implementing auth

This commit is contained in:
2026-02-23 14:34:19 -05:00
parent 715c122eb7
commit af9c23c521
14 changed files with 341 additions and 24 deletions
+62
View File
@@ -0,0 +1,62 @@
package handlers
import (
"encoding/json"
"go-weather/models"
"go-weather/services"
"net/http"
"strings"
)
type UserHandler struct {
userService *services.UserService
}
func NewUserHandler(us *services.UserService) *UserHandler {
return &UserHandler{userService: us}
}
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var req models.RegisterRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
req.Email = strings.TrimSpace(strings.ToLower(req.Email))
if req.Email == "" || req.Password == "" {
http.Error(w, "email and password are required", http.StatusBadRequest)
return
}
if len(req.Password) < 8 {
http.Error(w, "password must be at least 8 characters", http.StatusBadRequest)
return
}
exists, err := h.userService.EmailExists(req.Email)
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if exists {
http.Error(w, "email already registered", http.StatusConflict)
return
}
user, err := h.userService.CreateUser(req.Email, req.Password)
if err != nil {
http.Error(w, "Failed to create user", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)
}