import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class OptionalCustomerJwtGuard extends AuthGuard('jwt') { canActivate(context: ExecutionContext) { const req = context.switchToHttp().getRequest(); const supplied = Object.prototype.hasOwnProperty.call(req.headers, 'authorization') || /(?:^|;\s*)accessToken=/.test(req.headers.cookie || ''); if (!supplied) return true; if ((process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET || '').length < 32) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.'); if (req.headers.authorization !== undefined && !/^Bearer \S+$/.test(req.headers.authorization)) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.'); return super.canActivate(context); } handleRequest(err: unknown, user: T | false): T { if (err || !user) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.'); return user; } }