Authentication API

Complete reference for the ctx.auth authentication interface.

Properties

PropertyTypeDescription
auth.user RO User | null Current authenticated user or null
auth.isAuthenticated RO boolean Whether user is logged in
auth.sessionId RO string | null Current session ID

Methods

auth.login
login(user: User): Promise<void>

Create a new session for the user and set the session cookie.

Parameters
NameTypeDescription
user User User object to log in
Example
const user = db.query('SELECT * FROM users WHERE email = ?', [email])[0];
const valid = await auth.verifyPassword(password, user.password_hash);

if (valid) {
  await auth.login(user);
  return ctx.redirect('/dashboard');
}
auth.logout
logout(): Promise<void>

Destroy the current session and clear the session cookie.

Example
await auth.logout();
return ctx.redirect('/');
auth.hashPassword
hashPassword(password: string): Promise<string>

Hash a password using Argon2id.

Parameters
NameTypeDescription
password string Plain text password
Returns: Promise<string> - Argon2id hash
Example
const hash = await auth.hashPassword('mypassword123');
db.run('INSERT INTO users (email, password_hash) VALUES (?, ?)', [email, hash]);
auth.verifyPassword
verifyPassword(password: string, hash: string): Promise<boolean>

Verify a password against an Argon2id hash.

Parameters
NameTypeDescription
password string Plain text password to verify
hash string Stored Argon2id hash
Returns: Promise<boolean> - True if password matches
Example
const valid = await auth.verifyPassword(inputPassword, user.password_hash);
if (!valid) {
  return { error: 'Invalid password' };
}
auth.hasRole
hasRole(role: string): boolean

Check if user has a specific role.

Parameters
NameTypeDescription
role string Role name to check
Returns: boolean - True if user has role
Example
if (!auth.hasRole('admin')) {
  return ctx.redirect('/');
}
auth.hasAnyRole
hasAnyRole(roles: string[]): boolean

Check if user has any of the specified roles.

Parameters
NameTypeDescription
roles string[] Array of role names
Returns: boolean - True if user has any role
Example
if (auth.hasAnyRole(['admin', 'editor', 'moderator'])) {
  // Show admin controls
}
auth.hasPermission
hasPermission(permission: string): boolean

Check if user has a specific permission.

Parameters
NameTypeDescription
permission string Permission name (e.g., 'posts:write')
Returns: boolean - True if user has permission
Example
if (!auth.hasPermission('posts:delete')) {
  return { error: 'You cannot delete posts' };
}