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('مشکلی در ساختار درخواست شما وجود دارد.')
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,11 +1,13 @@
|
||||
import { ITokenPayload } from '@/modules/auth/auth.utils'
|
||||
import { UnauthorizedException } from '@nestjs/common'
|
||||
import { JwtService } from '@nestjs/jwt'
|
||||
import { Request } from 'express'
|
||||
import { AccessTokenPayload } from 'modules/auth/models'
|
||||
|
||||
export function getAccountIdFromJwt(req: Request, jwtService: JwtService): string | null {
|
||||
// Try to get token from Authorization header
|
||||
|
||||
export function checkAndDecodeJwtToken(
|
||||
req: Request,
|
||||
jwtService: JwtService,
|
||||
): ITokenPayload | null {
|
||||
let token = req.cookies?.accessToken
|
||||
|
||||
if (!token) {
|
||||
@@ -18,11 +20,10 @@ export function getAccountIdFromJwt(req: Request, jwtService: JwtService): strin
|
||||
}
|
||||
if (!token) throw new UnauthorizedException('Missing accessToken cookie')
|
||||
|
||||
// const token = authHeader.replace('Bearer ', '')
|
||||
try {
|
||||
const payload = jwtService.decode(token) as AccessTokenPayload
|
||||
|
||||
return payload?.account_id || null
|
||||
return payload as ITokenPayload
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user