Overview
PyqDeck uses Clerk for authentication. We leverage Clerk’s managed UI for sign-in/up and their Express middleware for backend session validation.JWT Flow
- Frontend: Obtains a short-lived JWT (Session Token) from Clerk.
- Request: The token is sent in the
Authorization: Bearer <token>header. - Backend Middleware:
clerkMiddleware()(from@clerk/express) validates the JWT using theCLERK_PUBLISHABLE_KEYandCLERK_SECRET_KEY. - Session Object: If valid,
req.authis populated with the user’s Clerk ID and metadata.
User Provisioning (syncUser)
We use a “lazy provisioning” strategy. Users are only created in our MongoDB when they make their first authenticated API request.syncUser.middleware.js
This middleware runs after the Clerk middleware:
- Check Cache: It first checks if a user with the given
clerkIdexists in our database. - Fetch Clerk Profile: If not found, it performs a server-side fetch to the Clerk API (
api.clerk.com/v1/users/{id}) to get the user’s full profile (email, name, avatar). - Upsert: It creates or updates the user record in MongoDB.
- Attach to Request: The database user object is attached to
req.dbUser.
https request for the Clerk API fetch to avoid IPv6 resolution issues common in some Node.js environments.
Role-Based Access Control (RBAC)
We define three primary roles in theUser model:
| Role | Permissions |
|---|---|
normal | View papers, search questions, add bookmarks, submit solutions. |
editor | All normal permissions + Create/Edit universities, subjects, and papers. |
admin | Full system access, including user management and platform configuration. |
Authorization Middleware
We use theauthorize higher-order function in backend/src/middlewares/auth.middleware.js:
requireAuthentication: Ensures the user is logged in (has a valid Clerk session).isEditor: Restricts access to users witheditororadminroles.isAdmin: Restricts access to users with theadminrole only.
Role Management
Roles can be managed in two ways:- Clerk Public Metadata: If a
roleis set in the user’spublic_metadatain Clerk, it will be synced to our database during thesyncUserflow. - Direct DB Edit: Admins can update roles directly in the database or via the Studio (Admin Panel).

