Overview

Apply JWT auth guard and optional roles in a single decorator.

Features

  • JWT + Roles combined
  • Swagger integration
  • AdminOnly shortcut
  • ModeratorOnly shortcut

Installation

npx hanma add auth --framework nest

Code

import { applyDecorators, UseGuards } from "@nestjs/common";
import { ApiBearerAuth, ApiUnauthorizedResponse, ApiForbiddenResponse } from "@nestjs/swagger";
import { JwtAuthGuard } from "../guards/jwt-auth.guard";
import { RolesGuard } from "../guards/roles.guard";
import { Roles, Role, ROLES_KEY } from "./roles.decorator";

/**
 * Combined authentication decorator.
 * Applies JWT authentication and optionally enforces roles.
 * 
 * Usage:
 * // Require authentication only
 * @Auth()
 * @Get("profile")
 * getProfile() {}
 * 
 * // Require authentication + specific role
 * @Auth(Role.ADMIN)
 * @Get("admin")
 * adminRoute() {}
 * 
 * // Multiple roles (any role grants access)
 * @Auth(Role.ADMIN, Role.MODERATOR)
 * @Get("staff")
 * staffRoute() {}
 */

 
export function Auth(...roles: Role[]) {
  const decorators = [
    UseGuards(JwtAuthGuard, RolesGuard),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({ description: "Unauthorized - Invalid or missing token" }),
  ];

  if (roles.length > 0) {
    decorators.push(
      Roles(...roles),
      ApiForbiddenResponse({ description: "Forbidden - Insufficient permissions" })
    );
  }

  return applyDecorators(...decorators);
}

/**
 * Admin-only routes shorthand.
 */
export function AdminOnly() {
  return Auth(Role.ADMIN, Role.SUPER_ADMIN);
}

/**
 * Moderator and above shorthand.
 */
export function ModeratorOnly() {
  return Auth(Role.MODERATOR, Role.ADMIN, Role.SUPER_ADMIN);
}

Usage

@Auth(Role.ADMIN)
@Get('admin')
adminRoute() {}

Dependencies

No external dependencies required.

Frequently Asked Questions

How do I install Auth Decorator?
Run the following command: npx hanma add auth --framework nest
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to src/decorators/auth.decorator.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.