authHelper
Workspace API / helpers/authHelper
helpers/authHelper
Interfaces
GetRequestOrganizationIdOptions
Defined in: helpers/authHelper.ts:428
Options for getRequestOrganizationId helper function
Properties
required?
optionalrequired:boolean
Defined in: helpers/authHelper.ts:433
If true, throw error when organization ID cannot be determined
Default
false
checkBody?
optionalcheckBody:boolean
Defined in: helpers/authHelper.ts:438
If true, check request body for organizationId (for POST/PUT requests)
Default
false
allowServiceAccount?
optionalallowServiceAccount:boolean
Defined in: helpers/authHelper.ts:443
If true, allow service accounts (they must provide organizationId explicitly)
Default
true
Variables
JWT_SESSION_EXPIRES_IN
constJWT_SESSION_EXPIRES_IN:string
Defined in: helpers/authHelper.ts:26
JWT session token expiration duration (default: 1 day)
JWT_REFRESH_TOKEN_EXPIRES_IN
constJWT_REFRESH_TOKEN_EXPIRES_IN:string
Defined in: helpers/authHelper.ts:28
JWT refresh token expiration duration (default: 7 days)
LOGIN_MFA_BYPASS_EXPIRES_IN
constLOGIN_MFA_BYPASS_EXPIRES_IN:string
Defined in: helpers/authHelper.ts:30
MFA bypass token expiration duration (default: 1 day)
LOGIN_MFA_BYPASS_COOKIE_MAX_AGE
constLOGIN_MFA_BYPASS_COOKIE_MAX_AGE:string
Defined in: helpers/authHelper.ts:32
MFA bypass cookie max age (default: 1 day)
Functions
parseDurationToMs()
parseDurationToMs(
duration):number
Defined in: helpers/authHelper.ts:46
Parse a duration string to milliseconds.
Parameters
duration
string
Duration string in format: number + unit (s/m/h/d)
Returns
number
Duration in milliseconds
Throws
Error if duration format is invalid
Example
parseDurationToMs('30m') // 1800000 (30 minutes)
parseDurationToMs('1d') // 86400000 (1 day)
parseDurationToMs('2h') // 7200000 (2 hours)
getExpirationDate()
getExpirationDate(
duration):Date
Defined in: helpers/authHelper.ts:77
Calculate an expiration date from a duration string.
Parameters
duration
string
Duration string (e.g., '1d', '7d', '24h')
Returns
Date
Date object representing the expiration time
generateSecureToken()
generateSecureToken():
string
Defined in: helpers/authHelper.ts:86
Generate a cryptographically secure random token.
Returns
string
64-character hex string (32 bytes)
generateToken()
generateToken(
userId,Promise<string>
Defined in: helpers/authHelper.ts:100
Generate a JWT access token for a user with their organization roles.
Fetches the user's organizations and roles from the database and embeds them in the token payload for stateless authorization.
Parameters
userId
string
User's unique identifier
email
string
User's email address
Returns
Promise<string>
Signed JWT access token
generateRefreshToken()
generateRefreshToken(
userId,Promise<string>
Defined in: helpers/authHelper.ts:153
Generate a JWT refresh token for a user with their organization roles.
Refresh tokens have a longer expiration than access tokens and are used to obtain new access tokens without re-authentication.
Parameters
userId
string
User's unique identifier
email
string
User's email address
Returns
Promise<string>
Signed JWT refresh token
verifyToken()
verifyToken(
token):JwtPayload|null
Defined in: helpers/authHelper.ts:202
Verify and decode a JWT access token.
Parameters
token
string
JWT token string to verify
Returns
JwtPayload | null
Decoded JWT payload if valid, null if invalid or expired
verifyRefreshToken()
verifyRefreshToken(
token):JwtPayload|null
Defined in: helpers/authHelper.ts:219
Verify and decode a JWT refresh token.
Parameters
token
string
JWT refresh token string to verify
Returns
JwtPayload | null
Decoded JWT payload if valid, null if invalid or expired
generateFingerprint()
generateFingerprint(
request):string
Defined in: helpers/authHelper.ts:247
Generate a client fingerprint for additional authentication security.
Creates a SHA-256 hash from browser headers to help detect token theft by binding tokens to specific client characteristics.
Parameters
request
FastifyRequest
Fastify request object
Returns
string
SHA-256 hash of client headers as hex string
setSecureCookies()
setSecureCookies(
options):void
Defined in: helpers/authHelper.ts:272
Set secure HTTP-only cookies for authentication tokens.
Sets three cookies:
- access_token: Short-lived session token (30 min)
- refresh_token: Long-lived refresh token (7 days, /auth path only)
- fingerprint: Client fingerprint for theft detection (7 days)
Parameters
options
Cookie configuration
reply
FastifyReply
Fastify reply object
accessToken
string
JWT access token
refreshToken
string
JWT refresh token
fingerprint
string
Client fingerprint hash
Returns
void
clearCookies()
clearCookies(
reply):void
Defined in: helpers/authHelper.ts:316
Clear all authentication cookies on logout.
Parameters
reply
FastifyReply
Fastify reply object
Returns
void
sendMfaCode()
sendMfaCode(
options,log):Promise<void>
Defined in: helpers/authHelper.ts:342
Send MFA verification code to user's email.
Silently handles email delivery failures to prevent login disruption. In production, consider implementing fallback delivery mechanisms.
Parameters
options
MFA code options
email
string
User's email address
code
string
Generated MFA code
userName?
string
Optional user's name for personalization
log
Logger = logger
Optional logger instance (defaults to main logger)
Returns
Promise<void>
extractToken()
extractToken(
request):string|null
Defined in: helpers/authHelper.ts:376
Extract Bearer token from Authorization header.
Parameters
request
FastifyRequest
Fastify request object
Returns
string | null
Token string if present and valid format, null otherwise
verifyAuth()
verifyAuth(
request,reply):Promise<void>
Defined in: helpers/authHelper.ts:398
Authentication middleware for Fastify route hooks.
Extracts and verifies JWT from Authorization header, attaches user payload to request object for use in route handlers.
Parameters
request
FastifyRequest
Fastify request object
reply
FastifyReply
Fastify reply object
Returns
Promise<void>
Sends 401 response if authentication fails
Example
// Use as preHandler hook
fastify.get('/protected', { preHandler: verifyAuth }, handler)
getRequestOrganizationId()
getRequestOrganizationId(
request,options):string|undefined
Defined in: helpers/authHelper.ts:472
Centralized helper to get organization ID from request with priority order:
- Query parameter organizationId (explicit selection)
- Body parameter organizationId (for POST/PUT, when checkBody: true)
- Request context organization_id (set by verifyAuth)
- First organization from JWT payload
Supports both user JWTs and service account tokens.
Parameters
request
FastifyRequest
Fastify request object (must have user attached by verifyAuth)
options
GetRequestOrganizationIdOptions = {}
Configuration options
Returns
string | undefined
Organization ID string or undefined if not found and not required
Throws
Error if required=true and organization ID cannot be determined
Examples
// Basic usage (GET request)
const orgId = getRequestOrganizationId(request)
// POST request with body check
const orgId = getRequestOrganizationId(request, { checkBody: true })
// Required organization ID
const orgId = getRequestOrganizationId(request, { required: true })