users.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // users.go — CRUD de usuarios (paridad routes/users.js).
  2. //
  3. // PUT /api/auth/password (autenticado — cambia la PROPIA contraseña)
  4. // PUT /api/users/me/language (cualquier rol — fuera del gate admin)
  5. // PUT /api/users/me/display-name (cualquier rol — fuera del gate admin)
  6. // GET /api/users (admin)
  7. // POST /api/users (admin) → 201 · 400 · 409
  8. // PUT /api/users/:id/password (admin) → 204 (invalida sus sesiones)
  9. // PUT /api/users/:id/role?role= (admin) → rol nuevo en QUERY STRING (quirk)
  10. // DELETE /api/users/:id (admin) → 204 (no self, no último admin)
  11. package httpapi
  12. import (
  13. "database/sql"
  14. "net/http"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "unicode/utf8"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/db"
  21. )
  22. var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  23. // parseUserID replica Number(:id): no numérico → NaN → no encontrado (404).
  24. func parseUserID(s string) (float64, bool) {
  25. n, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
  26. if err != nil {
  27. return 0, false
  28. }
  29. return n, true
  30. }
  31. type userTarget struct {
  32. ID int64
  33. Username string
  34. Role string
  35. }
  36. func (s *server) findUser(id float64) *userTarget {
  37. var t userTarget
  38. err := s.db.QueryRow("SELECT id, username, role FROM users WHERE id = ?", id).
  39. Scan(&t.ID, &t.Username, &t.Role)
  40. if err != nil {
  41. return nil
  42. }
  43. return &t
  44. }
  45. func (s *server) adminCount() int {
  46. var n int
  47. _ = s.db.QueryRow("SELECT COUNT(*) FROM users WHERE role = 'admin'").Scan(&n)
  48. return n
  49. }
  50. // handleMyDisplayName (SPEC-65 D65-5): {displayName: string} → 204 (fuera del
  51. // gate admin). Trim, máx 40 runes, vacío permitido (= volver al username) y
  52. // sin '<' ni '>' (el frontend ya escapa, pero no se permite HTML).
  53. func (s *server) handleMyDisplayName(w http.ResponseWriter, r *http.Request) {
  54. me := auth.UserFromContext(r.Context())
  55. var body struct {
  56. DisplayName *string `json:"displayName"`
  57. }
  58. if st := readJSONBody(w, r, &body); st != 0 {
  59. writeBodyError(w, st, "invalid_input", `Se esperaba { "displayName": string }`)
  60. return
  61. }
  62. if body.DisplayName == nil {
  63. writeError(w, http.StatusBadRequest, "invalid_input", `Se esperaba { "displayName": string }`)
  64. return
  65. }
  66. name := strings.TrimSpace(*body.DisplayName)
  67. if utf8.RuneCountInString(name) > 40 {
  68. writeError(w, http.StatusBadRequest, "invalid_input", "displayName máximo 40 caracteres")
  69. return
  70. }
  71. if strings.ContainsAny(name, "<>") {
  72. writeError(w, http.StatusBadRequest, "invalid_input", "displayName no puede contener '<' ni '>'")
  73. return
  74. }
  75. _, _ = s.db.Exec("UPDATE users SET display_name = ? WHERE id = ?", name, me.ID)
  76. w.WriteHeader(http.StatusNoContent)
  77. }
  78. // handleMyLanguage: {language: auto|es|en} → 204 (fuera del gate admin).
  79. func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
  80. me := auth.UserFromContext(r.Context())
  81. var body struct {
  82. Language string `json:"language"`
  83. }
  84. if st := readJSONBody(w, r, &body); st != 0 {
  85. writeBodyError(w, st, "invalid_input", "language debe ser auto|es|en")
  86. return
  87. }
  88. if body.Language != "auto" && body.Language != "es" && body.Language != "en" {
  89. writeError(w, http.StatusBadRequest, "invalid_input", "language debe ser auto|es|en")
  90. return
  91. }
  92. _, _ = s.db.Exec("UPDATE users SET language = ? WHERE id = ?", body.Language, me.ID)
  93. w.WriteHeader(http.StatusNoContent)
  94. }
  95. // handleListUsers: {users:[{id, username, role, language, displayName, created_at}]}
  96. // por username (SPEC-65 D65-5: displayName, "" si no puesto).
  97. func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
  98. rows, err := s.db.Query("SELECT id, username, role, language, display_name, created_at FROM users ORDER BY username")
  99. if err != nil {
  100. writeError(w, http.StatusInternalServerError, "internal_error")
  101. return
  102. }
  103. defer rows.Close()
  104. users := []map[string]any{}
  105. for rows.Next() {
  106. var (
  107. id int64
  108. username string
  109. role string
  110. language sql.NullString
  111. displayName sql.NullString
  112. createdAt int64
  113. )
  114. if err := rows.Scan(&id, &username, &role, &language, &displayName, &createdAt); err != nil {
  115. continue
  116. }
  117. var lang any
  118. if language.Valid {
  119. lang = language.String
  120. }
  121. users = append(users, map[string]any{
  122. "id": id, "username": username, "role": role, "language": lang,
  123. "displayName": displayName.String, "created_at": createdAt,
  124. })
  125. }
  126. writeJSON(w, http.StatusOK, map[string]any{"users": users})
  127. }
  128. // handleCreateUser: alta (admin). bcrypt cost 10.
  129. func (s *server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
  130. var body struct {
  131. Username *string `json:"username"`
  132. Password *string `json:"password"`
  133. Role *string `json:"role"`
  134. Language *string `json:"language"`
  135. }
  136. if st := readJSONBody(w, r, &body); st != 0 {
  137. writeBodyError(w, st, "invalid_input", "Required")
  138. return
  139. }
  140. // Validación (orden zod: username → password → role → language)
  141. if body.Username == nil {
  142. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  143. return
  144. }
  145. username := strings.TrimSpace(*body.Username)
  146. if len(username) < 2 {
  147. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 2 character(s)")
  148. return
  149. }
  150. if len(username) > 32 {
  151. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 32 character(s)")
  152. return
  153. }
  154. if !usernameRe.MatchString(username) {
  155. writeError(w, http.StatusBadRequest, "invalid_input", "usuario debe ser alfanumérico (.-_ permitidos)")
  156. return
  157. }
  158. if body.Password == nil {
  159. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  160. return
  161. }
  162. password := *body.Password
  163. if len(password) < 10 {
  164. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 10 character(s)")
  165. return
  166. }
  167. if len(password) > 128 {
  168. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  169. return
  170. }
  171. role := "user"
  172. if body.Role != nil {
  173. if *body.Role != "admin" && *body.Role != "user" {
  174. writeError(w, http.StatusBadRequest, "invalid_input",
  175. "Invalid enum value. Expected 'admin' | 'user'")
  176. return
  177. }
  178. role = *body.Role
  179. }
  180. language := "auto"
  181. if body.Language != nil {
  182. if *body.Language != "auto" && *body.Language != "es" && *body.Language != "en" {
  183. writeError(w, http.StatusBadRequest, "invalid_input",
  184. "Invalid enum value. Expected 'auto' | 'es' | 'en'")
  185. return
  186. }
  187. language = *body.Language
  188. }
  189. var exists int
  190. _ = s.db.QueryRow("SELECT 1 FROM users WHERE username = ?", username).Scan(&exists)
  191. if exists == 1 {
  192. writeError(w, http.StatusConflict, "duplicate_user", "Ya existe el usuario "+username)
  193. return
  194. }
  195. hash, err := auth.HashPassword(password)
  196. if err != nil {
  197. writeError(w, http.StatusInternalServerError, "internal_error")
  198. return
  199. }
  200. res, err := s.db.Exec(
  201. "INSERT INTO users (username, pass_hash, role, language, created_at) VALUES (?, ?, ?, ?, ?)",
  202. username, hash, role, language, db.NowMS(),
  203. )
  204. if err != nil {
  205. writeError(w, http.StatusInternalServerError, "internal_error")
  206. return
  207. }
  208. id, _ := res.LastInsertId()
  209. writeJSON(w, http.StatusCreated, map[string]any{
  210. "user": map[string]any{"id": id, "username": username, "role": role, "language": language},
  211. })
  212. }
  213. // handleMyPassword (#465): PUT /api/auth/password {current, password} → 204.
  214. // Verifica la contraseña actual contra el hash almacenado, aplica la misma
  215. // política que el alta (10..128) e invalida las demás sesiones del usuario;
  216. // la sesión que pide el cambio sigue viva (no se desloguea a sí mismo).
  217. func (s *server) handleMyPassword(w http.ResponseWriter, r *http.Request) {
  218. me := auth.UserFromContext(r.Context())
  219. var body struct {
  220. Current *string `json:"current"`
  221. Password *string `json:"password"`
  222. }
  223. if st := readJSONBody(w, r, &body); st != 0 {
  224. writeBodyError(w, st, "invalid_input", "current y password son obligatorios")
  225. return
  226. }
  227. if body.Current == nil || body.Password == nil {
  228. writeError(w, http.StatusBadRequest, "invalid_input", "current y password son obligatorios")
  229. return
  230. }
  231. if len(*body.Password) < 10 || len(*body.Password) > 128 {
  232. writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 10 caracteres")
  233. return
  234. }
  235. var hash string
  236. err := s.db.QueryRow("SELECT pass_hash FROM users WHERE id = ?", me.ID).Scan(&hash)
  237. if err != nil || !auth.CheckPassword(*body.Current, hash) {
  238. writeError(w, http.StatusUnauthorized, "invalid_credentials", "la contraseña actual no es correcta")
  239. return
  240. }
  241. newHash, err := auth.HashPassword(*body.Password)
  242. if err != nil {
  243. writeError(w, http.StatusInternalServerError, "internal_error")
  244. return
  245. }
  246. _, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", newHash, me.ID)
  247. if current := auth.SessionIDFromRequest(s.db, s.secret, r); current != "" {
  248. _, _ = s.db.Exec("DELETE FROM sessions WHERE user_id = ? AND id <> ?", me.ID, current)
  249. } else {
  250. auth.DestroyUserSessions(s.db, me.ID)
  251. }
  252. w.WriteHeader(http.StatusNoContent)
  253. }
  254. // handleSetPassword: {password 6..128} → 204 + destroyUserSessions.
  255. func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
  256. id, ok := parseUserID(r.PathValue("id"))
  257. if !ok {
  258. writeError(w, http.StatusNotFound, "not_found")
  259. return
  260. }
  261. target := s.findUser(id)
  262. if target == nil {
  263. writeError(w, http.StatusNotFound, "not_found")
  264. return
  265. }
  266. var body struct {
  267. Password *string `json:"password"`
  268. }
  269. if st := readJSONBody(w, r, &body); st != 0 {
  270. writeBodyError(w, st, "invalid_input", "password mínimo 10 caracteres")
  271. return
  272. }
  273. if body.Password == nil || len(*body.Password) < 10 || len(*body.Password) > 128 {
  274. writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 10 caracteres")
  275. return
  276. }
  277. hash, err := auth.HashPassword(*body.Password)
  278. if err != nil {
  279. writeError(w, http.StatusInternalServerError, "internal_error")
  280. return
  281. }
  282. _, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", hash, target.ID)
  283. auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login
  284. w.WriteHeader(http.StatusNoContent)
  285. }
  286. // handleSetRole: rol nuevo en QUERY STRING (quirk del contrato) → 204.
  287. func (s *server) handleSetRole(w http.ResponseWriter, r *http.Request) {
  288. id, ok := parseUserID(r.PathValue("id"))
  289. if !ok {
  290. writeError(w, http.StatusNotFound, "not_found")
  291. return
  292. }
  293. me := auth.UserFromContext(r.Context())
  294. target := s.findUser(id)
  295. if target == nil {
  296. writeError(w, http.StatusNotFound, "not_found")
  297. return
  298. }
  299. role := r.URL.Query().Get("role")
  300. if role != "admin" && role != "user" {
  301. writeError(w, http.StatusBadRequest, "invalid_input", "role debe ser admin|user")
  302. return
  303. }
  304. if target.ID == me.ID {
  305. writeError(w, http.StatusBadRequest, "cannot_change_self", "No puedes cambiar tu propio rol")
  306. return
  307. }
  308. if target.Role == "admin" && role == "user" && s.adminCount() <= 1 {
  309. writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
  310. return
  311. }
  312. _, _ = s.db.Exec("UPDATE users SET role = ? WHERE id = ?", role, target.ID)
  313. auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login con el nuevo rol
  314. w.WriteHeader(http.StatusNoContent)
  315. }
  316. // handleDeleteUser: 204 (no self, no último admin); borra sesiones y la fila.
  317. func (s *server) handleDeleteUser(w http.ResponseWriter, r *http.Request) {
  318. id, ok := parseUserID(r.PathValue("id"))
  319. if !ok {
  320. writeError(w, http.StatusNotFound, "not_found")
  321. return
  322. }
  323. me := auth.UserFromContext(r.Context())
  324. target := s.findUser(id)
  325. if target == nil {
  326. writeError(w, http.StatusNotFound, "not_found")
  327. return
  328. }
  329. if target.ID == me.ID {
  330. writeError(w, http.StatusBadRequest, "cannot_delete_self", "No puedes borrar tu propio usuario")
  331. return
  332. }
  333. if target.Role == "admin" && s.adminCount() <= 1 {
  334. writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
  335. return
  336. }
  337. auth.DestroyUserSessions(s.db, target.ID)
  338. _, _ = s.db.Exec("DELETE FROM users WHERE id = ?", target.ID)
  339. w.WriteHeader(http.StatusNoContent)
  340. }