This repository was archived by the owner on Jan 28, 2026. It is now read-only.
File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- import { ExecutionContext , Injectable } from '@nestjs/common' ;
1+ import { ExecutionContext , Injectable , UnauthorizedException } from '@nestjs/common' ;
22import { Reflector } from '@nestjs/core' ;
33import { AuthGuard } from '@nestjs/passport' ;
44import { IS_PUBLIC_KEY } from '../decorators/public.decorator' ;
@@ -29,9 +29,30 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
2929 if ( isPublic ) {
3030 return user || null ;
3131 }
32+
33+ // Если есть ошибка или пользователь отсутствует
3234 if ( err || ! user ) {
33- throw err || new Error ( 'Unauthorized' ) ;
35+ // Если ошибка уже является HttpException (например, UnauthorizedException из JwtStrategy), пробрасываем её
36+ if ( err && ( err . statusCode || err instanceof UnauthorizedException ) ) {
37+ throw err ;
38+ }
39+
40+ // Определяем сообщение об ошибке
41+ let message = 'Необходима авторизация' ;
42+ if ( info ?. message ) {
43+ message = info . message ;
44+ } else if ( info ?. name === 'JsonWebTokenError' ) {
45+ message = 'Недействительный токен' ;
46+ } else if ( info ?. name === 'TokenExpiredError' ) {
47+ message = 'Токен истёк' ;
48+ } else if ( ! user && ! err ) {
49+ message = 'Токен не предоставлен или недействителен' ;
50+ }
51+
52+ // Всегда выбрасываем UnauthorizedException для корректного статуса 401
53+ throw new UnauthorizedException ( message ) ;
3454 }
55+
3556 return user ;
3657 }
3758}
You can’t perform that action at this time.
0 commit comments