diff --git a/apps/api/v1/middlewares/auth.ts b/apps/api/v1/middlewares/auth.ts index 7c0acb55..5f302b83 100644 --- a/apps/api/v1/middlewares/auth.ts +++ b/apps/api/v1/middlewares/auth.ts @@ -1,6 +1,8 @@ import type { User } from '@/prisma/generated/zod' import { clerkMiddleware, getAuth } from '@hono/clerk-auth' +import type { Context } from 'hono' import { createMiddleware } from 'hono/factory' +import { HTTPException } from 'hono/http-exception' import { findUserById } from '../services/user.service' declare module 'hono' { @@ -29,3 +31,13 @@ export const authMiddleware = createMiddleware(async (c, next) => { await next() }) + +export const getAuthUser = (c: Context) => c.get('user') + +export const getAuthUserStrict = (c: Context) => { + const user = getAuthUser(c) + if (!user) { + throw new HTTPException(401, { message: 'unauthorized' }) + } + return user +} diff --git a/apps/api/v1/routes/users.ts b/apps/api/v1/routes/users.ts index 5a564086..b7f18ea0 100644 --- a/apps/api/v1/routes/users.ts +++ b/apps/api/v1/routes/users.ts @@ -1,12 +1,13 @@ import { zValidator } from '@hono/zod-validator' import { Hono } from 'hono' +import { getAuthUser } from '../middlewares/auth' import { createUser } from '../services/user.service' import { zCreateUser } from '../validation' const router = new Hono() router.post('/', zValidator('json', zCreateUser), async (c) => { - const existingUser = c.get('user') + const existingUser = getAuthUser(c) if (existingUser) { return c.json({ message: 'user already exists' }, 409)