Files
baby-nas/internal/web/handlers_auth.go
T

50 lines
1.2 KiB
Go

package web
import (
"encoding/json"
"net/http"
)
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
if s.Auth == nil {
writeError(w, http.StatusServiceUnavailable, "auth not configured")
return
}
defer r.Body.Close()
var req loginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if !s.Auth.Authenticate(req.Username, req.Password) {
writeError(w, http.StatusUnauthorized, "invalid credentials")
return
}
s.Auth.setSessionCookie(w, req.Username)
writeJSON(w, http.StatusOK, map[string]any{"username": req.Username})
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if s.Auth != nil {
s.Auth.clearSessionCookie(w)
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (s *Server) handleAuthStatus(w http.ResponseWriter, r *http.Request) {
if s.Auth == nil {
writeJSON(w, http.StatusOK, map[string]any{"authenticated": true, "username": ""})
return
}
username, ok := s.Auth.currentUser(r)
writeJSON(w, http.StatusOK, map[string]any{
"authenticated": ok,
"username": username,
})
}