How peregrinno/rika-backend works
Project Type and Purpose
• This is a RESTful authentication API (“Rika App”) built with Ruby + Sinatra, using JWT for stateless auth and PostgreSQL for persistence.
• It exposes endpoints for user registration, login, and protected resources (e.g., “cycle” endpoints).
High-Level File Structure Analysis
• Top-level entrypoints:
• app.rb + config.ru → boots the Sinatra app
• .env(.example) → runtime configuration (DB, JWT secret, CORS)
• Gemfile → declares Ruby dependencies (Sinatra, ActiveRecord, JWT, BCrypt, etc.)
• src/ → main application code
• config/ → DB connections & ActiveRecord setup
• routes/ → HTTP routing definitions (auth_routes, cycle_routes, central router)
• middlewares/ → request‐handling middleware (auth_middleware for JWT validation)
• controllers/ → action handlers (AuthController, CycleController, BaseController)
• services/ → domain services (TokenService, MailerService)
• contracts/ → input/schema validation (AuthContract, CycleContract)
• models/ → ActiveRecord models (User, Cycle)
• lib/ → shared utilities (API response formatting, CORS headers, validation helpers)
• Rakefile + migrations → database lifecycle (create, migrate, rollback)
Key Components
a. Clients
• Web/mobile front-end or any HTTP client
b. API Gateway / Web Server
• app.rb / Sinatra → handles incoming HTTP requests
c. Routing Layer
• src/routes/router.rb orchestrates auth_routes & cycle_routes
d. Middleware
• src/middlewares/auth_middleware.rb → verifies JWT, rejects unauthorized requests
e. Controllers
• AuthController → register/login
• CycleController → protected resource operations
f. Validation Layer
• AuthContract, CycleContract → enforce request schemas before business logic
g. Services
• TokenService → generate & verify JWT tokens
• MailerService → send confirmation or notification emails
h. Models & Database
• ActiveRecord models (User, Cycle) → map to PostgreSQL tables
• Database (PostgreSQL) → persistent store
i. Utilities
• CORS headers injector, API response formatting, error handlers
Component Interactions & Data Flow
1. Client issues HTTP request → hits Sinatra server (app.rb)
2. Request flows through AuthMiddleware (if endpoint protected)
3. Router delegates to specific controller
4. Controller invokes Contract for payload validation
5. On success: Controller calls Service(s) or Model(s)
• TokenService for login → signs JWT
• MailerService for welcome emails
• Models read/write data via ActiveRecord → DB
6. Controller packs data into a standardized API response (via ApiResponse)
7. Response returns to client
Architectural Patterns & Principles
• Layered Architecture: clear separation (Routing → Middleware → Controllers → Services → Models → DB)
• Stateless Authentication: JWT tokens passed on each request
• Single-responsibility: each component has one concern (validation vs. business logic vs. persistence)
• Configuration via environment variables for 12-factor compliance