Skip to main content

MOR Financial Portal API Documentation

Overview​

This document outlines the complete API flow from frontend to backend in the MOR Financial Portal application. The application uses Next.js for the frontend and communicates with a separate backend server through API routes.

Environment Configuration​

The application requires the following environment variables:

  • SERVER_URL: The base URL of the backend server
  • SERVER_API_TOKEN: API token for backend authentication
  • CLIENT_URL: The base URL of the frontend application
  • NODE_ENV: Environment mode (development/production)

Application Routes​

Public Routes​

  • / (login)
  • /sign-up
  • /forgot-password
  • /reset-password
  • /verify-email

Protected Routes​

Investor Routes​

  • /investor (dashboard)
  • /investor/offerings (investment offerings list)
  • /investor/offerings/{id} (single offering details)
  • /investor/portfolio
  • /investor/history
  • /investor/calculators

Broker Routes​

  • /broker (dashboard)

Authentication Flow​

1. Signup​

Frontend Route: /sign-up API Flow:

  1. Frontend (src/views/Auth/Register.tsx) β†’
  2. Redux Action (src/store/api/authApi.ts) β†’
  3. Next.js API Route (src/app/api/auth/signup/route.ts) β†’
  4. Backend Server (${SERVER_URL}/signup)

Request Payload:

{
email: string;
password: string;
role: ROLES;
name: string;
}

Response:

{
success: boolean;
data: {
message: string;
accessToken: string;
refreshToken: string;
}
}

Error Scenarios:

  • Server URL not configured (500)
  • Invalid input validation (400)
  • Email already exists (409)
  • Server error (500)

2. Login​

Frontend Route: / API Flow:

  1. Frontend (src/views/Auth/Login.tsx) β†’
  2. Redux Action (src/store/api/authApi.ts) β†’
  3. Next.js API Route (src/app/api/auth/login/route.ts) β†’
  4. Backend Server (${SERVER_URL}/login)

Request Payload:

{
email: string;
password: string;
}

Response:

  • Sets HTTP-only cookies:
    • token: Access token (30 days expiry)
    • refreshToken: Refresh token (30 days expiry)

Error Scenarios:

  • Invalid credentials (401)
  • Account not verified (403)
  • Server error (500)

3. Logout​

Frontend Route: N/A (Triggered by user action) API Flow:

  1. Redux Action (src/store/api/authApi.ts) β†’
  2. Next.js API Route (src/app/api/auth/logout/route.ts)

Response:

  • Deletes token and refreshToken cookies
  • Clears local auth state

4. Forgot Password​

Frontend Route: /forgot-password API Flow:

  1. Frontend β†’
  2. Redux Action (src/store/api/authApi.ts) β†’
  3. Next.js API Route (src/app/api/auth/forgot-password/route.ts) β†’
  4. Backend Server (${SERVER_URL}/forgot-password)

Request Payload:

{
email: string;
}

Response:

{
success: boolean;
message: string;
}

Error Scenarios:

  • Email not found (404)
  • Rate limiting (429)
  • Server error (500)

5. Reset Password​

Frontend Route: /reset-password API Flow:

  1. Frontend β†’
  2. Redux Action (src/store/api/authApi.ts) β†’
  3. Next.js API Route (src/app/api/auth/reset-password/route.ts) β†’
  4. Backend Server (${SERVER_URL}/reset-password)

Request Payload:

{
token: string;
password: string;
confirmPassword: string;
}

Error Scenarios:

  • Invalid/expired token (401)
  • Password validation failed (400)
  • Server error (500)

Investor Routes​

1. Investment Offerings List​

Frontend Route: /investor/offerings API Flow:

  1. Frontend β†’
  2. Redux Action (src/store/api/investor/offeringsApi.ts) β†’
  3. Next.js API Route (src/app/api/investors/investment-offerings/route.ts) β†’
  4. Backend Server (${SERVER_URL}/tdos)

Request Payload:

{
page: number; // Default: 1
limit: number; // Default: 10
search: string; // Default: ''
sortBy: string; // Default: 'tdo_title_asc'
filters: Record<string, string | number | boolean> | undefined;
}

Response:

{
data: InvestmentOfferings[];
total: number;
page: number;
limit: number;
totalPages: number;
}

Authentication:

  • Requires token cookie
  • Authorization header: Bearer ${token}

Error Scenarios:

  • Unauthorized (401)
  • Invalid filters (400)
  • Server error (500)

2. Single Investment Offering​

Frontend Route: /investor/offerings/{id} API Flow:

  1. Frontend β†’
  2. Redux Action (src/store/api/investor/offeringsApi.ts) β†’
  3. Next.js API Route (src/app/api/investors/investment-offering/route.ts) β†’
  4. Backend Server (${SERVER_URL}/tdos/${id})

Request Payload:

{
id: string;
}

Response:

{
data: InvestmentOffering;
}

Authentication:

  • Requires token cookie
  • Authorization header: Bearer ${token}

Error Scenarios:

  • Unauthorized (401)
  • Offering not found (404)
  • Server error (500)

3. Investor History​

Frontend Route: /investor/history API Flow:

  1. Frontend β†’
  2. Redux Action (src/store/api/investor/historyApi.ts) β†’
  3. Next.js API Route (src/app/api/investors/history/route.ts) β†’
  4. Backend Server (${SERVER_URL}/investor-history)

Request Payload:

{
page: number; // Default: 1
limit: number; // Default: 10
start_date?: string; // Optional
end_date?: string; // Optional
loan_account?: string; // Optional
}

Response:

{
data: InvestorHistory[];
total: number;
page: number;
limit: number;
totalPages: number;
}

Authentication:

  • Requires token cookie
  • Authorization header: Bearer ${token}

Error Scenarios:

  • Unauthorized (401)
  • Invalid date format (400)
  • Server error (500)

Middleware and Route Protection​

The application uses Next.js middleware (src/middleware.ts) to protect routes and handle authentication:

  1. Public Routes:

    • / (login)
    • /sign-up
    • /forgot-password
    • /reset-password
    • /verify-email
  2. Protected Routes:

    • /investor/* (requires investor role)
    • /broker/* (requires broker role)
  3. Route Protection Logic:

    • Checks for token cookie
    • Validates user role
    • Redirects unauthorized access
    • Handles role-based access control
    • Excludes static assets and API routes from protection

Error Handling​

All API routes implement consistent error handling:

  1. Authentication errors (401)
  2. Server errors (500)
  3. Validation errors (400)
  4. Not found errors (404)
  5. Rate limiting errors (429)
  6. Conflict errors (409)

Each error response follows the format:

{
error: string;
details?: any;
status: number;
message?: string;
}

State Management​

The application uses Redux Toolkit for state management with the following slices:

  1. Auth State (authApi):

    • Authentication status
    • User information
    • Token management
    • Login/Signup state
  2. Investment Offerings (investorOfferingsApi):

    • List of offerings
    • Single offering details
    • Filtering and sorting state
    • Pagination state
  3. Investor History (historyApi):

    • Transaction history
    • Filtering state
    • Pagination state
  4. General Auth State (authReducer):

    • User preferences
    • UI state
    • Session management

Security Measures​

  1. Token Storage:

    • Access tokens stored in HTTP-only cookies
    • 30-day expiration for both access and refresh tokens
    • Secure flag enabled in production
    • SameSite: 'lax' to prevent CSRF
  2. API Security:

    • All protected routes require valid JWT token
    • Role-based access control
    • CORS protection
    • Rate limiting (implemented on backend)
    • Input validation on all endpoints
    • XSS protection through proper encoding
  3. Environment Variables:

    • Sensitive configuration stored in environment variables
    • Different configurations for development and production
    • Server URL and API tokens managed through Cloudflare Pages
  4. Cloudflare Integration:

    • KV namespace for caching
    • Edge runtime for better performance
    • DDoS protection
    • SSL/TLS encryption

Development and Deployment​

  1. Local Development:

    npm run dev        # Development server with Turbopack
    npm run preview # Preview production build
    npm run build # Production build
  2. Deployment:

    npm run deploy     # Deploy to Cloudflare Pages
  3. Environment Setup:

    • Configure environment variables in Cloudflare Pages
    • Set up KV namespace bindings
    • Configure custom domains if needed
  4. Monitoring:

    • Cloudflare Analytics
    • Error tracking through console logs
    • Performance monitoring through Cloudflare

Implementation Recommendations​

1. Authentication Enhancements​

Session Management​

// Session timeout handling
interface SessionConfig {
timeout: number; // Session timeout in minutes
refreshThreshold: number; // Time before timeout to refresh
maxConcurrentSessions: number;
}

// Token refresh mechanism
interface TokenRefresh {
refreshToken: string;
accessToken: string;
expiresIn: number;
}

Account Verification​

// Email verification status
interface VerificationStatus {
isVerified: boolean;
verificationDate?: string;
verificationMethod: 'email' | 'phone' | 'manual';
}

// Verification endpoints
POST / api / auth / verify - email;
POST / api / auth / resend - verification;
POST / api / auth / verify - phone;

2. Investment Management​

Investment Actions​

// Investment request
interface InvestmentRequest {
offeringId: string;
amount: number;
paymentMethod: string;
terms: Record<string, any>;
}

// Investment endpoints
POST / api / investor / investments / create;
GET / api / investor / investments / status / {id};
POST / api / investor / investments / withdraw;
GET / api / investor / investments / portfolio;

Document Management​

// Document handling
interface DocumentRequest {
type: 'NDA' | 'AGREEMENT' | 'STATEMENT';
offeringId?: string;
format: 'PDF' | 'DOC';
}

// Document endpoints
POST / api / investor / documents / sign;
GET / api / investor / documents / list;
GET / api / investor / documents / {id};

3. Broker Management​

Broker Operations​

// Broker management
interface BrokerOperations {
createOffering: (data: OfferingData) => Promise<Response>;
manageInvestors: (investorId: string, action: string) => Promise<Response>;
viewAnalytics: (filters: AnalyticsFilters) => Promise<Response>;
}

// Broker endpoints
POST / api / broker / offerings / create;
PUT / api / broker / offerings / {id};
GET / api / broker / investors;
POST / api / broker / investors / {id} / approve;

4. Data Management Enhancements​

Export and Bulk Operations​

// Data export
interface ExportRequest {
type: 'CSV' | 'PDF' | 'EXCEL';
filters: Record<string, any>;
dateRange: [string, string];
}

// Export endpoints
POST /api/investor/export/portfolio
POST /api/investor/export/history
POST /api/broker/export/offerings

Caching Strategy​

// Cache configuration
interface CacheConfig {
ttl: number;
strategy: 'memory' | 'redis' | 'cloudflare-kv';
invalidationRules: Record<string, string[]>;
}

// Cache endpoints
GET / api / cache / status;
POST / api / cache / invalidate;

5. Enhanced Error Handling​

Error Logging​

// Error logging
interface ErrorLog {
timestamp: string;
error: string;
stack?: string;
context: Record<string, any>;
severity: 'low' | 'medium' | 'high' | 'critical';
}

// Logging endpoints
POST / api / logs / error;
GET / api / logs / errors;
GET / api / logs / errors / {id};

Error Recovery​

// Recovery mechanisms
interface RecoveryAction {
type: 'retry' | 'fallback' | 'rollback';
maxAttempts: number;
backoffStrategy: 'linear' | 'exponential';
}

// Recovery endpoints
POST / api / recovery / retry;
POST / api / recovery / rollback;

6. Security Enhancements​

Rate Limiting​

// Rate limit configuration
interface RateLimitConfig {
windowMs: number;
maxRequests: number;
message: string;
statusCode: number;
}

// Rate limit endpoints
GET / api / rate - limit / status;
POST / api / rate - limit / reset;

Security Headers​

// Security headers
interface SecurityHeaders {
'Content-Security-Policy': string;
'X-Frame-Options': string;
'X-Content-Type-Options': string;
'Strict-Transport-Security': string;
'X-XSS-Protection': string;
}

7. Performance and Monitoring​

Analytics and Metrics​

// Performance metrics
interface PerformanceMetrics {
pageLoad: number;
apiResponse: number;
resourceUsage: Record<string, number>;
userInteractions: Record<string, number>;
}

// Analytics endpoints
POST / api / analytics / track;
GET / api / analytics / summary;
GET / api / analytics / detailed;

Error Tracking​

// Error tracking
interface ErrorTracking {
service: 'sentry' | 'logrocket' | 'custom';
config: Record<string, any>;
filters: Record<string, string[]>;
}

// Tracking endpoints
POST / api / tracking / error;
GET / api / tracking / errors;

8. UI/UX Enhancements​

Progressive Loading​

// Progressive loading
interface ProgressiveLoad {
chunkSize: number;
preloadThreshold: number;
fallbackContent: React.ReactNode;
}

// Loading endpoints
GET / api / content / chunk / {id};
POST / api / content / preload;

Accessibility​

// Accessibility features
interface AccessibilityConfig {
highContrast: boolean;
fontSize: number;
screenReader: boolean;
keyboardNavigation: boolean;
}

// Accessibility endpoints
POST / api / accessibility / preferences;
GET / api / accessibility / status;

Implementation Priority​

  1. High Priority

    • Session management and token refresh
    • Investment action flows
    • Document management
    • Error logging and tracking
    • Rate limiting
  2. Medium Priority

    • Broker management features
    • Data export functionality
    • Caching strategy
    • Performance metrics
    • Progressive loading
  3. Low Priority

    • Analytics and reporting
    • Bulk operations
    • Accessibility features
    • Offline support
    • Advanced security headers

Development Guidelines​

  1. Code Organization

    • Follow the existing directory structure
    • Use TypeScript for all new features
    • Implement proper error boundaries
    • Add comprehensive unit tests
  2. API Design

    • Follow RESTful principles
    • Use consistent error formats
    • Implement proper validation
    • Document all new endpoints
  3. Security

    • Implement all security measures
    • Follow OWASP guidelines
    • Regular security audits
    • Proper secret management
  4. Performance

    • Implement caching where appropriate
    • Use proper indexing
    • Optimize database queries
    • Monitor performance metrics
  5. Testing

    • Unit tests for all new features
    • Integration tests for API endpoints
    • E2E tests for critical flows
    • Performance testing