users.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 !readJSONBody(r, &body) || body.DisplayName == nil {
  58. writeError(w, http.StatusBadRequest, "invalid_input", `Se esperaba { "displayName": string }`)
  59. return
  60. }
  61. name := strings.TrimSpace(*body.DisplayName)
  62. if utf8.RuneCountInString(name) > 40 {
  63. writeError(w, http.StatusBadRequest, "invalid_input", "displayName máximo 40 caracteres")
  64. return
  65. }
  66. if strings.ContainsAny(name, "<>") {
  67. writeError(w, http.StatusBadRequest, "invalid_input", "displayName no puede contener '<' ni '>'")
  68. return
  69. }
  70. _, _ = s.db.Exec("UPDATE users SET display_name = ? WHERE id = ?", name, me.ID)
  71. w.WriteHeader(http.StatusNoContent)
  72. }
  73. // handleMyLanguage: {language: auto|es|en} → 204 (fuera del gate admin).
  74. func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
  75. me := auth.UserFromContext(r.Context())
  76. var body struct {
  77. Language string `json:"language"`
  78. }
  79. if !readJSONBody(r, &body) ||
  80. (body.Language != "auto" && body.Language != "es" && body.Language != "en") {
  81. writeError(w, http.StatusBadRequest, "invalid_input", "language debe ser auto|es|en")
  82. return
  83. }
  84. _, _ = s.db.Exec("UPDATE users SET language = ? WHERE id = ?", body.Language, me.ID)
  85. w.WriteHeader(http.StatusNoContent)
  86. }
  87. // handleListUsers: {users:[{id, username, role, language, displayName, created_at}]}
  88. // por username (SPEC-65 D65-5: displayName, "" si no puesto).
  89. func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
  90. rows, err := s.db.Query("SELECT id, username, role, language, display_name, created_at FROM users ORDER BY username")
  91. if err != nil {
  92. writeError(w, http.StatusInternalServerError, "internal_error")
  93. return
  94. }
  95. defer rows.Close()
  96. users := []map[string]any{}
  97. for rows.Next() {
  98. var (
  99. id int64
  100. username string
  101. role string
  102. language sql.NullString
  103. displayName sql.NullString
  104. createdAt int64
  105. )
  106. if err := rows.Scan(&id, &username, &role, &language, &displayName, &createdAt); err != nil {
  107. continue
  108. }
  109. var lang any
  110. if language.Valid {
  111. lang = language.String
  112. }
  113. users = append(users, map[string]any{
  114. "id": id, "username": username, "role": role, "language": lang,
  115. "displayName": displayName.String, "created_at": createdAt,
  116. })
  117. }
  118. writeJSON(w, http.StatusOK, map[string]any{"users": users})
  119. }
  120. // handleCreateUser: alta (admin). bcrypt cost 10.
  121. func (s *server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
  122. var body struct {
  123. Username *string `json:"username"`
  124. Password *string `json:"password"`
  125. Role *string `json:"role"`
  126. Language *string `json:"language"`
  127. }
  128. if !readJSONBody(r, &body) {
  129. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  130. return
  131. }
  132. // Validación (orden zod: username → password → role → language)
  133. if body.Username == nil {
  134. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  135. return
  136. }
  137. username := strings.TrimSpace(*body.Username)
  138. if len(username) < 2 {
  139. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 2 character(s)")
  140. return
  141. }
  142. if len(username) > 32 {
  143. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 32 character(s)")
  144. return
  145. }
  146. if !usernameRe.MatchString(username) {
  147. writeError(w, http.StatusBadRequest, "invalid_input", "usuario debe ser alfanumérico (.-_ permitidos)")
  148. return
  149. }
  150. if body.Password == nil {
  151. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  152. return
  153. }
  154. password := *body.Password
  155. if len(password) < 6 {
  156. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 6 character(s)")
  157. return
  158. }
  159. if len(password) > 128 {
  160. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  161. return
  162. }
  163. role := "user"
  164. if body.Role != nil {
  165. if *body.Role != "admin" && *body.Role != "user" {
  166. writeError(w, http.StatusBadRequest, "invalid_input",
  167. "Invalid enum value. Expected 'admin' | 'user'")
  168. return
  169. }
  170. role = *body.Role
  171. }
  172. language := "auto"
  173. if body.Language != nil {
  174. if *body.Language != "auto" && *body.Language != "es" && *body.Language != "en" {
  175. writeError(w, http.StatusBadRequest, "invalid_input",
  176. "Invalid enum value. Expected 'auto' | 'es' | 'en'")
  177. return
  178. }
  179. language = *body.Language
  180. }
  181. var exists int
  182. _ = s.db.QueryRow("SELECT 1 FROM users WHERE username = ?", username).Scan(&exists)
  183. if exists == 1 {
  184. writeError(w, http.StatusConflict, "duplicate_user", "Ya existe el usuario "+username)
  185. return
  186. }
  187. hash, err := auth.HashPassword(password)
  188. if err != nil {
  189. writeError(w, http.StatusInternalServerError, "internal_error")
  190. return
  191. }
  192. res, err := s.db.Exec(
  193. "INSERT INTO users (username, pass_hash, role, language, created_at) VALUES (?, ?, ?, ?, ?)",
  194. username, hash, role, language, db.NowMS(),
  195. )
  196. if err != nil {
  197. writeError(w, http.StatusInternalServerError, "internal_error")
  198. return
  199. }
  200. id, _ := res.LastInsertId()
  201. writeJSON(w, http.StatusCreated, map[string]any{
  202. "user": map[string]any{"id": id, "username": username, "role": role, "language": language},
  203. })
  204. }
  205. // handleSetPassword: {password 6..128} → 204 + destroyUserSessions.
  206. func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
  207. id, ok := parseUserID(r.PathValue("id"))
  208. if !ok {
  209. writeError(w, http.StatusNotFound, "not_found")
  210. return
  211. }
  212. target := s.findUser(id)
  213. if target == nil {
  214. writeError(w, http.StatusNotFound, "not_found")
  215. return
  216. }
  217. var body struct {
  218. Password *string `json:"password"`
  219. }
  220. if !readJSONBody(r, &body) || body.Password == nil || len(*body.Password) < 6 || len(*body.Password) > 128 {
  221. writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 6 caracteres")
  222. return
  223. }
  224. hash, err := auth.HashPassword(*body.Password)
  225. if err != nil {
  226. writeError(w, http.StatusInternalServerError, "internal_error")
  227. return
  228. }
  229. _, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", hash, target.ID)
  230. auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login
  231. w.WriteHeader(http.StatusNoContent)
  232. }
  233. // handleSetRole: rol nuevo en QUERY STRING (quirk del contrato) → 204.
  234. func (s *server) handleSetRole(w http.ResponseWriter, r *http.Request) {
  235. id, ok := parseUserID(r.PathValue("id"))
  236. if !ok {
  237. writeError(w, http.StatusNotFound, "not_found")
  238. return
  239. }
  240. me := auth.UserFromContext(r.Context())
  241. target := s.findUser(id)
  242. if target == nil {
  243. writeError(w, http.StatusNotFound, "not_found")
  244. return
  245. }
  246. role := r.URL.Query().Get("role")
  247. if role != "admin" && role != "user" {
  248. writeError(w, http.StatusBadRequest, "invalid_input", "role debe ser admin|user")
  249. return
  250. }
  251. if target.ID == me.ID {
  252. writeError(w, http.StatusBadRequest, "cannot_change_self", "No puedes cambiar tu propio rol")
  253. return
  254. }
  255. if target.Role == "admin" && role == "user" && s.adminCount() <= 1 {
  256. writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
  257. return
  258. }
  259. _, _ = s.db.Exec("UPDATE users SET role = ? WHERE id = ?", role, target.ID)
  260. auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login con el nuevo rol
  261. w.WriteHeader(http.StatusNoContent)
  262. }
  263. // handleDeleteUser: 204 (no self, no último admin); borra sesiones y la fila.
  264. func (s *server) handleDeleteUser(w http.ResponseWriter, r *http.Request) {
  265. id, ok := parseUserID(r.PathValue("id"))
  266. if !ok {
  267. writeError(w, http.StatusNotFound, "not_found")
  268. return
  269. }
  270. me := auth.UserFromContext(r.Context())
  271. target := s.findUser(id)
  272. if target == nil {
  273. writeError(w, http.StatusNotFound, "not_found")
  274. return
  275. }
  276. if target.ID == me.ID {
  277. writeError(w, http.StatusBadRequest, "cannot_delete_self", "No puedes borrar tu propio usuario")
  278. return
  279. }
  280. if target.Role == "admin" && s.adminCount() <= 1 {
  281. writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
  282. return
  283. }
  284. auth.DestroyUserSessions(s.db, target.ID)
  285. _, _ = s.db.Exec("DELETE FROM users WHERE id = ?", target.ID)
  286. w.WriteHeader(http.StatusNoContent)
  287. }