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 serverSERVER_API_TOKEN: API token for backend authenticationCLIENT_URL: The base URL of the frontend applicationNODE_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:
- Frontend (
src/views/Auth/Register.tsx) β - Redux Action (
src/store/api/authApi.ts) β - Next.js API Route (
src/app/api/auth/signup/route.ts) β - 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:
- Frontend (
src/views/Auth/Login.tsx) β - Redux Action (
src/store/api/authApi.ts) β - Next.js API Route (
src/app/api/auth/login/route.ts) β - 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:
- Redux Action (
src/store/api/authApi.ts) β - Next.js API Route (
src/app/api/auth/logout/route.ts)
Response:
- Deletes
tokenandrefreshTokencookies - Clears local auth state
4. Forgot Passwordβ
Frontend Route: /forgot-password API Flow:
- Frontend β
- Redux Action (
src/store/api/authApi.ts) β - Next.js API Route (
src/app/api/auth/forgot-password/route.ts) β - 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:
- Frontend β
- Redux Action (
src/store/api/authApi.ts) β - Next.js API Route (
src/app/api/auth/reset-password/route.ts) β - 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:
- Frontend β
- Redux Action (
src/store/api/investor/offeringsApi.ts) β - Next.js API Route (
src/app/api/investors/investment-offerings/route.ts) β - 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
tokencookie - 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:
- Frontend β
- Redux Action (
src/store/api/investor/offeringsApi.ts) β - Next.js API Route (
src/app/api/investors/investment-offering/route.ts) β - Backend Server (
${SERVER_URL}/tdos/${id})
Request Payload:
{
id: string;
}
Response:
{
data: InvestmentOffering;
}
Authentication:
- Requires
tokencookie - Authorization header:
Bearer ${token}
Error Scenarios:
- Unauthorized (401)
- Offering not found (404)
- Server error (500)
3. Investor Historyβ
Frontend Route: /investor/history API Flow:
- Frontend β
- Redux Action (
src/store/api/investor/historyApi.ts) β - Next.js API Route (
src/app/api/investors/history/route.ts) β - 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
tokencookie - 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:
-
Public Routes:
/(login)/sign-up/forgot-password/reset-password/verify-email
-
Protected Routes:
/investor/*(requires investor role)/broker/*(requires broker role)
-
Route Protection Logic:
- Checks for
tokencookie - Validates user role
- Redirects unauthorized access
- Handles role-based access control
- Excludes static assets and API routes from protection
- Checks for
Error Handlingβ
All API routes implement consistent error handling:
- Authentication errors (401)
- Server errors (500)
- Validation errors (400)
- Not found errors (404)
- Rate limiting errors (429)
- 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:
-
Auth State (
authApi):- Authentication status
- User information
- Token management
- Login/Signup state
-
Investment Offerings (
investorOfferingsApi):- List of offerings
- Single offering details
- Filtering and sorting state
- Pagination state
-
Investor History (
historyApi):- Transaction history
- Filtering state
- Pagination state
-
General Auth State (
authReducer):- User preferences
- UI state
- Session management
Security Measuresβ
-
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
-
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
-
Environment Variables:
- Sensitive configuration stored in environment variables
- Different configurations for development and production
- Server URL and API tokens managed through Cloudflare Pages
-
Cloudflare Integration:
- KV namespace for caching
- Edge runtime for better performance
- DDoS protection
- SSL/TLS encryption
Development and Deploymentβ
-
Local Development:
npm run dev # Development server with Turbopack
npm run preview # Preview production build
npm run build # Production build -
Deployment:
npm run deploy # Deploy to Cloudflare Pages -
Environment Setup:
- Configure environment variables in Cloudflare Pages
- Set up KV namespace bindings
- Configure custom domains if needed
-
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β
-
High Priority
- Session management and token refresh
- Investment action flows
- Document management
- Error logging and tracking
- Rate limiting
-
Medium Priority
- Broker management features
- Data export functionality
- Caching strategy
- Performance metrics
- Progressive loading
-
Low Priority
- Analytics and reporting
- Bulk operations
- Accessibility features
- Offline support
- Advanced security headers
Development Guidelinesβ
-
Code Organization
- Follow the existing directory structure
- Use TypeScript for all new features
- Implement proper error boundaries
- Add comprehensive unit tests
-
API Design
- Follow RESTful principles
- Use consistent error formats
- Implement proper validation
- Document all new endpoints
-
Security
- Implement all security measures
- Follow OWASP guidelines
- Regular security audits
- Proper secret management
-
Performance
- Implement caching where appropriate
- Use proper indexing
- Optimize database queries
- Monitor performance metrics
-
Testing
- Unit tests for all new features
- Integration tests for API endpoints
- E2E tests for critical flows
- Performance testing