main.go 20 KB

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