|
| 1 | +/** |
| 2 | + * sentry auth whoami |
| 3 | + * |
| 4 | + * Display the currently authenticated user's identity by fetching live from |
| 5 | + * the /auth/ endpoint. Unlike `sentry auth status`, this command only shows |
| 6 | + * who you are — no token details, no defaults, no org verification. |
| 7 | + */ |
| 8 | + |
| 9 | +import type { SentryContext } from "../../context.js"; |
| 10 | +import { getCurrentUser } from "../../lib/api-client.js"; |
| 11 | +import { buildCommand } from "../../lib/command.js"; |
| 12 | +import { isAuthenticated } from "../../lib/db/auth.js"; |
| 13 | +import { setUserInfo } from "../../lib/db/user.js"; |
| 14 | +import { AuthError } from "../../lib/errors.js"; |
| 15 | +import { formatUserIdentity, writeJson } from "../../lib/formatters/index.js"; |
| 16 | + |
| 17 | +type WhoamiFlags = { |
| 18 | + readonly json: boolean; |
| 19 | +}; |
| 20 | + |
| 21 | +export const whoamiCommand = buildCommand({ |
| 22 | + docs: { |
| 23 | + brief: "Show the currently authenticated user", |
| 24 | + fullDescription: |
| 25 | + "Fetch and display the identity of the currently authenticated user.\n\n" + |
| 26 | + "This calls the Sentry API live (not cached) so the result always reflects " + |
| 27 | + "the current token. Works with all token types: OAuth, API tokens, and OAuth App tokens.", |
| 28 | + }, |
| 29 | + parameters: { |
| 30 | + flags: { |
| 31 | + json: { |
| 32 | + kind: "boolean", |
| 33 | + brief: "Output as JSON", |
| 34 | + default: false, |
| 35 | + }, |
| 36 | + }, |
| 37 | + }, |
| 38 | + async func(this: SentryContext, flags: WhoamiFlags): Promise<void> { |
| 39 | + const { stdout } = this; |
| 40 | + |
| 41 | + if (!(await isAuthenticated())) { |
| 42 | + throw new AuthError("not_authenticated"); |
| 43 | + } |
| 44 | + |
| 45 | + const user = await getCurrentUser(); |
| 46 | + |
| 47 | + // Keep cached user info up to date. Non-fatal: display must succeed even |
| 48 | + // if the DB write fails (read-only filesystem, corrupted database, etc.). |
| 49 | + try { |
| 50 | + setUserInfo({ |
| 51 | + userId: user.id, |
| 52 | + email: user.email, |
| 53 | + username: user.username, |
| 54 | + name: user.name, |
| 55 | + }); |
| 56 | + } catch { |
| 57 | + // Cache update failure is non-essential — user identity was already fetched. |
| 58 | + } |
| 59 | + |
| 60 | + if (flags.json) { |
| 61 | + writeJson(stdout, { |
| 62 | + id: user.id, |
| 63 | + name: user.name ?? null, |
| 64 | + username: user.username ?? null, |
| 65 | + email: user.email ?? null, |
| 66 | + }); |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + stdout.write(`${formatUserIdentity(user)}\n`); |
| 71 | + }, |
| 72 | +}); |
0 commit comments