48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"go-backend/internal/auth"
|
|
)
|
|
|
|
func (h *Handler) UserHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
// Get session token from cookie
|
|
cookies := auth.ParseCookies(r.Header.Get("Cookie"))
|
|
sessionToken, exists := cookies["session"]
|
|
if !exists {
|
|
http.Error(w, "Unauthorized, no session token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Validate session
|
|
session, err := h.auth.ValidateSessionToken(sessionToken)
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if session == nil {
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Get user info
|
|
user, err := h.users.FindByID(session.UserID)
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if user == nil {
|
|
http.Error(w, "User not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(user)
|
|
}
|