users.go 10 KB

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