tokens_api.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package httpapi
  2. import (
  3. "net/http"
  4. "github.com/gnacho/netpulse/server-go/internal/apitoken"
  5. "github.com/gnacho/netpulse/server-go/internal/auth"
  6. )
  7. func (s *server) handleTokensList(w http.ResponseWriter, r *http.Request) {
  8. if s.tokenStore == nil {
  9. writeError(w, http.StatusServiceUnavailable, "tokens_disabled")
  10. return
  11. }
  12. user := auth.UserFromContext(r.Context())
  13. if user == nil {
  14. writeError(w, http.StatusUnauthorized, "unauthorized")
  15. return
  16. }
  17. tokens, err := s.tokenStore.List(user.ID, user.Role == "admin")
  18. if err != nil {
  19. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  20. return
  21. }
  22. type item struct {
  23. ID string `json:"id"`
  24. Name string `json:"name"`
  25. Scope string `json:"scope"`
  26. UserID int64 `json:"userId"`
  27. CreatedAt int64 `json:"createdAt"`
  28. ExpiresAt int64 `json:"expiresAt"`
  29. LastUsedAt int64 `json:"lastUsedAt"`
  30. }
  31. out := make([]item, 0, len(tokens))
  32. for _, t := range tokens {
  33. out = append(out, item{
  34. ID: t.ID, Name: t.Name, Scope: t.Scope, UserID: t.UserID,
  35. CreatedAt: t.CreatedAt, ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt,
  36. })
  37. }
  38. writeJSON(w, http.StatusOK, map[string]any{"tokens": out})
  39. }
  40. func (s *server) handleTokensCreate(w http.ResponseWriter, r *http.Request) {
  41. if s.tokenStore == nil {
  42. writeError(w, http.StatusServiceUnavailable, "tokens_disabled")
  43. return
  44. }
  45. user := auth.UserFromContext(r.Context())
  46. if user == nil {
  47. writeError(w, http.StatusUnauthorized, "unauthorized")
  48. return
  49. }
  50. var body struct {
  51. Name string `json:"name"`
  52. Scope string `json:"scope"`
  53. ExpiresIn int `json:"expiresInDays"`
  54. }
  55. if status := readJSONBody(w, r, &body); status != 0 {
  56. writeBodyError(w, status, "invalid_body", "")
  57. return
  58. }
  59. if body.Name == "" || body.Scope == "" {
  60. writeError(w, http.StatusBadRequest, "invalid_input", "name and scope required")
  61. return
  62. }
  63. // Un token no puede elevarse por encima de sí mismo: solo un admin con
  64. // sesión (o un token admin) puede emitir otro token admin.
  65. if body.Scope == apitoken.ScopeAdmin {
  66. if user.Role != "admin" {
  67. writeError(w, http.StatusForbidden, "forbidden")
  68. return
  69. }
  70. if scope := auth.APITokenFromContext(r.Context()); scope != "" && scope != apitoken.ScopeAdmin {
  71. writeError(w, http.StatusForbidden, "insufficient_scope")
  72. return
  73. }
  74. }
  75. id, raw, err := s.tokenStore.Create(body.Name, body.Scope, user.ID, body.ExpiresIn)
  76. if err != nil {
  77. writeError(w, http.StatusBadRequest, "create_failed", err.Error())
  78. return
  79. }
  80. writeJSON(w, http.StatusCreated, map[string]any{
  81. "id": id, "name": body.Name, "scope": body.Scope, "token": raw,
  82. })
  83. }
  84. func (s *server) handleTokensDelete(w http.ResponseWriter, r *http.Request) {
  85. if s.tokenStore == nil {
  86. writeError(w, http.StatusServiceUnavailable, "tokens_disabled")
  87. return
  88. }
  89. user := auth.UserFromContext(r.Context())
  90. if user == nil {
  91. writeError(w, http.StatusUnauthorized, "unauthorized")
  92. return
  93. }
  94. id := r.PathValue("id")
  95. if id == "" {
  96. writeError(w, http.StatusBadRequest, "invalid_input")
  97. return
  98. }
  99. if err := s.tokenStore.Delete(id, user.ID, user.Role == "admin"); err != nil {
  100. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  101. return
  102. }
  103. w.WriteHeader(http.StatusNoContent)
  104. }