Files
epess-web-backend/src/Clerk/clerk-auth.guard.ts
2024-11-06 17:16:10 +07:00

53 lines
1.4 KiB
TypeScript

// clerk-auth.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
Inject,
UnauthorizedException,
} from '@nestjs/common'
import Clerk from '@clerk/express'
import { GqlExecutionContext } from '@nestjs/graphql'
@Injectable()
export class ClerkAuthGuard implements CanActivate {
constructor(@Inject('CLERK') private readonly clerk: typeof Clerk) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
// For GraphQL, get the request from the GQL context
const ctx = GqlExecutionContext.create(context)
const request = ctx.getContext().req
// Get the token from the Authorization header
const authHeader = request.headers['authorization']
if (!authHeader) {
throw new UnauthorizedException('Authorization header not found')
}
const token = authHeader.split(' ')[1] // Assuming 'Bearer TOKEN'
if (!token) {
throw new UnauthorizedException('Token not found')
}
try {
// Verify the token with Clerk
const session = await this.clerk.verifyToken(token, {})
if (!session) {
throw new UnauthorizedException('Invalid session')
}
// Attach user info to the request context if needed
request.user = session.user
return true
} catch (error: unknown) {
throw new UnauthorizedException(
error instanceof Error ? error.message : 'Unknown error',
)
}
}
}