Skip to content

Commit

Permalink
fix(nestjs-clerk): error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
y-nk committed Jan 19, 2025
1 parent 01429aa commit d5c0df0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 1 addition & 1 deletion nestjs-clerk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@y_nk/nestjs-clerk",
"version": "1.0.4",
"version": "1.0.5",
"description": "auth and permission guards using clerk for nestjs",
"homepage": "https://github.com/y-nk/nonorepo/tree/main/astro-components",
"keywords": [
Expand Down
15 changes: 12 additions & 3 deletions nestjs-clerk/src/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { clerkMiddleware, getAuth } from "@clerk/express";
import {
Inject,
Injectable,
Logger,
UnauthorizedException,
type CanActivate,
type ExecutionContext,
Expand All @@ -13,6 +14,8 @@ import type { ClerkConfig } from "./types";

@Injectable()
export class ClerkAuthGuard implements CanActivate {
private logger = new Logger(ClerkAuthGuard.name);

constructor(
private reflector: Reflector,
@Inject(CLERK_CONFIG) private clerkConfig: ClerkConfig,
Expand All @@ -28,13 +31,19 @@ export class ClerkAuthGuard implements CanActivate {
const res = context.switchToHttp().getResponse();
const middleware = clerkMiddleware(this.clerkConfig);

const error = await new Promise<Error | undefined>((resolve) => {
const err = await new Promise<Error | undefined>((resolve) => {
middleware(req, res, resolve);
});

const auth = getAuth(req);
try {
if (err) throw err;

if (error || !auth.userId) throw new UnauthorizedException();
if (!getAuth(req)?.userId)
throw new Error("no auth data");
} catch (error) {
this.logger.error(error);
throw new UnauthorizedException();
}

return true;
}
Expand Down

0 comments on commit d5c0df0

Please sign in to comment.