create token decorator and consumer module
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { AccessTokenPayload } from '@/modules/auth/models'
|
||||
import {
|
||||
BadRequestException,
|
||||
createParamDecorator,
|
||||
ExecutionContext,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common'
|
||||
import { Request } from 'express'
|
||||
|
||||
export const TokenAccount = createParamDecorator(
|
||||
(data: keyof AccessTokenPayload | 'userId' | undefined, ctx: ExecutionContext) => {
|
||||
try {
|
||||
const request = ctx.switchToHttp().getRequest<Request>()
|
||||
const account = request.decodedToken
|
||||
|
||||
// ✅ if middleware didn't populate req.account, return undefined or throw
|
||||
if (!account.user?.id) {
|
||||
throw new UnauthorizedException('شما به این بخش دسترسی ندارید')
|
||||
}
|
||||
|
||||
// ✅ if decorator called with a key (e.g. @account('accountId'))
|
||||
if (data) {
|
||||
if (data === 'userId') {
|
||||
return account.user?.id
|
||||
}
|
||||
return account[data]
|
||||
}
|
||||
|
||||
// ✅ if called with no param — return full account object
|
||||
return account
|
||||
} catch (err) {
|
||||
throw new BadRequestException('مشکلی در ساختار درخواست شما وجود دارد.')
|
||||
}
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user