add auth to backend and frontend

This commit is contained in:
2026-02-24 10:42:36 -05:00
parent 11eb192e2a
commit 0d5cc4d21f
14 changed files with 336 additions and 35 deletions
+39 -1
View File
@@ -2,6 +2,7 @@ package handlers
import (
"encoding/json"
"go-weather/middleware"
"go-weather/models"
"go-weather/services"
"net/http"
@@ -17,6 +18,21 @@ func NewUserHandler(us *services.UserService, as *services.AuthService) *UserHan
return &UserHandler{userService: us, authService: as}
}
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
claims := middleware.GetClaims(r)
if claims == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
}
user, err := h.userService.GetUserByID(claims.UserID)
if err != nil {
http.Error(w, "user not found", http.StatusNotFound)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"user": user})
}
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
@@ -93,7 +109,29 @@ func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
return
}
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: token,
Path: "/",
HttpOnly: true,
Secure: true, // HTTPS only
SameSite: http.SameSiteStrictMode,
MaxAge: 86400, // 24 hours
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(models.LoginResponse{User: *user, Token: token})
json.NewEncoder(w).Encode(models.LoginResponse{User: *user})
}
func (h *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: "",
Path: "/",
HttpOnly: true,
Secure: true,
MaxAge: -1,
})
w.WriteHeader(http.StatusOK)
}