Authentication API
Complete reference for authentication endpoints and JWT token management
Overview
The WI-CARPOOL authentication system uses JWT (JSON Web Tokens) for secure user authentication. All authentication endpoints return standardized responses with status codes and user data.
π JWT Tokens
Secure token-based authentication with automatic expiration handling.
π± Multi-platform
Support for web, mobile, and social authentication methods.
π₯ User Types
Separate authentication flows for drivers and passengers.
π‘οΈ Security
Built-in security features including OTP verification and password reset.
Authentication Service
Service Implementation
// Location: src/api/services/authService.ts
export const authService = {
// User Registration
register: (userData) => apiCall(AppConstants.register, userData),
// User Login
login: (credentials) => apiCall(AppConstants.login, credentials),
// Social Authentication
socialSignup: (socialData) => apiCall(AppConstants.socialSignup, socialData),
// OTP Verification
otpVerification: (otpData) => apiCall(AppConstants.otpVerification, otpData),
// Password Reset
forgotPassword: (email) => apiCall(AppConstants.forgotPassword, { email }),
resetPassword: (resetData) => apiCall(AppConstants.resetPassword, resetData),
// Validation
numberValidation: (phoneNumber) => apiCall(AppConstants.numberValidation, phoneNumber),
emailValidation: (email) => apiCall(AppConstants.emailValidation, { email }),
// Session Management
logout: () => apiCall(AppConstants.logout),
updateDevice: (deviceData) => apiCall(AppConstants.updateDevice, deviceData)
};
User Registration
POST /register
Register a new user account with complete profile information.
Request Body
{
"first_name": "John",
"last_name": "Doe",
"email_id": "[email protected]",
"mobile_number": "1234567890",
"country_code": "+1",
"password": "securePassword123",
"user_type": "Rider", // or "Driver"
"device_type": "2", // 2 for web
"device_id": "unique-device-identifier",
"device_token": "web-token-12345678",
"gender": "male",
"auth_type": "email",
"language": "en",
"new_user": "0",
"referral_code": ""
}
Success Response
{
"status_code": "1",
"status_message": "Registration successful",
"data": {
"user_id": 123,
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"mobile_number": "1234567890",
"country_code": "+1",
"user_type": "Rider",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"profile_picture": "",
"currency_code": "USD",
"language_code": "en",
"is_verified": false
}
}
Frontend Implementation
// Registration in AuthProvider
const signUp = async (params: SignUpParams) => {
const response = await authService.register({
first_name: params.firstName,
last_name: params.lastName,
email_id: params.email,
mobile_number: params.phoneNumber,
country_code: params.countryCode,
password: params.password,
user_type: params.userType,
device_type: "2",
device_id: generateDeviceId(),
device_token: `web-token-${deviceId.slice(0, 8)}`,
gender: 'male',
auth_type: 'email',
language: 'en',
new_user: '0',
referral_code: ''
});
// Store user data and token
localStorage.setItem("user", JSON.stringify(userData));
};
User Login
POST /login
Authenticate existing users with phone number and password.
Request Body
{
"mobile_number": "1234567890",
"country_code": "+1",
"password": "userPassword123",
"user_type": "Rider", // or "Driver"
"device_type": "2",
"device_id": "unique-device-identifier",
"device_token": "web-token-12345678",
"language": "en"
}
Success Response
{
"status_code": "1",
"status_message": "Login successful",
"data": {
"user_id": 123,
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"mobile_number": "1234567890",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"profile_picture": "https://example.com/profile.jpg",
"currency_code": "USD",
"language_code": "en",
"is_verified": true,
"wallet_balance": 50.00
}
}
Frontend Implementation
// Login in AuthProvider
const signIn = async (params: SignInParams) => {
const response = await authService.login({
mobile_number: params.phoneNumber,
country_code: params.countryCode,
password: params.password,
user_type: params.userType,
device_type: "2",
device_id: generateDeviceId(),
device_token: `web-token-${deviceId.slice(0, 8)}`,
language: "en"
});
// Transform and store user data
const userData: User = {
id: String(response.user_id),
token: response.access_token,
// ... other user properties
};
setUser(userData);
localStorage.setItem("user", JSON.stringify(userData));
};
Social Authentication
POST /socialsignup
Authenticate users through social media platforms like Google, Facebook, or Apple.
Request Body
{
"auth_type": "google", // or "facebook", "apple"
"social_id": "google-user-id-12345",
"first_name": "John",
"last_name": "Doe",
"email_id": "[email protected]",
"profile_picture": "https://lh3.googleusercontent.com/...",
"user_type": "Rider",
"device_type": "2",
"device_id": "unique-device-identifier",
"device_token": "web-token-12345678",
"language": "en"
}
POST /apple_callback
Handle Apple Sign-In callback with identity token verification.
Request Body
{
"identity_token": "apple-identity-token",
"authorization_code": "apple-auth-code",
"user_identifier": "apple-user-id",
"email": "[email protected]",
"first_name": "John",
"last_name": "Doe",
"user_type": "Rider"
}
OTP Verification
POST /otp_verification
Verify user phone numbers using SMS-based OTP codes.
Request Body
{
"mobile_number": "1234567890",
"country_code": "+1",
"otp_code": "123456",
"verification_type": "registration" // or "password_reset"
}
Success Response
{
"status_code": "1",
"status_message": "OTP verified successfully",
"data": {
"verification_token": "temp-verification-token",
"expires_at": "2024-01-01T12:00:00Z",
"next_step": "complete_registration"
}
}
POST /verify_ride_otp
Verify OTP codes specifically for ride-related actions.
Request Body
{
"ride_id": 456,
"otp_code": "987654",
"action": "start_ride" // or "end_ride"
}
Password Management
POST /forgotpassword
Initiate password reset process by sending reset token to user's email.
Request Body
{
"email": "[email protected]"
}
Success Response
{
"status_code": "1",
"status_message": "Password reset email sent",
"data": {
"reset_token_sent": true,
"email": "[email protected]",
"expires_in": 3600 // seconds
}
}
POST /resetpassword
Complete password reset using the token received via email.
Request Body
{
"reset_token": "password-reset-token-12345",
"new_password": "newSecurePassword123",
"confirm_password": "newSecurePassword123"
}
Validation Endpoints
POST /numbervalidation
Validate phone number format and availability.
Request Body
{
"mobile_number": "1234567890",
"country_code": "+1"
}
Response
{
"status_code": "1",
"status_message": "Phone number is valid and available",
"data": {
"is_valid": true,
"is_available": true,
"formatted_number": "+11234567890"
}
}
POST /emailvalidation
Validate email format and check availability.
Request Body
{
"email": "[email protected]"
}
Response
{
"status_code": "1",
"status_message": "Email is valid and available",
"data": {
"is_valid": true,
"is_available": true,
"domain_valid": true
}
}
Session Management
POST /logout
Invalidate user session and revoke authentication token.
Request Headers
Authorization: Bearer {access_token}
Content-Type: application/json
Success Response
{
"status_code": "1",
"status_message": "Logout successful",
"data": {
"logout_time": "2024-01-01T12:00:00Z",
"session_invalidated": true
}
}
POST /update_device
Update device information for push notifications and security.
Request Body
{
"device_id": "new-device-identifier",
"device_token": "new-push-token-12345",
"device_type": "2",
"platform": "web",
"app_version": "1.0.0",
"os_version": "15.0"
}
POST /language
Update user's preferred language setting.
Request Body
{
"language_code": "es", // Spanish
"country_code": "ES"
}
System Data Endpoints
GET /company_list
Retrieve list of supported companies or organizations.
Response
{
"status_code": "1",
"status_message": "Companies retrieved successfully",
"data": {
"companies": [
{
"id": 1,
"name": "ABC Corporation",
"code": "ABC",
"logo": "https://example.com/abc-logo.png"
},
{
"id": 2,
"name": "XYZ Industries",
"code": "XYZ",
"logo": "https://example.com/xyz-logo.png"
}
]
}
}
GET /language_list
Get list of supported languages for the application.
Response
{
"status_code": "1",
"status_message": "Languages retrieved successfully",
"data": {
"languages": [
{
"code": "en",
"name": "English",
"native_name": "English",
"flag": "πΊπΈ"
},
{
"code": "es",
"name": "Spanish",
"native_name": "EspaΓ±ol",
"flag": "πͺπΈ"
}
]
}
}
GET /currency_list
Retrieve supported currencies and exchange rates.
Response
{
"status_code": "1",
"status_message": "Currencies retrieved successfully",
"data": {
"currencies": [
{
"code": "USD",
"name": "US Dollar",
"symbol": "$",
"exchange_rate": 1.0
},
{
"code": "EUR",
"name": "Euro",
"symbol": "β¬",
"exchange_rate": 0.85
}
]
}
}
GET /country_list
Get list of supported countries with phone codes.
Response
{
"status_code": "1",
"status_message": "Countries retrieved successfully",
"data": {
"countries": [
{
"id": 1,
"name": "United States",
"code": "US",
"phone_code": "+1",
"flag": "πΊπΈ",
"currency": "USD"
},
{
"id": 2,
"name": "United Kingdom",
"code": "GB",
"phone_code": "+44",
"flag": "π¬π§",
"currency": "GBP"
}
]
}
}
Token Management
JWT Token Structure
Access tokens are JWT tokens containing user information and permissions:
Token Payload Example
{
"user_id": 123,
"user_type": "Rider",
"email": "[email protected]",
"device_id": "device-12345",
"iat": 1640995200, // Issued at
"exp": 1641081600, // Expires at
"permissions": ["ride:book", "profile:update"]
}
Token Usage
Include the token in API requests for authenticated endpoints:
Authorization Header
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
URL Parameter (Alternative)
GET /api/profile?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Token Refresh
Tokens automatically refresh on successful API calls. Handle token expiration:
Expiration Handling
// Automatic token validation in AuthProvider
useEffect(() => {
const validateToken = () => {
if (user?.token) {
try {
const tokenParts = user.token.split('.');
const payload = JSON.parse(atob(tokenParts[1]));
const currentTime = Date.now() / 1000;
if (payload.exp && payload.exp < currentTime) {
// Token expired, sign out user
signOut();
}
} catch (error) {
console.error("Token validation error:", error);
}
}
};
// Validate every 5 minutes
const interval = setInterval(validateToken, 5 * 60 * 1000);
return () => clearInterval(interval);
}, [user]);
Error Handling
Error Response Format
All authentication errors follow a consistent format:
Error Response
{
"status_code": "0",
"status_message": "Invalid credentials",
"data": {
"error_code": "AUTH_001",
"error_details": "The provided phone number and password combination is incorrect",
"retry_after": 300 // seconds before retry allowed
}
}
Common Error Codes
Error Code | HTTP Status | Description | Resolution |
---|---|---|---|
AUTH_001 | 401 | Invalid credentials | Check phone number and password |
AUTH_002 | 401 | Token expired | Re-authenticate user |
AUTH_003 | 400 | Invalid OTP code | Request new OTP or check code |
AUTH_004 | 409 | User already exists | Use login instead of registration |
AUTH_005 | 400 | Invalid phone number format | Validate phone number format |
AUTH_006 | 429 | Too many attempts | Wait before retrying |
Error Handling Implementation
Frontend Error Handling
// In axios interceptor
axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
const { status } = error.response;
switch (status) {
case 401:
// Unauthorized - redirect to login
localStorage.removeItem('user');
window.location.href = '/signin';
break;
case 429:
// Too many requests - show retry message
toast({
title: 'Too many attempts',
description: 'Please wait before trying again.',
variant: 'destructive'
});
break;
default:
// General error handling
const errorMessage = error.response?.data?.status_message ||
'An error occurred';
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive'
});
}
return Promise.reject(error);
}
);
Security Considerations
π Token Security
JWT tokens are stored securely and automatically expire after a set period.
π‘οΈ HTTPS Only
All authentication endpoints require HTTPS encryption in production.
π Rate Limiting
API endpoints have rate limiting to prevent brute force attacks.
π± Device Tracking
Each login session is tied to a specific device for security monitoring.
Best Practices
- Token Storage - Store tokens in secure, httpOnly localStorage
- Token Validation - Always validate token expiration before API calls
- Logout Cleanup - Clear all stored user data on logout
- Error Handling - Never expose sensitive error details to users
- HTTPS Enforcement - Ensure all authentication traffic uses HTTPS
- Input Validation - Validate all user inputs before sending to API