Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/commands/auth/logs/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,25 @@ export const logs_list: CommandModule<unknown, LogsListArgs> = {
return
}
log.info(`📜 ${page.data.length} entr${page.data.length === 1 ? 'y' : 'ies'}:`)
// The USER column: the resolved user when there is one; otherwise the
// identifier the person actually TYPED (`data.email`), marked `(tried)`.
// A failed login never resolves a user — that typed value is the whole
// point of the row (who was trying, with what address).
const user_cell = (entry: (typeof page.data)[number]): string => {
const resolved =
typeof entry.user === 'string'
? entry.user
: ((entry.user as { email?: string; id?: string } | undefined)?.email ??
(entry.user as { id?: string } | undefined)?.id)
if (resolved) return resolved
const tried = (entry.data as { email?: string } | undefined)?.email
return tried ? `${tried} (tried)` : '-'
}
const rows = page.data.map(entry => [
entry.createdAt ?? '-',
entry.type ?? '-',
log_status_badge(entry.status),
typeof entry.user === 'string'
? entry.user
: ((entry.user as { email?: string; id?: string } | undefined)?.email ??
(entry.user as { id?: string } | undefined)?.id ??
'-'),
user_cell(entry),
truncate(entry.message, 48),
entry.id ?? '-'
])
Expand Down
130 changes: 130 additions & 0 deletions src/commands/auth/users/diagnose.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { CommandModule } from 'yargs'
import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin'
import { fetch_page, from_paginator } from '../../../lib/listing'
import { log } from '../../../log'
import { TenantArgs, json_option, tenant_options } from '../options'
import { print_json } from '../render'

interface DiagnoseArgs extends TenantArgs {
identifier: string
}

type Cred = {
id: string
connection?: string
email?: string
username?: string
user?: string | { id?: string; email?: string }
}

const user_of = (c: Cred): { id?: string; email?: string } =>
typeof c.user === 'string' ? { id: c.user } : (c.user ?? {})

// Answers "why can't X log in?" from the identifier the person typed. The
// password login matches a CREDENTIAL identifier, not the profile email, so a
// login can fail for a reason get_auth_user alone does not show: the address
// they were given is simply not one any account logs in with. This resolves
// that in one call.
export const users_diagnose: CommandModule<unknown, DiagnoseArgs> = {
command: 'diagnose <identifier>',
describe: 'Explain why an email/username someone typed does (or does not) log in',
builder: yargs =>
json_option(tenant_options(yargs))
.positional('identifier', {
type: 'string',
demandOption: true,
description: 'The email or username the person is trying to log in with'
})
.example(
'$0 auth users diagnose jtamargo@med.ucm.es',
'Check whether that identifier logs in, and if not, what the account actually uses'
)
.showHelpOnFail(false) as any,
handler: withAuthHints(async args => {
const api = await requireAuthAdmin(args)
const id = args.identifier.trim()
const as_email = id.includes('@')
const needle = as_email ? id.toLowerCase() : id

const first = async (params: Record<string, unknown>): Promise<Cred[]> =>
fetch_page(from_paginator(api.credentialsList(params as never)), { limit: 20 })
.then(r => r.data as Cred[])
.catch(() => [])

// 1. Exact: does any database credential log in with this identifier?
const matches = await first({
...(as_email ? { email: needle } : { username: needle }),
expand: ['user']
})

// 2. If not, is it a user's PROFILE email while they log in with another
// identifier? (the trap: a right-looking email that is not the login.)
const profile_users = matches.length === 0 && as_email
? await fetch_page(from_paginator(api.userList({ email: needle } as never)), {
limit: 5
})
.then(r => r.data as Array<{ id: string; email?: string }>)
.catch(() => [])
: []
const alt_creds: Record<string, Cred[]> = {}
for (const u of profile_users) {
alt_creds[u.id] = await first({ user: u.id })
}

// 3. Fuzzy suggestions when nothing matched at all.
const suggestions =
matches.length === 0 && profile_users.length === 0
? await first({ q: as_email ? id.split('@')[0] : id })
: []

if (args.json) {
return print_json({
identifier: id,
logs_in: matches.length > 0,
matches: matches.map(c => ({
credential: c.id,
connection: c.connection,
identifier: c.email ?? c.username,
user: user_of(c)
})),
profile_email_only: profile_users.map(u => ({
user: u.id,
email: u.email,
login_identifiers: (alt_creds[u.id] ?? []).map(c => c.email ?? c.username)
})),
suggestions: suggestions.map(c => c.email ?? c.username).filter(Boolean)
})
}

log.info(`🔎 Diagnosing login for: ${id}`)
if (matches.length > 0) {
log.info('✅ This IS a login identifier. It signs in as:')
for (const c of matches) {
const u = user_of(c)
log.info(` ${u.email ?? u.id ?? '-'} (${u.id ?? '-'}) · connection ${c.connection ?? '-'}`)
}
log.info(' If login still fails, it is the password or a suspension — not the identifier.')
log.info(' Set a password: faable auth users set-password <user> --generate')
return
}

log.info(`❌ No account logs in with ${id}.`)
if (profile_users.length > 0) {
log.info('⚠️ But a user has it as their PROFILE email — they must log in with their identifier:')
for (const u of profile_users) {
const ids = (alt_creds[u.id] ?? []).map(c => c.email ?? c.username).filter(Boolean)
log.info(` ${u.email} → logs in with: ${ids.length ? ids.join(', ') : '(no database credential)'}`)
}
log.info(' Fix: tell them that identifier, or move it with: faable auth users update <user> --email ' + id)
return
}
if (suggestions.length > 0) {
log.info(' Did you mean one of these login identifiers?')
for (const c of suggestions.slice(0, 5)) {
log.info(` - ${c.email ?? c.username} (${user_of(c).email ?? user_of(c).id ?? '-'})`)
}
} else {
log.info(' No similar identifier found in this tenant.')
}
})
}
58 changes: 54 additions & 4 deletions src/commands/auth/users/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ type ProfileData = {

export const users_get: CommandModule<unknown, UsersGetArgs> = {
command: 'get <user_id>',
describe: 'Show a user (by id or email), including their federated identities',
describe:
'Show a user (by id or email), their federated identities and their database login identifiers',
builder: yargs =>
json_option(tenant_options(yargs))
.positional('user_id', {
Expand All @@ -59,10 +60,40 @@ export const users_get: CommandModule<unknown, UsersGetArgs> = {
.then(r => r.data.map(i => sanitize_identity(i as never)))
.catch(() => [] as Record<string, unknown>[])

// Resolve connection ids to names ("github") once per distinct id.
// Database-connection credentials: the email/username the user actually
// TYPES to log in. Distinct from `user.email` (the profile email), which
// is NOT what the password login matches — the gap that otherwise sends
// you to the dashboard to find out why a login keeps failing. Best-effort.
const credentials = await fetch_page(
from_paginator(api.credentialsList({ user: user_id })),
{ limit: 200, all: true }
)
.then(r =>
r.data.map(c => ({
id: String((c as { id?: unknown }).id ?? ''),
connection: String((c as { connection?: unknown }).connection ?? ''),
email: (c as { email?: string }).email,
username: (c as { username?: string }).username
}))
)
.catch(
() =>
[] as {
id: string
connection: string
email?: string
username?: string
}[]
)

// Resolve connection ids to names ("github", "default") once per distinct
// id — identities and credentials alike.
const connection_names = new Map<string, string>()
for (const id of new Set(
identities.map(i => String(i.connection ?? '')).filter(Boolean)
[
...identities.map(i => String(i.connection ?? '')),
...credentials.map(c => c.connection)
].filter(Boolean)
)) {
const conn = (await api.connectionGet(id).catch(() => null)) as {
connection_name?: string
Expand All @@ -74,11 +105,30 @@ export const users_get: CommandModule<unknown, UsersGetArgs> = {
)
}

if (args.json) return print_json({ ...user, identities })
if (args.json)
return print_json({
...user,
identities,
credentials: credentials.map(c => ({
...c,
connection_name: connection_names.get(c.connection) ?? c.connection
}))
})

log.info(`👤 ${user.id}`)
log.info(` Email: ${user.email ?? '-'} (verified: ${yes_no(user.email_verified)})`)
log.info(` Name: ${user.name ?? '-'}`)
if (credentials.length > 0) {
// What the user types at the password login — may differ from the
// profile email above, in which case that mismatch is the bug.
const ids = credentials
.map(c => {
const conn = connection_names.get(c.connection) ?? (c.connection || 'default')
return `${c.email ?? c.username ?? '-'} (${conn})`
})
.join(', ')
log.info(` Login IDs: ${ids}`)
}
if (user.phone) log.info(` Phone: ${user.phone}`)
if (user.country_iso) log.info(` Country: ${user.country_iso}`)
log.info(` Created: ${user.createdAt ?? '-'}`)
Expand Down
10 changes: 9 additions & 1 deletion src/commands/auth/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CommandModule } from 'yargs'
import { users_diagnose } from './diagnose'
import { users_export } from './export'
import { users_get } from './get'
import { users_import } from './import'
Expand All @@ -7,19 +8,26 @@ import { users_password_setup } from './password_setup'
import { users_permissions } from './permissions'
import { users_reinstate } from './reinstate'
import { users_roles } from './roles'
import { users_set_password } from './set_password'
import { users_suspend } from './suspend'
import { users_tickets } from './tickets'
import { users_update } from './update'

export const users: CommandModule = {
command: 'users',
describe:
'List, count, inspect, suspend, reinstate, import and export users, and manage their roles',
'List, count, inspect, update, suspend, reinstate, set passwords for, import and export users, and manage their roles',
builder: yargs =>
yargs
.command(users_list)
.command(users_get)
.command(users_diagnose)
.command(users_update)
.command(users_suspend)
.command(users_reinstate)
.command(users_set_password)
.command(users_password_setup)
.command(users_tickets)
.command(users_roles)
.command(users_permissions)
.command(users_import)
Expand Down
40 changes: 37 additions & 3 deletions src/commands/auth/users/password_setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { resolve_user_ref } from './resolve'
interface PasswordSetupArgs extends TenantArgs {
user: string
channel?: 'email' | 'sms' | 'whatsapp'
print?: boolean
yes?: boolean
}

Expand All @@ -29,12 +30,22 @@ export const users_password_setup: CommandModule<unknown, PasswordSetupArgs> = {
choices: ['email', 'sms', 'whatsapp'],
description: "How to deliver it (default: the tenant's)"
})
.option('print', {
type: 'boolean',
default: false,
description:
'Also print the recovery link, to hand it over by another channel when the email will not reach the person (email channel only)'
})
.option('yes', {
alias: 'y',
type: 'boolean',
default: false,
description: 'Skip the confirmation prompt'
})
.example(
'$0 auth users password-setup ana@example.com --print',
'Mint a reset link and print it (also sends the email)'
)
.showHelpOnFail(false) as any,
handler: withAuthHints(async args => {
// An email is resolved first (a read), so the prompt names one user; an
Expand All @@ -50,10 +61,33 @@ export const users_password_setup: CommandModule<unknown, PasswordSetupArgs> = {
return
}
const api = early ?? (await requireAuthAdmin(args))
const res = await api.userPasswordSetup(await resolve_user_ref(api, user_id), {
const id = await resolve_user_ref(api, user_id)
const res = await api.userPasswordSetup(id, {
...(args.channel ? { channel: args.channel } : {})
})
if (args.json) return print_json({ user_id, ...res })
log.info(`📨 Sent to ${args.user} (${(res as { channel?: string }).channel ?? 'email'}).`)
const channel = (res as { channel?: string }).channel ?? 'email'

// The setup response carries only the ticket id; the usable link lives on
// the ticket. Read it back when asked — the way to deliver a reset to
// someone whose mailbox does not receive (a login identifier that is not a
// real inbox). A link exists only for the email channel.
let link: string | undefined
if (args.print && channel === 'email') {
const ticket_id = (res as { ticket_id?: string }).ticket_id
const tickets = await api
.userListTickets(id)
.then(r => (r as { results?: Array<{ id: string; link?: string }> }).results ?? [])
.catch(() => [])
link = tickets.find(t => t.id === ticket_id)?.link ?? tickets.find(t => t.link)?.link
}

if (args.json) return print_json({ user_id: id, ...res, ...(link ? { link } : {}) })
log.info(`📨 Sent to ${args.user} (${channel}).`)
if (args.print) {
if (link) log.info(`🔗 ${link}`)
else if (channel === 'email')
log.info(' (link not available — it may already be consumed or expired)')
else log.info(` (no link: the ${channel} channel delivers a code, not a link)`)
}
})
}
Loading
Loading