60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"go-backend/internal/auth"
|
|
)
|
|
|
|
type UserResponse struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
Email string `json:"email"`
|
|
}
|
|
|
|
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(r.Context(), 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(r.Context(), 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
|
|
}
|
|
|
|
resp := UserResponse{
|
|
ID: user.ID,
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(resp)
|
|
}
|