Skip to content

Commit

Permalink
refactor: wip - working path
Browse files Browse the repository at this point in the history
  • Loading branch information
seo-wo committed Dec 5, 2023
1 parent af60022 commit c811427
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 10 deletions.
File renamed without changes.
32 changes: 26 additions & 6 deletions src/auth/jwt/jwt.guard.ts → src/auth/guard/jwt.guard.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,48 @@
import { Injectable, ExecutionContext, Logger } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class JwtGuard extends AuthGuard('jwt') {
private readonly logger = new Logger(JwtGuard.name);
constructor(private readonly jwtService: JwtService) {
super();
}

async canActivate(context: ExecutionContext): Promise<boolean>{
async canActivate(context: ExecutionContext): Promise<boolean> {
if (context.getType() === 'http') {
this.logger.debug(`canActivate [http, ${context.getArgs()[0].method} ${context.getArgs()[0].url}]`);
} else{
this.logger.debug(
`canActivate [http, ${context.getArgs()[0].method} ${
context.getArgs()[0].url
}]`,
);
} else {
this.logger.debug(`canActivate [not http]`);
return false;
}
const token = context.switchToHttp().getRequest().headers?.authorization?.split('Bearer ')[1];
const token = context
.switchToHttp()
.getRequest()
.headers?.authorization?.split('Bearer ')[1];
this.logger.debug(`canActivate [token: ${token}]`);

// if (!token) {
// this.logger.debug(`canActivate [no token]`);
// return false;
// }
let result: boolean = false;
try {
result = (await super.canActivate(context)) as boolean;
this.logger.debug(`canActivate [result: ${result}]`);
} catch (error) {
this.logger.error(`canActivate [error: ${error}]`);
result = false;
/*
token could be expired or invaild
return exception to client and let client to refresh token
*/
throw error;
}
this.logger.debug(`canActivate [result: ${result}]`);
return result;
}
}
}
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import { VerifyCallback } from 'jsonwebtoken';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
private readonly logger = new Logger(JwtStrategy.name);
constructor (
private readonly configService: ConfigService,
){
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get<string>('jwt.secret'),
Expand All @@ -25,4 +23,4 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
throw new UnauthorizedException('Unauthorized', '401');
}
}
}
}
File renamed without changes.

0 comments on commit c811427

Please sign in to comment.