main.go 21 KB

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