✨ add user.decorator
This commit is contained in:
parent
c081296242
commit
2d2365fe7a
@ -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
|
||||
}
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
|
12
src/common/decorators/user.decorator.ts
Normal file
12
src/common/decorators/user.decorator.ts
Normal file
@ -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<Request>()
|
||||
const user = request.user as UserEntity
|
||||
|
||||
return key ? user?.[key] : user
|
||||
},
|
||||
)
|
Loading…
Reference in New Issue
Block a user