Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat(api): add getAuthUser & getAuthUserStrict helpers #14

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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