mirror change from https://github.com/binhkid2/FullStack-Blog-Nestjs-Nextjs-Postgres
This commit is contained in:
9
backend/src/common/decorators/current-user.decorator.ts
Normal file
9
backend/src/common/decorators/current-user.decorator.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(data: string | undefined, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
return data ? user?.[data] : user;
|
||||
},
|
||||
);
|
||||
4
backend/src/common/decorators/public.decorator.ts
Normal file
4
backend/src/common/decorators/public.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
5
backend/src/common/decorators/roles.decorator.ts
Normal file
5
backend/src/common/decorators/roles.decorator.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { UserRole } from '../../users/entities/user.entity';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: UserRole[]) => SetMetadata(ROLES_KEY, roles);
|
||||
44
backend/src/common/filters/all-exceptions.filter.ts
Normal file
44
backend/src/common/filters/all-exceptions.filter.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
@Catch()
|
||||
export class AllExceptionsFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(AllExceptionsFilter.name);
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const res = ctx.getResponse<Response>();
|
||||
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let message = 'Internal server error';
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const responseBody = exception.getResponse();
|
||||
if (typeof responseBody === 'string') {
|
||||
message = responseBody;
|
||||
} else if (typeof responseBody === 'object' && responseBody !== null) {
|
||||
const body = responseBody as any;
|
||||
message = body.message || body.error || message;
|
||||
if (Array.isArray(message)) {
|
||||
message = message[0];
|
||||
}
|
||||
}
|
||||
} else if (exception instanceof Error) {
|
||||
message = exception.message;
|
||||
this.logger.error(exception.message, exception.stack);
|
||||
}
|
||||
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: { code: status, message },
|
||||
});
|
||||
}
|
||||
}
|
||||
54
backend/src/common/guards/jwt-auth.guard.ts
Normal file
54
backend/src/common/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
import { verifyAccessToken } from '../helpers/jwt.helper';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private configService: ConfigService,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) return true;
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractToken(request);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Missing authentication token');
|
||||
}
|
||||
|
||||
try {
|
||||
const secret = this.configService.get<string>('JWT_ACCESS_SECRET');
|
||||
const payload = verifyAccessToken(token, secret);
|
||||
request.user = payload;
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Invalid or expired token');
|
||||
}
|
||||
}
|
||||
|
||||
private extractToken(request: any): string | null {
|
||||
// Check Authorization header
|
||||
const authHeader = request.headers?.authorization as string;
|
||||
if (authHeader?.startsWith('Bearer ')) {
|
||||
return authHeader.substring(7);
|
||||
}
|
||||
// Check cookie
|
||||
if (request.cookies?.accessToken) {
|
||||
return request.cookies.accessToken;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
44
backend/src/common/guards/roles.guard.ts
Normal file
44
backend/src/common/guards/roles.guard.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
import { UserRole } from '../../users/entities/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) return true;
|
||||
|
||||
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (!requiredRoles || requiredRoles.length === 0) return true;
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
|
||||
if (!user) {
|
||||
throw new ForbiddenException('Access denied');
|
||||
}
|
||||
|
||||
if (!requiredRoles.includes(user.role)) {
|
||||
throw new ForbiddenException(
|
||||
`Access denied. Required roles: ${requiredRoles.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
46
backend/src/common/helpers/jwt.helper.ts
Normal file
46
backend/src/common/helpers/jwt.helper.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as crypto from 'crypto';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
|
||||
export interface AccessTokenPayload {
|
||||
sub: string;
|
||||
email: string;
|
||||
role: string;
|
||||
type: 'access';
|
||||
}
|
||||
|
||||
export interface RefreshTokenPayload {
|
||||
sub: string;
|
||||
type: 'refresh';
|
||||
}
|
||||
|
||||
export function signAccessToken(
|
||||
payload: Omit<AccessTokenPayload, 'type'>,
|
||||
secret: string,
|
||||
expiresIn: string,
|
||||
): string {
|
||||
return jwt.sign({ ...payload, type: 'access' }, secret, { expiresIn } as any);
|
||||
}
|
||||
|
||||
export function signRefreshToken(
|
||||
payload: Omit<RefreshTokenPayload, 'type'>,
|
||||
secret: string,
|
||||
expiresIn: string,
|
||||
): string {
|
||||
return jwt.sign({ ...payload, type: 'refresh' }, secret, { expiresIn } as any);
|
||||
}
|
||||
|
||||
export function verifyAccessToken(token: string, secret: string): AccessTokenPayload {
|
||||
return jwt.verify(token, secret) as AccessTokenPayload;
|
||||
}
|
||||
|
||||
export function verifyRefreshToken(token: string, secret: string): RefreshTokenPayload {
|
||||
return jwt.verify(token, secret) as RefreshTokenPayload;
|
||||
}
|
||||
|
||||
export function hashToken(raw: string): string {
|
||||
return crypto.createHash('sha256').update(raw).digest('hex');
|
||||
}
|
||||
|
||||
export function generateRawToken(): string {
|
||||
return crypto.randomBytes(48).toString('hex');
|
||||
}
|
||||
45
backend/src/common/helpers/mailer.helper.ts
Normal file
45
backend/src/common/helpers/mailer.helper.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import * as nodemailer from 'nodemailer';
|
||||
|
||||
export interface MailOptions {
|
||||
to: string;
|
||||
subject: string;
|
||||
html: string;
|
||||
}
|
||||
|
||||
let transporter: nodemailer.Transporter | null = null;
|
||||
|
||||
function getTransporter(): nodemailer.Transporter {
|
||||
if (transporter) return transporter;
|
||||
|
||||
const host = process.env.SMTP_HOST;
|
||||
if (!host) {
|
||||
// Console fallback for development
|
||||
transporter = nodemailer.createTransport({ jsonTransport: true });
|
||||
return transporter;
|
||||
}
|
||||
|
||||
transporter = nodemailer.createTransport({
|
||||
host,
|
||||
port: parseInt(process.env.SMTP_PORT || '587', 10),
|
||||
auth: {
|
||||
user: process.env.SMTP_USER,
|
||||
pass: process.env.SMTP_PASS,
|
||||
},
|
||||
});
|
||||
return transporter;
|
||||
}
|
||||
|
||||
export async function sendMail(options: MailOptions): Promise<void> {
|
||||
const from = process.env.MAIL_FROM || 'no-reply@blog.local';
|
||||
const t = getTransporter();
|
||||
|
||||
if (!process.env.SMTP_HOST) {
|
||||
console.log('[MAIL CONSOLE FALLBACK]');
|
||||
console.log(` TO: ${options.to}`);
|
||||
console.log(` SUBJECT: ${options.subject}`);
|
||||
console.log(` BODY: ${options.html}`);
|
||||
return;
|
||||
}
|
||||
|
||||
await t.sendMail({ from, ...options });
|
||||
}
|
||||
14
backend/src/common/helpers/slug.helper.ts
Normal file
14
backend/src/common/helpers/slug.helper.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
export function generateSlug(title: string): string {
|
||||
const base = title
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^\w\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.substring(0, 200);
|
||||
|
||||
const suffix = uuidv4().split('-')[0]; // 8-char UUID segment
|
||||
return `${base}-${suffix}`;
|
||||
}
|
||||
60
backend/src/common/middleware/csrf.middleware.ts
Normal file
60
backend/src/common/middleware/csrf.middleware.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { ForbiddenException, Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
const EXEMPT_PATHS = [
|
||||
'/auth/login',
|
||||
'/auth/register',
|
||||
'/auth/magic-link',
|
||||
'/auth/refresh',
|
||||
'/auth/google',
|
||||
'/auth/google/callback',
|
||||
'/auth/password-reset',
|
||||
'/health',
|
||||
];
|
||||
|
||||
const STATE_CHANGING_METHODS = ['POST', 'PATCH', 'PUT', 'DELETE'];
|
||||
|
||||
@Injectable()
|
||||
export class CsrfMiddleware implements NestMiddleware {
|
||||
use(req: Request, res: Response, next: NextFunction) {
|
||||
// Read or generate CSRF token
|
||||
let csrfToken: string = req.cookies?.csrfToken;
|
||||
if (!csrfToken) {
|
||||
csrfToken = crypto.randomBytes(24).toString('hex');
|
||||
}
|
||||
|
||||
// Set as non-httpOnly cookie so JS can read it
|
||||
// SameSite=none required for cross-subdomain (frontend ↔ backend on different subdomains)
|
||||
const secure = process.env.COOKIE_SECURE === 'true';
|
||||
const domain = process.env.COOKIE_DOMAIN || undefined;
|
||||
const sameSite = secure ? ('none' as const) : ('lax' as const);
|
||||
res.cookie('csrfToken', csrfToken, {
|
||||
httpOnly: false,
|
||||
sameSite,
|
||||
secure,
|
||||
domain,
|
||||
});
|
||||
|
||||
(req as any).csrfToken = csrfToken;
|
||||
|
||||
// Validate on state-changing methods
|
||||
if (STATE_CHANGING_METHODS.includes(req.method)) {
|
||||
const isExempt = EXEMPT_PATHS.some((p) => req.path.startsWith(p));
|
||||
if (!isExempt) {
|
||||
const hasCookieAuth =
|
||||
req.cookies?.accessToken || req.cookies?.refreshToken;
|
||||
if (hasCookieAuth) {
|
||||
const tokenFromHeader = req.headers['x-csrf-token'] as string;
|
||||
const tokenFromBody = (req.body as any)?._csrf;
|
||||
const provided = tokenFromHeader || tokenFromBody;
|
||||
if (!provided || provided !== csrfToken) {
|
||||
throw new ForbiddenException('Invalid CSRF token');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user