API Reference

Complete API reference for the Vercube Auth module

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<string | null> | string | null;
  
  public abstract getCurrentUser(
    request: Request
  ): Promise<U | null> | U | null;
}

Type Parameters

ParameterDescription
UThe type of the user object returned by getCurrentUser()

Methods

validate()

Validates an incoming request for authentication.

public abstract validate(
  request: Request, 
  params?: AuthTypes.MiddlewareOptions
): Promise<string | null> | string | null;

Parameters:

ParameterTypeDescription
requestRequestThe incoming HTTP request object
paramsAuthTypes.MiddlewareOptionsOptional middleware options (e.g., required roles)

Returns: Promise<string | null> | string | null

  • null if authentication succeeds
  • Error message string if authentication fails

Example:

public validate(request: Request, params?: AuthTypes.MiddlewareOptions): string | null {
  const token = request.headers.get('Authorization')?.replace('Bearer ', '');
  
  if (!token) {
    return 'No token provided';
  }

  try {
    const user = jwt.verify(token, this.secret);
    
    if (params?.roles?.length) {
      const hasRole = params.roles.some(role => user.roles.includes(role));
      if (!hasRole) {
        return 'Insufficient permissions';
      }
    }
    
    return null;
  } catch {
    return 'Invalid token';
  }
}

getCurrentUser()

Retrieves the currently authenticated user from the request.

public abstract getCurrentUser(
  request: Request
): Promise<U | null> | U | null;

Parameters:

ParameterTypeDescription
requestRequestThe incoming HTTP request object

Returns: Promise<U | null> | U | null

  • User object if authenticated
  • null if 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:

ParameterTypeDescription
optionsAuthTypes.MiddlewareOptionsOptional 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:

ParameterTypeDescription
optionsUserDecoratorOptionsOptional decorator options

UserDecoratorOptions:

PropertyTypeDescription
providertypeof AuthProviderCustom 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[];
}
PropertyTypeDescription
rolesstring[]Array of roles allowed to access the endpoint

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): string | null {
    const authHeader = request.headers.get('Authorization');
    
    if (!authHeader) {
      return 'Authorization header required';
    }
    
    if (!authHeader.startsWith('Bearer ')) {
      return '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 'Insufficient permissions';
        }
      }
      
      return null;
    } catch (error) {
      if (error instanceof jwt.TokenExpiredError) {
        return 'Token expired';
      }
      if (error instanceof jwt.JsonWebTokenError) {
        return 'Invalid token';
      }
      return '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 
    };
  }
}
Previous

Overview

Flexible and extensible logging system for Vercube applications

Next