main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Command authd is the in-house multi-tenant auth IdP that powers
  2. // the M13 admin UI. It exposes:
  3. //
  4. // POST /v1/auth/login — email + password → access JWT + refresh token
  5. // POST /v1/auth/refresh — refresh token → new pair
  6. // POST /v1/auth/logout — refresh token → revoke
  7. // POST /v1/auth/magic — magic-link token + new password → session
  8. // POST /v1/users/invite — super/tenant-admin → magic link (email side-effect lives in the caller)
  9. // GET /v1/users/me — current user info
  10. // GET /health, /metrics — observability
  11. //
  12. // All endpoints are unauthenticated except /v1/users/me and
  13. // /v1/users/invite (which require a valid access JWT). The auth
  14. // path is /v1/auth/* (no JWT required to log in, naturally).
  15. //
  16. // Configuration: env vars only. See authdEnv() below.
  17. package main
  18. import (
  19. "context"
  20. cryptorand "crypto/rand"
  21. "encoding/json"
  22. "errors"
  23. "log/slog"
  24. "net/http"
  25. "os"
  26. "os/signal"
  27. "strconv"
  28. "syscall"
  29. "time"
  30. "git3.techno-world.net/lrosales/broad-announce/internal/authd"
  31. "git3.techno-world.net/lrosales/broad-announce/internal/httpserver"
  32. "git3.techno-world.net/lrosales/broad-announce/internal/observability"
  33. "git3.techno-world.net/lrosales/broad-announce/internal/postgres"
  34. )
  35. func main() {
  36. logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
  37. if err := run(logger); err != nil {
  38. logger.Error("authd exited with error", "err", err)
  39. os.Exit(1)
  40. }
  41. }
  42. func run(logger *slog.Logger) error {
  43. cfg, err := authdEnv()
  44. if err != nil {
  45. return err
  46. }
  47. logger.Info("authd starting",
  48. "env", cfg.Env, "addr", cfg.HTTPAddr,
  49. "issuer", cfg.Issuer, "access_ttl", cfg.AuthdConfig.AccessTokenTTL)
  50. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
  51. defer stop()
  52. pool, err := postgres.Connect(ctx, cfg.PostgresDSN)
  53. if err != nil {
  54. return err
  55. }
  56. defer pool.Close()
  57. // Verify the migration is applied (graceful if not — first boot
  58. // may need to run `go run ./cmd/seed` first).
  59. if err := pingSchema(ctx, pool); err != nil {
  60. logger.Warn("auth schema not yet present, login will fail", "err", err)
  61. }
  62. // Generate a JWT secret if not provided. The first-run case
  63. // (no env) gets a random secret written to a file so restarts
  64. // produce the same tokens. This is dev-only behavior; in
  65. // production the secret comes from K8s sealed-secrets.
  66. if len(cfg.JWTSecret) < 32 {
  67. if !cfg.AllowGeneratedSecret {
  68. return errors.New("BA_AUTHD_JWT_SECRET must be at least 32 bytes (set in env or sealed-secret)")
  69. }
  70. sec, err := loadOrCreateSecret(cfg.SecretFile, logger)
  71. if err != nil {
  72. return err
  73. }
  74. cfg.JWTSecret = sec
  75. }
  76. ad, err := authd.New(pool, cfg.AuthdConfig)
  77. if err != nil {
  78. return err
  79. }
  80. reg, _ := observability.NewRegistry("authd")
  81. srv := httpserver.New(httpserver.Config{
  82. Addr: cfg.HTTPAddr,
  83. ServiceName: "authd",
  84. }, logger, observability.MetricsHandler(reg))
  85. mux := srv.Mux()
  86. mux.HandleFunc("POST /v1/auth/login", loginHandler(ad, logger))
  87. mux.HandleFunc("POST /v1/auth/refresh", refreshHandler(ad, logger))
  88. mux.HandleFunc("POST /v1/auth/logout", logoutHandler(ad, logger))
  89. mux.HandleFunc("POST /v1/auth/magic", magicConsumeHandler(ad, logger))
  90. mux.Handle("POST /v1/users/invite", ad.RequireRole("super_admin", "tenant_admin")(inviteHandler(ad, logger)))
  91. mux.Handle("GET /v1/users/me", ad.RequireAuth(meHandler(ad, logger)))
  92. // M13b W1: Tenant (company) CRUD. See cmd/authd/tenants.go.
  93. // GET /v1/tenants — any auth (scope: super_admin sees all, others see own)
  94. // POST /v1/tenants — super_admin only
  95. // GET /v1/tenants/{id} — any auth (per-id scope check in handler)
  96. // PATCH /v1/tenants/{id} — any auth (per-id scope + field scope in handler)
  97. // POST /v1/tenants/{id}/status — super_admin only
  98. mux.Handle("GET /v1/tenants", ad.RequireAuth(listTenantsHandler(ad, logger)))
  99. mux.Handle("POST /v1/tenants", ad.RequireRole("super_admin")(createTenantHandler(ad, logger)))
  100. mux.Handle("GET /v1/tenants/{id}", ad.RequireAuth(getTenantHandler(ad, logger)))
  101. mux.Handle("PATCH /v1/tenants/{id}", ad.RequireAuth(updateTenantHandler(ad, logger)))
  102. mux.Handle("POST /v1/tenants/{id}/status", ad.RequireRole("super_admin")(setTenantStatusHandler(ad, logger)))
  103. // Start in background, wait for signal, then graceful shutdown.
  104. errCh := make(chan error, 1)
  105. go func() { errCh <- srv.Start() }()
  106. select {
  107. case err := <-errCh:
  108. return err
  109. case <-ctx.Done():
  110. logger.Info("shutdown signal received")
  111. shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
  112. defer cancel()
  113. return srv.Shutdown(shutdownCtx)
  114. }
  115. }
  116. // ---------------------------------------------------------------------------
  117. // Env loading
  118. // ---------------------------------------------------------------------------
  119. type env struct {
  120. Env string
  121. HTTPAddr string
  122. Issuer string
  123. AuthdConfig authd.Config
  124. PostgresDSN string
  125. ShutdownGrace time.Duration
  126. // JWT secret
  127. JWTSecret []byte
  128. AllowGeneratedSecret bool
  129. SecretFile string
  130. }
  131. func authdEnv() (env, error) {
  132. e := env{
  133. Env: getenvDefault("BA_ENV", "dev"),
  134. HTTPAddr: getenvDefault("BA_AUTHD_HTTP_ADDR", ":8804"),
  135. Issuer: getenvDefault("BA_AUTHD_ISSUER", "broad-announce"),
  136. PostgresDSN: os.Getenv("BA_POSTGRES_DSN"),
  137. }
  138. if s := os.Getenv("BA_AUTHD_JWT_SECRET"); s != "" {
  139. e.JWTSecret = []byte(s)
  140. }
  141. e.AllowGeneratedSecret = getenvDefault("BA_AUTHD_ALLOW_GENERATED_SECRET", "") == "1" ||
  142. os.Getenv("BA_ENV") == "dev"
  143. e.SecretFile = getenvDefault("BA_AUTHD_SECRET_FILE", "/var/run/broad-announce/authd.jwt")
  144. if t := os.Getenv("BA_AUTHD_ACCESS_TTL"); t != "" {
  145. d, err := time.ParseDuration(t)
  146. if err != nil {
  147. return e, err
  148. }
  149. e.AuthdConfig.AccessTokenTTL = d
  150. }
  151. if t := os.Getenv("BA_AUTHD_REFRESH_TTL"); t != "" {
  152. d, err := time.ParseDuration(t)
  153. if err != nil {
  154. return e, err
  155. }
  156. e.AuthdConfig.RefreshTokenTTL = d
  157. }
  158. if c := os.Getenv("BA_AUTHD_BCRYPT_COST"); c != "" {
  159. n, err := strconv.Atoi(c)
  160. if err != nil {
  161. return e, err
  162. }
  163. e.AuthdConfig.BcryptCost = n
  164. }
  165. e.AuthdConfig.JWTSecret = e.JWTSecret // may be empty; New() will reject
  166. e.AuthdConfig.Issuer = e.Issuer
  167. if e.PostgresDSN == "" {
  168. return e, errors.New("BA_POSTGRES_DSN must be set")
  169. }
  170. grace := 10 * time.Second
  171. if g := os.Getenv("BA_AUTHD_SHUTDOWN_GRACE"); g != "" {
  172. d, err := time.ParseDuration(g)
  173. if err != nil {
  174. return e, err
  175. }
  176. grace = d
  177. }
  178. e.ShutdownGrace = grace
  179. return e, nil
  180. }
  181. func getenvDefault(k, def string) string {
  182. if v := os.Getenv(k); v != "" {
  183. return v
  184. }
  185. return def
  186. }
  187. // pingSchema is a best-effort check that the auth schema is migrated.
  188. // Returns nil if the audit_log table exists, an error otherwise.
  189. func pingSchema(ctx context.Context, pool *postgres.Pool) error {
  190. row := pool.QueryRow(ctx,
  191. `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema='auth' AND table_name='users')`)
  192. var ok bool
  193. if err := row.Scan(&ok); err != nil {
  194. return err
  195. }
  196. if !ok {
  197. return errors.New("auth.users not found; run migrations first")
  198. }
  199. return nil
  200. }
  201. // loadOrCreateSecret reads the JWT secret from disk, or generates a
  202. // random one and writes it. The file is chmod 600.
  203. func loadOrCreateSecret(path string, logger *slog.Logger) ([]byte, error) {
  204. if data, err := os.ReadFile(path); err == nil && len(data) >= 32 {
  205. return data, nil
  206. }
  207. logger.Warn("generating new JWT secret (dev-only)", "file", path)
  208. if err := os.MkdirAll(parentDir(path), 0o700); err != nil {
  209. return nil, err
  210. }
  211. secret := make([]byte, 48)
  212. if _, err := readFull(secret); err != nil {
  213. return nil, err
  214. }
  215. if err := os.WriteFile(path, secret, 0o600); err != nil {
  216. return nil, err
  217. }
  218. return secret, nil
  219. }
  220. // readFull fills b with cryptographically random bytes.
  221. func readFull(b []byte) (int, error) {
  222. return randomRead(b)
  223. }
  224. func parentDir(p string) string {
  225. for i := len(p) - 1; i >= 0; i-- {
  226. if p[i] == '/' {
  227. return p[:i]
  228. }
  229. }
  230. return "."
  231. }
  232. // randomRead is split out so tests can stub it; default uses crypto/rand.
  233. var randomRead = func(b []byte) (int, error) {
  234. return cryptorand.Read(b)
  235. }
  236. // ---------------------------------------------------------------------------
  237. // HTTP handlers
  238. // ---------------------------------------------------------------------------
  239. // clientIP pulls the IP from r.RemoteAddr, respecting X-Forwarded-For
  240. // when BA_AUTHD_TRUST_FORWARDED=1. Returns the bare IP (no port)
  241. // because the audit_log columns are INET.
  242. func clientIP(r *http.Request) string {
  243. raw := r.RemoteAddr
  244. if os.Getenv("BA_AUTHD_TRUST_FORWARDED") == "1" {
  245. if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
  246. // X-Forwarded-For is a list; first is the client
  247. if i := indexByte(xff, ','); i >= 0 {
  248. raw = xff[:i]
  249. } else {
  250. raw = xff
  251. }
  252. }
  253. }
  254. // Strip :port if present (host:port)
  255. if i := lastByte(raw, ':'); i >= 0 {
  256. // Make sure it's not part of an IPv6 address
  257. if !containsByte(raw, ']') || i > indexByte(raw, ']') {
  258. raw = raw[:i]
  259. }
  260. }
  261. return raw
  262. }
  263. func indexByte(s string, c byte) int {
  264. for i := 0; i < len(s); i++ {
  265. if s[i] == c {
  266. return i
  267. }
  268. }
  269. return -1
  270. }
  271. func lastByte(s string, c byte) int {
  272. for i := len(s) - 1; i >= 0; i-- {
  273. if s[i] == c {
  274. return i
  275. }
  276. }
  277. return -1
  278. }
  279. func containsByte(s string, c byte) bool {
  280. return indexByte(s, c) >= 0
  281. }
  282. // writeJSON writes status + JSON body. Sets Content-Type.
  283. func writeJSON(w http.ResponseWriter, status int, body any) {
  284. w.Header().Set("Content-Type", "application/json")
  285. w.WriteHeader(status)
  286. _ = json.NewEncoder(w).Encode(body)
  287. }
  288. // writeErr writes a JSON error response.
  289. func writeErr(w http.ResponseWriter, status int, code, msg string) {
  290. writeJSON(w, status, map[string]string{"error": code, "message": msg})
  291. }
  292. // --- /v1/auth/login -------------------------------------------------------
  293. type loginReq struct {
  294. Email string `json:"email"`
  295. Password string `json:"password"`
  296. }
  297. type loginResp struct {
  298. AccessToken string `json:"access_token"`
  299. RefreshToken string `json:"refresh_token"`
  300. TokenType string `json:"token_type"`
  301. ExpiresAt time.Time `json:"expires_at"`
  302. UserID string `json:"user_id"`
  303. TenantID string `json:"tenant_id,omitempty"`
  304. Role string `json:"role"`
  305. }
  306. func loginHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  307. return func(w http.ResponseWriter, r *http.Request) {
  308. var req loginReq
  309. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  310. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  311. return
  312. }
  313. if req.Email == "" || req.Password == "" {
  314. writeErr(w, http.StatusBadRequest, "bad_request", "email and password required")
  315. return
  316. }
  317. res, err := ad.Login(r.Context(), req.Email, req.Password, clientIP(r), r.UserAgent())
  318. if err != nil {
  319. if errors.Is(err, authd.ErrInvalidCredentials) || errors.Is(err, authd.ErrUserDisabled) {
  320. writeErr(w, http.StatusUnauthorized, "unauthorized", "invalid credentials")
  321. return
  322. }
  323. logger.Error("login internal error", "err", err)
  324. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  325. return
  326. }
  327. writeJSON(w, http.StatusOK, loginResp{
  328. AccessToken: res.AccessToken,
  329. RefreshToken: res.RefreshToken,
  330. TokenType: "Bearer",
  331. ExpiresAt: res.ExpiresAt,
  332. UserID: res.UserID,
  333. TenantID: res.TenantID,
  334. Role: res.Role,
  335. })
  336. }
  337. }
  338. // --- /v1/auth/refresh -----------------------------------------------------
  339. type refreshReq struct {
  340. RefreshToken string `json:"refresh_token"`
  341. }
  342. func refreshHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  343. return func(w http.ResponseWriter, r *http.Request) {
  344. var req refreshReq
  345. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  346. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  347. return
  348. }
  349. if req.RefreshToken == "" {
  350. writeErr(w, http.StatusBadRequest, "bad_request", "refresh_token required")
  351. return
  352. }
  353. res, err := ad.Refresh(r.Context(), req.RefreshToken, clientIP(r), r.UserAgent())
  354. if err != nil {
  355. if errors.Is(err, authd.ErrTokenReuse) {
  356. writeErr(w, http.StatusUnauthorized, "session_killed", "refresh token re-use detected, please log in again")
  357. return
  358. }
  359. if errors.Is(err, authd.ErrUserDisabled) {
  360. writeErr(w, http.StatusUnauthorized, "unauthorized", "user disabled")
  361. return
  362. }
  363. logger.Error("refresh internal error", "err", err)
  364. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  365. return
  366. }
  367. writeJSON(w, http.StatusOK, loginResp{
  368. AccessToken: res.AccessToken,
  369. RefreshToken: res.RefreshToken,
  370. TokenType: "Bearer",
  371. ExpiresAt: res.ExpiresAt,
  372. UserID: res.UserID,
  373. TenantID: res.TenantID,
  374. Role: res.Role,
  375. })
  376. }
  377. }
  378. // --- /v1/auth/logout ------------------------------------------------------
  379. type logoutReq struct {
  380. RefreshToken string `json:"refresh_token"`
  381. }
  382. func logoutHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  383. return func(w http.ResponseWriter, r *http.Request) {
  384. var req logoutReq
  385. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  386. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  387. return
  388. }
  389. // Resolve user id from the access JWT in the Authorization
  390. // header (best effort — logout is allowed without a valid
  391. // token so a user with a dead access can still kill their
  392. // refresh). If no claims, audit logs "user_id=''".
  393. uid := ""
  394. if c := authd.ClaimsFromContext(r.Context()); c != nil {
  395. uid = c.UserID
  396. }
  397. if err := ad.Logout(r.Context(), req.RefreshToken, uid, clientIP(r), r.UserAgent()); err != nil {
  398. logger.Error("logout internal error", "err", err)
  399. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  400. return
  401. }
  402. writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
  403. }
  404. }
  405. // --- /v1/auth/magic -------------------------------------------------------
  406. type magicReq struct {
  407. Token string `json:"token"`
  408. NewPassword string `json:"new_password"`
  409. }
  410. func magicConsumeHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  411. return func(w http.ResponseWriter, r *http.Request) {
  412. var req magicReq
  413. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  414. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  415. return
  416. }
  417. if req.Token == "" || req.NewPassword == "" {
  418. writeErr(w, http.StatusBadRequest, "bad_request", "token and new_password required")
  419. return
  420. }
  421. if len(req.NewPassword) < 12 {
  422. writeErr(w, http.StatusBadRequest, "weak_password", "password must be at least 12 characters")
  423. return
  424. }
  425. uid, err := ad.ConsumeMagicLink(r.Context(), req.Token, clientIP(r), r.UserAgent())
  426. if err != nil {
  427. if errors.Is(err, authd.ErrMagicLinkInvalid) {
  428. writeErr(w, http.StatusUnauthorized, "invalid_link", "magic link invalid or expired")
  429. return
  430. }
  431. logger.Error("magic consume error", "err", err)
  432. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  433. return
  434. }
  435. if err := ad.SetPassword(r.Context(), uid, req.NewPassword); err != nil {
  436. logger.Error("set password error", "err", err)
  437. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  438. return
  439. }
  440. // Auto-login: return a session so the user lands on the
  441. // dashboard without a separate login round-trip.
  442. user, err := ad.Store().GetUserByID(r.Context(), uid)
  443. if err != nil {
  444. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  445. return
  446. }
  447. // We don't have the plaintext password to call Login(). The
  448. // simpler path: sign a session directly using a helper.
  449. // For now, return success and require the user to log in
  450. // normally — UX is one extra click, security is cleaner.
  451. _ = user
  452. writeJSON(w, http.StatusOK, map[string]any{
  453. "status": "ok",
  454. "user_id": uid,
  455. "message": "password set. Please log in.",
  456. })
  457. }
  458. }
  459. // --- /v1/users/invite -----------------------------------------------------
  460. type inviteReq struct {
  461. TenantSlug string `json:"tenant_slug"`
  462. Email string `json:"email"`
  463. Role string `json:"role"`
  464. }
  465. type inviteResp struct {
  466. UserID string `json:"user_id"`
  467. MagicLinkToken string `json:"magic_link_token"`
  468. ExpiresAt time.Time `json:"expires_at"`
  469. }
  470. func inviteHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  471. return func(w http.ResponseWriter, r *http.Request) {
  472. claims := authd.ClaimsFromContext(r.Context())
  473. if claims == nil {
  474. // Should never happen — RequireAuth/RequireRole ensured
  475. // this. Belt-and-suspenders.
  476. writeErr(w, http.StatusUnauthorized, "unauthorized", "claims missing")
  477. return
  478. }
  479. var req inviteReq
  480. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  481. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  482. return
  483. }
  484. if req.Email == "" || req.Role == "" {
  485. writeErr(w, http.StatusBadRequest, "bad_request", "email and role required")
  486. return
  487. }
  488. // Resolve tenant: super_admin can target any tenant by slug;
  489. // tenant_admin can only target their own tenant.
  490. var (
  491. tenantID string
  492. err error
  493. )
  494. if claims.Role == "super_admin" {
  495. if req.TenantSlug == "" {
  496. writeErr(w, http.StatusBadRequest, "bad_request", "tenant_slug required for super_admin")
  497. return
  498. }
  499. tenantID, err = ad.Store().TenantIDBySlug(r.Context(), req.TenantSlug)
  500. if err != nil {
  501. writeErr(w, http.StatusBadRequest, "unknown_tenant", "tenant_slug not found")
  502. return
  503. }
  504. } else {
  505. tenantID = claims.TenantID
  506. }
  507. token, uid, err := ad.InviteUser(r.Context(), tenantID, req.Email, req.Role, claims.UserID, clientIP(r), r.UserAgent())
  508. if err != nil {
  509. logger.Error("invite error", "err", err)
  510. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  511. return
  512. }
  513. writeJSON(w, http.StatusOK, inviteResp{
  514. UserID: uid,
  515. MagicLinkToken: token,
  516. })
  517. }
  518. }
  519. // --- /v1/users/me ---------------------------------------------------------
  520. func meHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  521. return func(w http.ResponseWriter, r *http.Request) {
  522. claims := authd.ClaimsFromContext(r.Context())
  523. if claims == nil {
  524. writeErr(w, http.StatusUnauthorized, "unauthorized", "claims missing")
  525. return
  526. }
  527. u, err := ad.Store().GetUserByID(r.Context(), claims.UserID)
  528. if err != nil {
  529. writeErr(w, http.StatusInternalServerError, "internal", "user lookup failed")
  530. return
  531. }
  532. writeJSON(w, http.StatusOK, map[string]any{
  533. "user_id": u.ID,
  534. "email": u.Email,
  535. "role": u.Role,
  536. "status": u.Status,
  537. "tenant_id": u.TenantID,
  538. "display_name": u.DisplayName,
  539. })
  540. }
  541. }