User Authentication and Authorization Flow

+---------------------------------+
|             Start               |
+---------------------------------+
            |
            v
+---------------------------------+
|           User Logs In          |
+---------------------------------+
            |
            v
+---------------------------------+
|        Input Validation         |
+---------------------------------+
          /            \
         /              \
  Valid Input      Invalid Input
         |              |
         v              v
+------------------+  +-----------------+
| Fetch User Data  |  | Show Error Msg  |
+------------------+  +-----------------+
         |
         v
+-------------------------+
|    Check User Exists    |
+-------------------------+
          /      \
         /        \
   User Exists  User Not Found
         |           |
         v           v
+----------------+  +-----------------+
| Check Password |  | Show Error Msg  |
+----------------+  +-----------------+
         |
         v
+---------------------+
| Password Matches    |
+---------------------+
         |
         v
+------------------+
| Encrypt Session  |
|      Data        |
+------------------+
         |
         v
+-----------------+
| Create Session |
+-----------------+
         |
         v
+--------------------+
| Set Session Cookie |
+--------------------+
         |
         v
+-------------------------+
|  Return Session Data    |
|         and URL         |
+-------------------------+
         |
         v
+---------------------------------+
|          Session Check          |
+---------------------------------+
          /      |       \
         /       |        \
        /        |         \
       v         |          v
+---------------------------+ +---------------------------+
|      Invalid Session      | |       Valid Session       |
|   Show Error Message      | |   Check User Approval     |
+---------------------------+ +---------------------------+
            |                       /          \
            |                      /            \
            v                     /              \
+---------------------------+    v                v
|  Show Error Message       | +----------------+ +---------------------------+
|                           | | User Approved  | |   User Not Approved       |
|                           | | Display Content| |   Show Access Denied Msg  |
+---------------------------+ +----------------+ +---------------------------+

Detailed Middleware and Route Handling

Middleware Flow

  1. Start: The process begins when a request is made to a protected route.
  2. Route Matching: The middleware checks if the request matches any of the protected routes (e.g., /finance, /registry).
  3. Clerk Middleware for Finance Routes: If the route is matched, the Clerk middleware handles authentication.
    • Authenticate User: Clerk middleware authenticates the user.
    • Proceed to Next Middleware: If authenticated, proceed to the next middleware.
  4. Custom Authentication for Other Routes: If the route is not matched by Clerk, custom authentication logic is applied.
    • Get Session Data: Fetch session data from the request.
    • Check if Logged In: Verify if the user is logged in.
    • Public Route: If the route is public, allow access.
    • Authentication Route: If the route is for authentication (e.g., login, register), redirect logged-in users to the default login redirect.
    • API Authentication: Allow API authentication routes to pass without further checks.
    • Protected Route: For protected routes, check if the user is logged in.
    • Update Session: Update session data for logged-in users.
+---------------------------------+
|             Start               |
+---------------------------------+
            |
            v
+---------------------------------+
|         Route Matching          |
+---------------------------------+
            |
            v
+-------------------------------------------+
| Clerk Middleware for Finance Routes       |
+-------------------------------------------+
        /                    \
       /                      \
Authenticated User    Not Authenticated
       |                      |
       v                      v
+--------------------+  +--------------------+
| Proceed to Next    |  |   Show Error Msg   |
|     Middleware     |  +--------------------+
+--------------------+
       |
       v
+---------------------------------+
| Custom Authentication for Other |
|             Routes              |
+---------------------------------+
            |
            v
+-------------------------+
|  Get Session Data       |
+-------------------------+
            |
            v
+-------------------------+
|  Check if Logged In     |
+-------------------------+
        /          \
       /            \
Logged In       Not Logged In
       |            |
       v            v
+-----------------+  +---------------------------+
| Proceed to Next |  | Redirect to Login Page    |
|     Step        |  +---------------------------+
+-----------------+
       |
       v
+---------------------------+
|  Check if Public Route    |
+---------------------------+
        /            \
       /              \
Public Route    Protected Route
       |              |
       v              v
+-----------------+  +-------------------------+
| Allow Access    |  | Check if Logged In      |
+-----------------+  +-------------------------+
                         /          \
                        /            \
                   Logged In    Not Logged In
                        |            |
                        v            v
               +-------------------+  +------------------+
               | Update Session    |  | Redirect to Login|
               +-------------------+  +------------------+
                        |
                        v
               +-------------------------+
               | Proceed to Requested    |
               |        Route            |
               +-------------------------+

Authentication Logic Details

  • Input Validation: Uses LoginSchema to validate the user's input fields (email and password). Ensures that the input meets the required format and constraints.
  • Fetch User Data: Queries the database to retrieve the user data associated with the provided email. Uses getUserByEmail function to fetch the user data.
  • Check Password: Compares the provided password with the stored hashed password. Uses bcrypt.compare to securely compare the passwords.
  • Encrypt Session Data: Encrypts the user data and session expiry date to create a session token. Uses the encrypt function to perform encryption.
  • Set Session Cookie: Sets the session token in an HTTP-only cookie to ensure secure storage. Uses cookies().set to set the cookie with the httpOnly flag.

Authorization Logic Details

  • Session Check: Verifies the validity of the user's session.
  • Check User Approval: Checks if the user's ID is in the list of approved IDs for the requested path.
  • User Approved: Grants access to the requested content if the user is approved.
  • User Not Approved: Denies access and shows an access denied message if the user is not approved.

Overall Flow Description

  1. Start: The process begins when a request is made.
  2. User Logs In: The user attempts to log in.
  3. Input Validation: Validate the input fields.
  4. Fetch User Data: Retrieve user data from the database.
  5. Check User Exists: Verify if the user exists.
  6. Check Password: Compare the provided password with the stored hashed password.
  7. Encrypt Session Data: Encrypt user data and session expiry date.
  8. Create Session: Generate a session token.
  9. Set Session Cookie: Save the session token in an HTTP-only cookie.
  10. Return Session Data and URL: Return the session data and redirect URL.
  11. Session Check: Verify the user's session validity.
  12. Check User Approval: Check if the user is approved for the requested path.

Middleware Flow

  1. Start: Process begins when a request is made to a protected route.
  2. Route Matching: Middleware checks if the request matches any protected routes.
  3. Clerk Middleware: Handles authentication for finance-related routes.
  4. Custom Authentication: Handles authentication for other routes.
  5. Get Session Data: Fetch session data.
  6. Check if Logged In: Verify if the user is logged in.
  7. Public Route: Allow access to public routes.
  8. Authentication Route: Redirect logged-in users from authentication routes.
  9. API Authentication: Allow API authentication routes.
  10. Protected Route: Check if the user is logged in for protected routes.
  11. Update Session: Update session data for logged-in users.
  12. Proceed to Requested Route: Allow access to the requested route.

"Great companies are built on great products"