Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Authentication and Authorization

A secure authentication system using Clerk for identity verification and MongoDB collection for storing userIds only. Ensures only authenticated and authorized users can access or modify documents.

Authentication Flow

User Login to Access Document

User Login
   │
   ▼
┌─────────────────────────────────────┐
│ Clerk OAuth/Email Sign-In           │
│ (Frontend: @clerk/clerk-react)      │
└─────────────────────┬───────────────┘
                      │
                      ▼
           JWT Token Generated
      (RS256 signed by Clerk)
                      │
                      ▼
      ┌──────────────────────────────┐
      │ Stored in HTTPOnly Cookie    │
      │ Auto-included in all requests│
      └──────────────────────────────┘
                      │
                      ▼
GraphQl Resolvers -> if User has project access

Request Authentication

API Request with JWT Token

User creation or validating flow.

Frontend Request
      │
      ▼
┌──────────────────────────────────────┐
│ Headers:                             │
│ Authorization: Bearer eyJhbGc...     │
│ Content-Type: application/json       │
└────────────┬─────────────────────────┘
             │
             ▼ (HTTPS)
┌──────────────────────────────────────┐
│ Backend Middleware                   │
│ GinClerkAuthMiddleware               │
├──────────────────────────────────────┤
│ 1. Extract token from header         │
│ 2. Verify with Clerk public key      │
│ 3. Check expiration                  │
│ 4. Extract clerkUserID               │
│ 5. Get/create user in MongoDB        │
│ 6. Add user to context               │
└────────────┬─────────────────────────┘
             │
             ▼
      Request Authorized ✓
      Proceed to resolver

Authorization Checks

Document Access Control

Flow of how a document is fetched through authorization.

User requests: GET /api/project/{projectId}
      │
      ▼
┌──────────────────────────────────────┐
│ 1. User authenticated? (JWT valid)   │
│    ├─ YES → Continue                 │
│    └─ NO → Return 401 Unauthorized   │
└────────────┬─────────────────────────┘
             │
             ▼
┌───────────────────────────────────────┐
│ 2. Check project ownership/access     │
│    Query: Project.ownerId == user.id  │
│    OR user.id in Project.collaborators│
├───────────────────────────────────────┤
│    ├─ Owner → Full access             │
│    ├─ Collaborator → Read/Write       │
│    └─ Other → Return 403 Forbidden    │
└────────────┬──────────────────────────┘
             │
             ▼
      Authorization passed ✓
      Return project data