users.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // users.go — CRUD de usuarios (paridad routes/users.js).
  2. //
  3. // PUT /api/users/me/language (cualquier rol — fuera del gate admin)
  4. // GET /api/users (admin)
  5. // POST /api/users (admin) → 201 · 400 · 409
  6. // PUT /api/users/:id/password (admin) → 204 (invalida sus sesiones)
  7. // PUT /api/users/:id/role?role= (admin) → rol nuevo en QUERY STRING (quirk)
  8. // DELETE /api/users/:id (admin) → 204 (no self, no último admin)
  9. package httpapi
  10. import (
  11. "database/sql"
  12. "net/http"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "github.com/gnacho/netpulse/server-go/internal/auth"
  17. "github.com/gnacho/netpulse/server-go/internal/db"
  18. )
  19. var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  20. // parseUserID replica Number(:id): no numérico → NaN → no encontrado (404).
  21. func parseUserID(s string) (float64, bool) {
  22. n, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
  23. if err != nil {
  24. return 0, false
  25. }
  26. return n, true
  27. }
  28. type userTarget struct {
  29. ID int64
  30. Username string
  31. Role string
  32. }
  33. func (s *server) findUser(id float64) *userTarget {
  34. var t userTarget
  35. err := s.db.QueryRow("SELECT id, username, role FROM users WHERE id = ?", id).
  36. Scan(&t.ID, &t.Username, &t.Role)
  37. if err != nil {
  38. return nil
  39. }
  40. return &t
  41. }
  42. func (s *server) adminCount() int {
  43. var n int
  44. _ = s.db.QueryRow("SELECT COUNT(*) FROM users WHERE role = 'admin'").Scan(&n)
  45. return n
  46. }
  47. // handleMyLanguage: {language: auto|es|en} → 204 (fuera del gate admin).
  48. func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
  49. me := auth.UserFromContext(r.Context())
  50. var body struct {
  51. Language string `json:"language"`
  52. }
  53. if !readJSONBody(r, &body) ||
  54. (body.Language != "auto" && body.Language != "es" && body.Language != "en") {
  55. writeError(w, http.StatusBadRequest, "invalid_input", "language debe ser auto|es|en")
  56. return
  57. }
  58. _, _ = s.db.Exec("UPDATE users SET language = ? WHERE id = ?", body.Language, me.ID)
  59. w.WriteHeader(http.StatusNoContent)
  60. }
  61. // handleListUsers: {users:[{id, username, role, language, created_at}]} por username.
  62. func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
  63. rows, err := s.db.Query("SELECT id, username, role, language, created_at FROM users ORDER BY username")
  64. if err != nil {
  65. writeError(w, http.StatusInternalServerError, "internal_error")
  66. return
  67. }
  68. defer rows.Close()
  69. users := []map[string]any{}
  70. for rows.Next() {
  71. var (
  72. id int64
  73. username string
  74. role string
  75. language sql.NullString
  76. createdAt int64
  77. )
  78. if err := rows.Scan(&id, &username, &role, &language, &createdAt); err != nil {
  79. continue
  80. }
  81. var lang any
  82. if language.Valid {
  83. lang = language.String
  84. }
  85. users = append(users, map[string]any{
  86. "id": id, "username": username, "role": role, "language": lang, "created_at": createdAt,
  87. })
  88. }
  89. writeJSON(w, http.StatusOK, map[string]any{"users": users})
  90. }
  91. // handleCreateUser: alta (admin). bcrypt cost 10.
  92. func (s *server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
  93. var body struct {
  94. Username *string `json:"username"`
  95. Password *string `json:"password"`
  96. Role *string `json:"role"`
  97. Language *string `json:"language"`
  98. }
  99. if !readJSONBody(r, &body) {
  100. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  101. return
  102. }
  103. // Validación (orden zod: username → password → role → language)
  104. if body.Username == nil {
  105. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  106. return
  107. }
  108. username := strings.TrimSpace(*body.Username)
  109. if len(username) < 2 {
  110. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 2 character(s)")
  111. return
  112. }
  113. if len(username) > 32 {
  114. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 32 character(s)")
  115. return
  116. }
  117. if !usernameRe.MatchString(username) {
  118. writeError(w, http.StatusBadRequest, "invalid_input", "usuario debe ser alfanumérico (.-_ permitidos)")
  119. return
  120. }
  121. if body.Password == nil {
  122. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  123. return
  124. }
  125. password := *body.Password
  126. if len(password) < 6 {
  127. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 6 character(s)")
  128. return
  129. }
  130. if len(password) > 128 {
  131. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  132. return
  133. }
  134. role := "user"
  135. if body.Role != nil {
  136. if *body.Role != "admin" && *body.Role != "user" {
  137. writeError(w, http.StatusBadRequest, "invalid_input",
  138. "Invalid enum value. Expected 'admin' | 'user'")
  139. return
  140. }
  141. role = *body.Role
  142. }
  143. language := "auto"
  144. if body.Language != nil {
  145. if *body.Language != "auto" && *body.Language != "es" && *body.Language != "en" {
  146. writeError(w, http.StatusBadRequest, "invalid_input",
  147. "Invalid enum value. Expected 'auto' | 'es' | 'en'")
  148. return
  149. }
  150. language = *body.Language
  151. }
  152. var exists int
  153. _ = s.db.QueryRow("SELECT 1 FROM users WHERE username = ?", username).Scan(&exists)
  154. if exists == 1 {
  155. writeError(w, http.StatusConflict, "duplicate_user", "Ya existe el usuario "+username)
  156. return
  157. }
  158. hash, err := auth.HashPassword(password)
  159. if err != nil {
  160. writeError(w, http.StatusInternalServerError, "internal_error")
  161. return
  162. }
  163. res, err := s.db.Exec(
  164. "INSERT INTO users (username, pass_hash, role, language, created_at) VALUES (?, ?, ?, ?, ?)",
  165. username, hash, role, language, db.NowMS(),
  166. )
  167. if err != nil {
  168. writeError(w, http.StatusInternalServerError, "internal_error")
  169. return
  170. }
  171. id, _ := res.LastInsertId()
  172. writeJSON(w, http.StatusCreated, map[string]any{
  173. "user": map[string]any{"id": id, "username": username, "role": role, "language": language},
  174. })
  175. }
  176. // handleSetPassword: {password 6..128} → 204 + destroyUserSessions.
  177. func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
  178. id, ok := parseUserID(r.PathValue("id"))
  179. if !ok {
  180. writeError(w, http.StatusNotFound, "not_found")
  181. return
  182. }
  183. target := s.findUser(id)
  184. if target == nil {
  185. writeError(w, http.StatusNotFound, "not_found")
  186. return
  187. }
  188. var body struct {
  189. Password *string `json:"password"`
  190. }
  191. if !readJSONBody(r, &body) || body.Password == nil || len(*body.Password) < 6 || len(*body.Password) > 128 {
  192. writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 6 caracteres")
  193. return
  194. }
  195. hash, err := auth.HashPassword(*body.Password)
  196. if err != nil {
  197. writeError(w, http.StatusInternalServerError, "internal_error")
  198. return
  199. }
  200. _, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", hash, target.ID)
  201. auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login
  202. w.WriteHeader(http.StatusNoContent)
  203. }
  204. // handleSetRole: rol nuevo en QUERY STRING (quirk del contrato) → 204.
  205. func (s *server) handleSetRole(w http.ResponseWriter, r *http.Request) {
  206. id, ok := parseUserID(r.PathValue("id"))
  207. if !ok {
  208. writeError(w, http.StatusNotFound, "not_found")
  209. return
  210. }
  211. me := auth.UserFromContext(r.Context())
  212. target := s.findUser(id)
  213. if target == nil {
  214. writeError(w, http.StatusNotFound, "not_found")
  215. return
  216. }
  217. role := r.URL.Query().Get("role")
  218. if role != "admin" && role != "user" {
  219. writeError(w, http.StatusBadRequest, "invalid_input", "role debe ser admin|user")
  220. return
  221. }
  222. if target.ID == me.ID {
  223. writeError(w, http.StatusBadRequest, "cannot_change_self", "No puedes cambiar tu propio rol")
  224. return
  225. }
  226. if target.Role == "admin" && role == "user" && s.adminCount() <= 1 {
  227. writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
  228. return
  229. }
  230. _, _ = s.db.Exec("UPDATE users SET role = ? WHERE id = ?", role, target.ID)
  231. auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login con el nuevo rol
  232. w.WriteHeader(http.StatusNoContent)
  233. }
  234. // handleDeleteUser: 204 (no self, no último admin); borra sesiones y la fila.
  235. func (s *server) handleDeleteUser(w http.ResponseWriter, r *http.Request) {
  236. id, ok := parseUserID(r.PathValue("id"))
  237. if !ok {
  238. writeError(w, http.StatusNotFound, "not_found")
  239. return
  240. }
  241. me := auth.UserFromContext(r.Context())
  242. target := s.findUser(id)
  243. if target == nil {
  244. writeError(w, http.StatusNotFound, "not_found")
  245. return
  246. }
  247. if target.ID == me.ID {
  248. writeError(w, http.StatusBadRequest, "cannot_delete_self", "No puedes borrar tu propio usuario")
  249. return
  250. }
  251. if target.Role == "admin" && s.adminCount() <= 1 {
  252. writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
  253. return
  254. }
  255. auth.DestroyUserSessions(s.db, target.ID)
  256. _, _ = s.db.Exec("DELETE FROM users WHERE id = ?", target.ID)
  257. w.WriteHeader(http.StatusNoContent)
  258. }