- Removed unused permission and app retrieval logic from the login process. - Introduced a new endpoint for reissuing access tokens to handle role changes and account switches. - Updated JWT payload handling to improve clarity and maintainability. - Enhanced the readJwtPayload function for better decoding of JWT claims.
53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import type { FastifyInstance } from 'fastify'
|
|
import {
|
|
allPermissionKeys,
|
|
normalizePermissionKeys,
|
|
tenantsClaimForUser,
|
|
type LoginResponse,
|
|
} from '@authportal/shared'
|
|
import {
|
|
getAppSwitcherConfig,
|
|
getUserApps,
|
|
getUserPermissions,
|
|
type UserRow,
|
|
} from '@authportal/db'
|
|
import { toMe } from '../plugins/auth-guards.js'
|
|
|
|
/** Mint access JWT + Me from current DB state (login / reissue). */
|
|
export function issueAccessToken(
|
|
app: FastifyInstance,
|
|
user: UserRow,
|
|
): LoginResponse {
|
|
const apps = getUserApps(app.db, user.id)
|
|
let permissions = normalizePermissionKeys(getUserPermissions(app.db, user.id))
|
|
if (user.isAdmin) {
|
|
permissions = allPermissionKeys()
|
|
}
|
|
const switcher = getAppSwitcherConfig(app.db)
|
|
const tenants = tenantsClaimForUser(switcher, apps)
|
|
const me = toMe(user, apps, permissions)
|
|
const expiresAt = new Date(
|
|
Date.now() + app.config.jwtTtlHours * 60 * 60 * 1000,
|
|
)
|
|
const accessToken = app.jwt.sign(
|
|
{
|
|
sub: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
apps,
|
|
permissions,
|
|
tenants,
|
|
bgp_tenant_id: tenants.bgp,
|
|
is_admin: user.isAdmin,
|
|
iss: app.config.issuer,
|
|
},
|
|
{ expiresIn: `${app.config.jwtTtlHours}h` },
|
|
)
|
|
return {
|
|
access_token: accessToken,
|
|
expires_at: expiresAt.toISOString(),
|
|
token_type: 'Bearer',
|
|
user: me,
|
|
}
|
|
}
|