nestjs-guards-interceptors
БесплатноБез исполняемых скриптовНе проверенUse when nestJS guards and interceptors for auth, logging, and transformation. Use when implementing cross-cutting concerns.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
NestJS Guards and Interceptors
Master NestJS guards and interceptors for implementing authentication, authorization, logging, and request/response transformation.
Guards Fundamentals
Understanding CanActivate and ExecutionContext.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class BasicGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
return this.validateRequest(request);
}
private validateRequest(request: any): boolean {
// Simple validation logic
return !!request.headers.authorization;
}
}
// ExecutionContext provides context about current request
@Injectable()
export class ContextAwareGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
// Get HTTP context
const httpContext = context.switchToHttp();
const request = httpContext.getRequest();
const response = httpContext.getResponse();
// Get handler and class information
const handler = context.getHandler();
const controller = context.getClass();
console.log(`Handler: ${handler.name}`);
console.log(`Controller: ${controller.name}`);
return true;
}
}
// Usage in controller
import { Controller, Get, UseGuards } from '@nestjs/common';
@Controller('users')
@UseGuards(BasicGuard)
export class UserController {
@Get()
findAll() {
return [];
}
@Get('profile')
@UseGuards(ContextAwareGuard) // Method-level guard
getProfile() {
return { name: 'John' };
}
}
Authentication Guards
JWT, session, and API key authentication patterns.
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException('No token provided');
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: process.env.JWT_SECRET,
});
// Attach user to request
request['user'] = payload;
} catch {
throw new UnauthorizedException('Invalid token');
}
return true;
}
private extractTokenFromHeader(request: any): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
// Session-based authentication
@Injectable()
export class SessionAuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
if (!request.session || !request.session.userId) {
throw new UnauthorizedException('Not authenticated');
}
return true;
}
}
// API Key authentication
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private configService: ConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const apiKey = request.headers['x-api-key'];
if (!apiKey) {
throw new UnauthorizedException('API key required');
}
const validApiKey = this.configService.get('API_KEY');
if (apiKey !== validApiKey) {
throw new UnauthorizedException('Invalid API key');
}
return true;
}
}
// Multiple auth strategies
@Injectable()
export class MultiAuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
// Try JWT first
const token = this.extractTokenFromHeader(request);
if (token) {
try {
const payload = await this.jwtService.verifyAsync(token);
request['user'] = payload;
return true;
} catch {}
}
// Fall back to API key
const apiKey = request.headers['x-api-key'];
if (apiKey === this.configService.get('API_KEY')) {
return true;
}
throw new UnauthorizedException();
}
private extractTokenFromHeader(request: any): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
Role-Based Authorization Guards
RBAC patterns with decorators.
import { SetMetadata } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
// Define roles
export enum Role {
USER = 'user',
ADMIN = 'admin',
MODERATOR = 'moderator',
}
// Roles decorator
export const ROLES_KEY = 'rol
Установить nestjs-guards-interceptors в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadFAQ
Что делает скилл nestjs-guards-interceptors?
Use when nestJS guards and interceptors for auth, logging, and transformation. Use when implementing cross-cutting concerns.
Как установить скилл nestjs-guards-interceptors?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл nestjs-guards-interceptors запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic