Fixing file name casing
This commit is contained in:
50
src/Clerk/clerk-auth.guard.ts
Normal file
50
src/Clerk/clerk-auth.guard.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
// clerk-auth.guard.ts
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Inject,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import Clerk from '@clerk/clerk-sdk-node';
|
||||
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: any) {
|
||||
throw new UnauthorizedException(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user