diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 34ae9de..20a69da 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -1,9 +1,11 @@ -import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common' +import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common' import { AuthService } from './auth.service' import { CreateUserDto } from 'src/users/dto/create-user.dto' import { ApiTags } from '@nestjs/swagger' import { LoginInputDto } from './dto/login-input.dto' import { JwtAuthGuard } from './jwt-auth.guard' +import { UserEntity } from 'src/users/entities/user.entity' +import { User } from 'src/common/decorators/user.decorator' @ApiTags('auth') @Controller() @@ -22,8 +24,7 @@ export class AuthController { @UseGuards(JwtAuthGuard) @Get('api/profile') - async getUserInfo(@Req() req: any) { - console.log(req) - return req.user + async getUserInfo(@User() user: UserEntity) { + return user } } diff --git a/src/auth/jwt-auth.guard.ts b/src/auth/jwt-auth.guard.ts index aa859f7..0fd68ff 100644 --- a/src/auth/jwt-auth.guard.ts +++ b/src/auth/jwt-auth.guard.ts @@ -1,5 +1,24 @@ -import { Injectable } from '@nestjs/common' +import { + ExecutionContext, + Injectable, + UnauthorizedException, +} from '@nestjs/common' import { AuthGuard } from '@nestjs/passport' +import 'rxjs' @Injectable() -export class JwtAuthGuard extends AuthGuard('jwt') {} +export class JwtAuthGuard extends AuthGuard('jwt') { + canActivate(context: ExecutionContext) { + // Add your custom authentication logic here + // for example, call super.logIn(request) to establish a session. + return super.canActivate(context) + } + + handleRequest(err, user, info) { + // You can throw an exception based on either "info" or "err" arguments + if (err || !user) { + throw err || new UnauthorizedException() + } + return user + } +} diff --git a/src/common/decorators/user.decorator.ts b/src/common/decorators/user.decorator.ts new file mode 100644 index 0000000..d18ebab --- /dev/null +++ b/src/common/decorators/user.decorator.ts @@ -0,0 +1,12 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common' +import { type Request } from 'express' +import { UserEntity } from 'src/users/entities/user.entity' + +export const User = createParamDecorator( + (key: string, ctx: ExecutionContext) => { + const request = ctx.switchToHttp().getRequest() + const user = request.user as UserEntity + + return key ? user?.[key] : user + }, +)