wobsoriano / nuxt-clerk-template

Auth starts here with the Nuxt and Clerk Demo
https://nuxt-clerk-template.nuxt.dev
97 stars 11 forks source link

use withClerkMiddleware conditionally #2

Closed fanckush closed 1 year ago

fanckush commented 1 year ago

Really awesome work on h3-clerk.

Is there a way to define more control over withClerkMiddleware? for example I want to protect certain endpoints or check if the specific user has certain rights

// before
import { withClerkMiddleware } from 'h3-clerk';

export default withClerkMiddleware({
  publishableKey: useRuntimeConfig().public.clerkPublishableKey,
  secretKey: useRuntimeConfig().clerkSecretKey,
});
// after
import { withClerkMiddleware } from 'h3-clerk';

const protectedEndpoints = [
  '/api/requires-auth',
  'etc..'
]

const adminEndpoints = [
  '/api/requires-admin',
  'etc..'
]

const vieverEndpoints = [
  '/api/requires-viewer',
  'etc..' 
]

export default defineEventHandler((event) => {
  // how to use withClerkMiddleware here?
})
wobsoriano commented 1 year ago

How about having another middleware and checking the value of event.context.auth there? Something like

// server/middleware/clerk.ts
import { withClerkMiddleware } from 'h3-clerk';

export default withClerkMiddleware()
// server/middleware/other.ts

const protectedEndpoints = [
  '/api/requires-auth',
  '/api/another',
]

export default defineEventHandler((event) => {
  const { userId } = event.context.auth

  if (!userId && protectedEndpoints.includes(event.path)) {
    throw createError({ statusCode: 401 })
  }

  // Continue...
})
fanckush commented 1 year ago

@wobsoriano I have misunderstood the middleware purpose. I was getting 401 in localhost thinking that the middleware only allowed authenticated requests where it turns out that it's just a bug from clerk #1

it makes sense sow, all the middleware does is inject the auth into the context which is exactly what I wanted 👍

wobsoriano commented 1 year ago

Released a new version, with a withClerkAuth middleware. Prefer this one over withClerkMiddleware:

import { withClerkAuth } from 'h3-clerk'

const protectedEndpoints = [
  '/api/requires-auth',
  '/api/another',
]

export default withClerkAuth((event) => {
  const { userId } = event.context.auth

  if (!userId && protectedEndpoints.includes(event.path)) {
    throw createError({ statusCode: 401 })
  }

  // Continue...
})
fanckush commented 1 year ago

Thanks for the update, the DX is nice and allows me to combine two pieces of middleware into one.

That said, I still have the infinite loop bug with the header "cross-origin-referrer" i'm currently watching out for https://github.com/clerkinc/javascript/issues/1566 since I expect it to be the exact issue I have