Skip to content

Commit

Permalink
feat: create authenticated and protected middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
dallen4 committed Jan 12, 2025
1 parent 1e385fa commit 87847a4
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions worker/src/lib/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ export const SessionNotFound = {
export const NotAuthenticated = {
message: 'Not authenticated!',
};

export const PermissionDenied = {
message: 'Permission denied!',
};
33 changes: 33 additions & 0 deletions worker/src/lib/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createMiddleware } from 'hono/factory';
import { AppHeaders } from '../constants';
import { HonoCtx, Middleware } from './http/core';
import { Redis } from '@upstash/redis/cloudflare';
import { NotAuthenticated, PermissionDenied } from './messages';

export const tracing = () =>
createMiddleware<HonoCtx>(async (c, next) => {
Expand Down Expand Up @@ -42,3 +43,35 @@ export const redis = () =>

await next();
});

export const authenticated = () =>
createMiddleware<HonoCtx>(async (c, next) => {
const auth = c.get('clerkAuth');

if (!auth?.userId) {
return c.json(NotAuthenticated, 401);
}

await next();
});

// only allowed if user has been granted early_access or marked as internal
export const restricted = () =>
createMiddleware<HonoCtx>(async (c, next) => {
const auth = c.get('clerkAuth');

if (!auth?.userId) {
return c.json(NotAuthenticated, 401);
}

const claims = auth.sessionClaims;

const canAccess =
claims.early_access || claims.internal ? true : false;

if (!canAccess) {
return c.json(PermissionDenied, 401);
}

await next();
});
8 changes: 8 additions & 0 deletions worker/types/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export {};

declare global {
interface CustomJwtSessionClaims {
internal?: string;
early_access?: string;
}
}

0 comments on commit 87847a4

Please sign in to comment.