The user_session is valid for 24 hours, but the session will be bumped if it has been over an hour since the last update. An hour was set as a deadline, so that we would not update the user_session rows too often.
64 lines
1.4 KiB
Go
64 lines
1.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"go-backend/internal/auth"
|
|
"net/http"
|
|
)
|
|
|
|
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
|
|
cookie, err := r.Cookie("session")
|
|
if err != nil {
|
|
http.Error(w, "Unauthorized, no session token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Validate session
|
|
session, bump, err := h.auth.ValidateSessionToken(r.Context(), cookie.Value)
|
|
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if session == nil {
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if bump {
|
|
http.SetCookie(w, auth.NewSessionCookie(cookie.Value, false))
|
|
}
|
|
|
|
// 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)
|
|
}
|