users.go 13 KB

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