Skip to content

Commit

Permalink
feat(api): add getAuthUser & getAuthUserStrict helpers (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
duongdev committed Jun 6, 2024
1 parent 413a81f commit e546860
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
12 changes: 12 additions & 0 deletions apps/api/v1/middlewares/auth.ts
Original file line number Diff line number Diff line change
@@ -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' {
Expand Down Expand Up @@ -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
}
3 changes: 2 additions & 1 deletion apps/api/v1/routes/users.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand Down

0 comments on commit e546860

Please sign in to comment.