wobsoriano / vue-clerk

Community Clerk Vue SDK.
https://vue-clerk.com
MIT License
156 stars 14 forks source link

use of useAuth from #clerk in middleware #172

Closed 5knnbdwm closed 3 weeks ago

5knnbdwm commented 1 month ago

Hey, I basically want to protect most of my api with clerk, also dont really need access to the userObject so i just wanted to do the auth check in middleware.

However when doing so getAuth() returns undefined. Any idea as how to solve this?

// server/middleware/auth.ts
import { getAuth } from "#clerk";
// import { clerkClient, getAuth } from "#clerk";

export default defineEventHandler(async (event) => {
  if (event.node.req.url?.startsWith("/api")) {
    const publicRoutes = ["/api/public", "/api/another-public-route"];

    if (publicRoutes.includes(event.node.req.url || "")) {
      return;
    }

    console.log("getAuth", getAuth(event)); // returns `undefined`
    // const { userId } = getAuth(event);

    // if (!userId) {
    //   throw createError({
    //     statusCode: 401,
    //   });
    // }

    // event.context.userId = userId;
  }
});
wobsoriano commented 1 month ago

Hey, thanks for checking this module out.

Did you add vue-clerk/nuxt to modules array in your nuxt.config.ts file?

5knnbdwm commented 1 month ago

hey, yes i did. useAuth does work in a normal endpoint just doesnt seem to work in the middleware

wobsoriano commented 1 month ago

This is a good catch. Thanks! Looks like this might be caused by the ordering of middleware. Looking into it now

5knnbdwm commented 1 month ago

Okay just created a reproduction if it as well so it wasn't just a bug in my project.

But thanks for the quick response and looking into it.

wobsoriano commented 1 month ago

thanks, yeah I can confirm this one

wobsoriano commented 3 weeks ago

Hello! Sorry for the late update.

I have added an experimental feature where you can add custom logic when you want to protect API routes. See this PR for more info.

Example:

// server/middleware/clerk.ts
import { clerkMiddleware } from 'vue-clerk/server'

export default clerkMiddleware((event) => {
  const protectedRoutes = ['/api/protected', '/api/another-protected-route']
  const { auth } = event.context

  if (!auth.userId && protectedRoutes.includes(event.context.path)) {
    throw createError({
      statusCode: 401,
      message: 'Unauthorized'
    })
  }
})
5knnbdwm commented 3 weeks ago

Thanks. That works beautifully