API Reference
Complete API documentation for the Auth module.
AuthProvider
Abstract base class for implementing authentication providers.
Class Definition
abstract class AuthProvider<U = unknown> {
public abstract validate(
request: Request,
params?: AuthTypes.MiddlewareOptions
): Promise<AuthTypes.ValidationResult<U>> | AuthTypes.ValidationResult<U>;
public abstract getCurrentUser(
request: Request
): Promise<U | null> | U | null;
}
Type Parameters
| Parameter | Description |
|---|---|
U | The type of the user object returned by validate() and getCurrentUser() |
Methods
validate()
Validates an incoming request for authentication.
public abstract validate(
request: Request,
params?: AuthTypes.MiddlewareOptions
): Promise<AuthTypes.ValidationResult<U>> | AuthTypes.ValidationResult<U>;
Parameters:
| Parameter | Type | Description |
|---|---|---|
request | Request | The incoming HTTP request object |
params | AuthTypes.MiddlewareOptions | Optional middleware options (e.g., required roles) |
Returns: Promise<AuthTypes.ValidationResult<U>> | AuthTypes.ValidationResult<U>
{ user }if authentication succeeds.@User()receives this user for the rest of the request{ error }with the error message if authentication fails
Returning an error string, or null on success, still works. @User() then has no user to receive and calls getCurrentUser(), so the user is loaded twice on routes with both decorators.
Example:
public validate(
request: Request,
params?: AuthTypes.MiddlewareOptions,
): AuthTypes.ValidationResult<User> {
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
if (!token) {
return { error: 'No token provided' };
}
try {
const user = jwt.verify(token, this.secret) as User;
if (params?.roles?.length) {
const hasRole = params.roles.some((role) => user.roles.includes(role));
if (!hasRole) {
return { error: 'Insufficient permissions' };
}
}
return { user };
} catch {
return { error: 'Invalid token' };
}
}
getCurrentUser()
Retrieves the currently authenticated user from the request. @User() skips it only when @Auth() with the same provider returned { user } earlier in the request. It is called otherwise: on a route without @Auth(), after a legacy null from validate(), or with requestContext: false, so every provider has to implement it.
public abstract getCurrentUser(
request: Request
): Promise<U | null> | U | null;
Parameters:
| Parameter | Type | Description |
|---|---|---|
request | Request | The incoming HTTP request object |
Returns: Promise<U | null> | U | null
- User object if authenticated
nullif not authenticated
Example:
public getCurrentUser(request: Request): User | null {
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
if (!token) {
return null;
}
try {
return jwt.verify(token, this.secret) as User;
} catch {
return null;
}
}
Decorators
@Auth()
Protects a controller method by requiring authentication.
function Auth(options?: AuthTypes.MiddlewareOptions): MethodDecorator
Parameters:
| Parameter | Type | Description |
|---|---|---|
options | AuthTypes.MiddlewareOptions | Optional authentication options |
Example:
@Get('/protected')
@Auth()
public protectedRoute() {}
@Get('/admin')
@Auth({ roles: ['admin'] })
public adminRoute() {}
@User()
Injects the current authenticated user into a method parameter.
function User(options?: UserDecoratorOptions): ParameterDecorator
Parameters:
| Parameter | Type | Description |
|---|---|---|
options | UserDecoratorOptions | Optional decorator options |
UserDecoratorOptions:
| Property | Type | Description |
|---|---|---|
provider | typeof AuthProvider | Custom auth provider to use |
Example:
@Get('/me')
public getMe(@User() user: User) {
return user;
}
@Get('/custom')
public getCustom(@User({ provider: CustomAuthProvider }) user: CustomUser) {
return user;
}
Types
AuthTypes.MiddlewareOptions
Options for the authentication middleware.
interface MiddlewareOptions {
roles?: string[];
provider?: typeof AuthProvider<any>;
}
| Property | Type | Description |
|---|---|---|
roles | string[] | Array of roles allowed to access the endpoint |
provider | typeof AuthProvider | Provider to use instead of the one bound as AuthProvider |
AuthTypes.ValidationResult
What validate() returns. string | null is the shape from before { user } and { error }, kept for existing providers.
type ValidationResult<U = unknown> = { user: U } | { error: string } | string | null;
Usage Examples
Complete JWT Provider
import { AuthProvider, type AuthTypes } from '@vercube/auth';
import jwt from 'jsonwebtoken';
interface JWTPayload {
id: number;
username: string;
email: string;
roles: string[];
iat: number;
exp: number;
}
export class JWTAuthProvider extends AuthProvider<JWTPayload> {
private readonly secret = process.env.JWT_SECRET!;
public validate(
request: Request,
params?: AuthTypes.MiddlewareOptions,
): AuthTypes.ValidationResult<JWTPayload> {
const authHeader = request.headers.get('Authorization');
if (!authHeader) {
return { error: 'Authorization header required' };
}
if (!authHeader.startsWith('Bearer ')) {
return { error: 'Invalid authorization format. Use: Bearer <token>' };
}
const token = authHeader.slice(7);
try {
const payload = jwt.verify(token, this.secret) as JWTPayload;
// Check roles if specified
if (params?.roles && params.roles.length > 0) {
const hasRequiredRole = params.roles.some((role) =>
payload.roles.includes(role),
);
if (!hasRequiredRole) {
return { error: 'Insufficient permissions' };
}
}
return { user: payload };
} catch (error) {
if (error instanceof jwt.TokenExpiredError) {
return { error: 'Token expired' };
}
if (error instanceof jwt.JsonWebTokenError) {
return { error: 'Invalid token' };
}
return { error: 'Authentication failed' };
}
}
public getCurrentUser(request: Request): JWTPayload | null {
const authHeader = request.headers.get('Authorization');
if (!authHeader?.startsWith('Bearer ')) {
return null;
}
const token = authHeader.slice(7);
try {
return jwt.verify(token, this.secret) as JWTPayload;
} catch {
return null;
}
}
}
Registration in Container
import { type App } from '@vercube/core';
import { AuthProvider } from '@vercube/auth';
import { JWTAuthProvider } from './providers/JWTAuthProvider';
export function setup(app: App): void {
// Bind JWTAuthProvider as the implementation for AuthProvider
app.container.bind(AuthProvider, JWTAuthProvider);
}
Controller with Authentication
import { Controller, Get, Post, Put, Delete } from '@vercube/core';
import { Auth, User } from '@vercube/auth';
interface User {
id: number;
username: string;
roles: string[];
}
@Controller('/api/resources')
export class ResourceController {
// Public endpoint - no authentication required
@Get('/public')
public getPublic() {
return { message: 'Public data' };
}
// Authenticated endpoint - any logged in user
@Get('/')
@Auth()
public getAll(@User() user: User) {
return {
requestedBy: user.username,
resources: []
};
}
// Role-protected endpoint - only admins
@Post('/')
@Auth({ roles: ['admin'] })
public create(@User() admin: User) {
return {
createdBy: admin.username,
success: true
};
}
// Multiple roles - admins OR moderators
@Delete('/:id')
@Auth({ roles: ['admin', 'moderator'] })
public delete(@User() user: User) {
return {
deletedBy: user.username,
success: true
};
}
}