auth.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // auth.go — POST /api/auth/login · POST /api/auth/logout · GET /api/auth/me
  2. // (paridad routes/auth.js).
  3. package httpapi
  4. import (
  5. "net/http"
  6. "github.com/gnacho/netpulse/server-go/internal/auth"
  7. )
  8. // handleLogin: 429 rate_limited (antes de validar nada) → 400 invalid_body →
  9. // 401 invalid_credentials → 204 + Set-Cookie (rotación de sesión).
  10. func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
  11. if limited, retryAfterSec := auth.LoginRateLimited(s.db, r); limited {
  12. writeJSON(w, http.StatusTooManyRequests, map[string]any{
  13. "error": "rate_limited",
  14. "retryAfterSec": retryAfterSec,
  15. })
  16. return
  17. }
  18. var body struct {
  19. Username *string `json:"username"`
  20. Password *string `json:"password"`
  21. }
  22. if !readJSONBody(r, &body) || body.Username == nil || body.Password == nil ||
  23. len(*body.Username) < 1 || len(*body.Username) > 64 || len(*body.Password) < 1 {
  24. writeError(w, http.StatusBadRequest, "invalid_body",
  25. `Se esperaba { "username": string, "password": string }`)
  26. return
  27. }
  28. result := auth.HandleLogin(s.db, s.secret, r, *body.Username, *body.Password)
  29. if result == nil {
  30. auth.RegisterLoginFail(s.db, r)
  31. writeError(w, http.StatusUnauthorized, "invalid_credentials")
  32. return
  33. }
  34. auth.LoginOk(s.db, r)
  35. signed := auth.SignSessionID(s.secret, result.SessionID)
  36. w.Header().Set("Set-Cookie", auth.BuildSessionCookie(s.cfg, r, signed, auth.SessionTTLMS/1000))
  37. w.WriteHeader(http.StatusNoContent)
  38. }
  39. // handleLogout: destruye la sesión y borra la cookie (204; SIN Secure).
  40. func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) {
  41. auth.HandleLogout(s.db, s.secret, r)
  42. w.Header().Set("Set-Cookie", auth.ClearSessionCookie)
  43. w.WriteHeader(http.StatusNoContent)
  44. }
  45. // handleMe: {user, role, language, mode} (language releído de users).
  46. func (s *server) handleMe(mode string) http.HandlerFunc {
  47. return func(w http.ResponseWriter, r *http.Request) {
  48. user := auth.UserFromContext(r.Context())
  49. if user == nil {
  50. writeError(w, http.StatusUnauthorized, "unauthorized")
  51. return
  52. }
  53. language := "auto"
  54. var lang *string
  55. if err := s.db.QueryRow("SELECT language FROM users WHERE id = ?", user.ID).Scan(&lang); err == nil && lang != nil {
  56. language = *lang
  57. }
  58. writeJSON(w, http.StatusOK, map[string]any{
  59. "user": user.Username,
  60. "role": user.Role,
  61. "language": language,
  62. "mode": mode,
  63. })
  64. }
  65. }