Terrrrr Backend API Documentation

website·Indexed 29 days ago

https://terrrrr-backend.vercel.app

Documentation for the Terrrrr backend, featuring a PostgreSQL database managed via Prisma. It includes details on database models for worlds, users, bosses, and events, as well as API controllers for authentication, world membership, and role-based access control using JWT tokens.

Tokens
9.5K
Snippets
62
Records
92
Agent score
75%

What's inside Terrrrr

  1. Overview of terrrrr-backend documentation

    The terrrrr-backend documentation provides comprehensive technical details for the project's backend architecture, including:

    • API Reference: Documentation for all backend routes and controllers.
    • Authentication & Authorization: Implementation details for JWT, user roles, and protected routes.
    • Database Schema: Explanations of database models, relationships, and constraints.
    • Middleware: Guidance on the usage and flow of authentication and role-check middleware.
  2. Protect routes using the requireAuth middleware

    The requireAuth middleware ensures that only authenticated users can access specific routes. It validates a JWT token stored in the request cookies. If the token is valid, the decoded JWT payload is attached to request.user, allowing subsequent route handlers to access the authenticated user's information.
    router.get("/protected", requireAuth, functionName); // Only accessible if authenticated
  3. Add a new feature to the backend step-by-step

    To add a new feature involving a database model and API endpoints, follow these steps:

    1. Define the data model in Prisma.
    2. Create separate files for routes and controllers.
    3. Register the new route in the main application file.
    4. Define the specific endpoints and apply necessary authentication/authorization middleware.
    5. Implement the business logic within the controller functions.
  4. Define API routes with authentication and role middleware

    In the route file (e.g., src/routes/new.routes.ts), use express.Router() to map endpoints to controller functions.

    • Use requireAuth middleware to ensure the user is authenticated.
    • Use requireRole("ROLE_NAME") (e.g., ADMIN, OWNER, SUB_ADMIN, MEMBER) to restrict access to specific user roles.
    import express from "express";
    import { getNewModels, createNewModel } from "../controllers/new.controller";
    import requireAuth from "../middleware/requireAuth";
    import requireRole from "../middleware/requireRole";
    
    const router = express.Router();
    
    // Protected route: requires authentication
    router.post("/", requireAuth, createNewModel);
    
    // Restricted route: requires authentication AND ADMIN role
    router.get("/", requireAuth, requireRole("ADMIN"), getNewModels);
    
    export default router;
  5. Configure environment variables for terrrrr-backend

    Create and update your environment configuration file with the following required keys. Ensure your database is running before proceeding to the database setup step.
    JWT_SECRET=secret key
    DATABASE_URL=database url
    FRONTEND_URL=http://localhost:3000
    PORT=1234
  6. Manage user authentication lifecycle

    Follow these steps to manage the user authentication flow:

    1. Sign In: Upon successful login, the backend sets token and refreshToken as httpOnly cookies.
    2. Session Validation: Call GET /api/auth/session to verify if the user is currently authenticated via their JWT.
    3. Token Refresh: When the JWT expires, call GET /api/auth/refresh. The backend will validate the refreshToken cookie, issue new tokens, and update the cookies.
    4. Sign Out: Clear both the token and refreshToken cookies on the client side.
  7. Clone the terrrrr-backend repository

    To get the project running on your machine, clone the repository using the provided GitHub URL. If using GitKraken, copy the URL, select 'Clone', paste the URL, and choose a local destination folder.
    https://github.com/alexappleget/terrrrr-backend.git
  8. Terrrrr API General Usage and Authentication

    The Terrrrr API uses JSON for data exchange. All API endpoints are prefixed with /api/. Most routes require authentication; users must authenticate via the /api/auth/session endpoint, after which a JWT token is sent as a cookie to be used for protected routes.
    GET /api/auth/session
  9. Create and sync a new Prisma database model

    Add the new model definition to prisma/schema.prisma. After defining the model, update the database and synchronize the Prisma client using the CLI.
    model NewModel {
        id String @id @default(cuid())
        name String
        createdAt DateTime @default(now())
    }
    npx prisma db push
    npx prisma generate
  10. Restrict route access using requireRole middleware

    The requireRole middleware restricts access to routes based on user roles. It should be used in combination with requireAuth to ensure a user is both authenticated and authorized. The middleware accepts either a single role string or an array of allowed roles for flexible access control.
    // Only users with the OWNER role can access
    router.get("/owner-route", requireAuth, requireRole(["OWNER"]), getAdminData);
    
    // Users with either OWNER or ADMIN roles can access
    router.get("/admin-route", requireAuth, requireRole(["OWNER", "ADMIN"]));