Code Examples

Ready-to-use code examples for common Fayda Authentication scenarios.

Basic Authentication Flow
Complete authentication flow using the JavaScript SDK.
javascript
import { FaydaAuth } from 'fayda-auth';

const fayda = new FaydaAuth({
  apiKey: process.env.FAYDA_API_KEY
});

async function authenticateUser(fcn) {
  try {
    // Step 1: Initiate OTP
    const otpResult = await fayda.initiateOTP(fcn);
    
    // Display masked mobile to user
    console.log(`OTP sent to: ${otpResult.maskedMobile}`);
    
    // Step 2: Get OTP from user input
    const otp = prompt('Enter the OTP code:');
    
    // Step 3: Verify OTP
    const verifyResult = await fayda.verifyOTP(
      otpResult.transactionId, 
      otp, 
      fcn
    );
    
    // Success - user is authenticated
    return {
      success: true,
      user: verifyResult.user,
      photo: verifyResult.photo,
      qrCode: verifyResult.qrCode
    };
    
  } catch (error) {
    console.error('Authentication failed:', error.message);
    return {
      success: false,
      error: error.error,
      message: error.message
    };
  }
}

// Usage
authenticateUser('1234567890123456')
  .then(result => {
    if (result.success) {
      console.log('Welcome,', result.user.fullName[0].value);
    } else {
      console.log('Authentication failed:', result.message);
    }
  });
React Integration
Complete React component for Fayda authentication.
jsx
import React, { useState } from 'react';
import { FaydaAuth } from 'fayda-auth';

const fayda = new FaydaAuth({
  apiKey: process.env.REACT_APP_FAYDA_API_KEY
});

function FaydaAuthComponent() {
  const [fcn, setFcn] = useState('');
  const [otp, setOtp] = useState('');
  const [transactionId, setTransactionId] = useState('');
  const [maskedMobile, setMaskedMobile] = useState('');
  const [step, setStep] = useState('fcn'); // 'fcn', 'otp', 'success'
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [user, setUser] = useState(null);

  const handleInitiateOTP = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const result = await fayda.initiateOTP(fcn);
      setTransactionId(result.transactionId);
      setMaskedMobile(result.maskedMobile);
      setStep('otp');
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOTP = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const result = await fayda.verifyOTP(transactionId, otp, fcn);
      setUser(result.user);
      setStep('success');
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setFcn('');
    setOtp('');
    setTransactionId('');
    setMaskedMobile('');
    setStep('fcn');
    setError('');
    setUser(null);
  };

  if (step === 'success' && user) {
    return (
      <div className="max-w-md mx-auto p-6 bg-green-50 border border-green-200 rounded-lg">
        <h2 className="text-xl font-semibold text-green-800 mb-4">
          Authentication Successful!
        </h2>
        <div className="space-y-2 text-sm">
          <p><strong>Name:</strong> {user.fullName[0].value}</p>
          <p><strong>UIN:</strong> {user.uin}</p>
          <p><strong>Phone:</strong> {user.phone}</p>
          <p><strong>Date of Birth:</strong> {user.dateOfBirth}</p>
        </div>
        <button
          onClick={resetForm}
          className="mt-4 w-full bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700"
        >
          Authenticate Another User
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto p-6 bg-white border border-gray-200 rounded-lg">
      <h2 className="text-xl font-semibold mb-4">Fayda Authentication</h2>
      
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded text-red-700 text-sm">
          {error}
        </div>
      )}

      {step === 'fcn' && (
        <form onSubmit={handleInitiateOTP}>
          <div className="mb-4">
            <label htmlFor="fcn" className="block text-sm font-medium text-gray-700 mb-2">
              Fayda Card Number
            </label>
            <input
              type="text"
              id="fcn"
              value={fcn}
              onChange={(e) => setFcn(e.target.value)}
              placeholder="Enter 16-digit FCN"
              maxLength={16}
              className="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>
          <button
            type="submit"
            disabled={loading || fcn.length !== 16}
            className="w-full bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? 'Sending OTP...' : 'Send OTP'}
          </button>
        </form>
      )}

      {step === 'otp' && (
        <form onSubmit={handleVerifyOTP}>
          <div className="mb-4">
            <p className="text-sm text-gray-600 mb-2">
              OTP sent to: {maskedMobile}
            </p>
            <label htmlFor="otp" className="block text-sm font-medium text-gray-700 mb-2">
              Enter OTP Code
            </label>
            <input
              type="text"
              id="otp"
              value={otp}
              onChange={(e) => setOtp(e.target.value)}
              placeholder="Enter 6-digit OTP"
              maxLength={6}
              className="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>
          <div className="flex space-x-2">
            <button
              type="button"
              onClick={() => setStep('fcn')}
              className="flex-1 bg-gray-300 text-gray-700 py-2 px-4 rounded hover:bg-gray-400"
            >
              Back
            </button>
            <button
              type="submit"
              disabled={loading || otp.length !== 6}
              className="flex-1 bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? 'Verifying...' : 'Verify OTP'}
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

export default FaydaAuthComponent;
Node.js Backend Integration
Server-side authentication with Express.js.
javascript
const express = require('express');
const { FaydaAuth } = require('fayda-auth');

const app = express();
app.use(express.json());

const fayda = new FaydaAuth({
  apiKey: process.env.FAYDA_API_KEY,
  debug: process.env.NODE_ENV === 'development'
});

// Store active OTP sessions (use Redis in production)
const otpSessions = new Map();

// Initiate OTP endpoint
app.post('/api/fayda/otp/initiate', async (req, res) => {
  try {
    const { fcn } = req.body;
    
    if (!fcn || fcn.length !== 16) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_FCN',
        message: 'FCN must be exactly 16 digits'
      });
    }

    const result = await fayda.initiateOTP(fcn);
    
    // Store session for verification
    otpSessions.set(result.transactionId, {
      fcn,
      createdAt: new Date(),
      expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10 minutes
    });

    res.json({
      success: true,
      transactionId: result.transactionId,
      maskedMobile: result.maskedMobile,
      message: result.message
    });

  } catch (error) {
    res.status(error.statusCode || 500).json({
      success: false,
      error: error.error || 'INTERNAL_ERROR',
      message: error.message
    });
  }
});

// Verify OTP endpoint
app.post('/api/fayda/otp/verify', async (req, res) => {
  try {
    const { transactionId, otp } = req.body;
    
    if (!transactionId || !otp) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_PARAMETERS',
        message: 'Transaction ID and OTP are required'
      });
    }

    // Check if session exists and is valid
    const session = otpSessions.get(transactionId);
    if (!session || new Date() > session.expiresAt) {
      otpSessions.delete(transactionId);
      return res.status(400).json({
        success: false,
        error: 'INVALID_TRANSACTION_ID',
        message: 'Invalid or expired transaction ID'
      });
    }

    const result = await fayda.verifyOTP(transactionId, otp, session.fcn);
    
    // Clean up session
    otpSessions.delete(transactionId);

    res.json({
      success: true,
      user: result.user,
      hasPhoto: !!result.photo,
      hasQRCode: !!result.qrCode
    });

  } catch (error) {
    res.status(error.statusCode || 500).json({
      success: false,
      error: error.error || 'INTERNAL_ERROR',
      message: error.message
    });
  }
});

// Clean up expired sessions periodically
setInterval(() => {
  const now = new Date();
  for (const [transactionId, session] of otpSessions.entries()) {
    if (now > session.expiresAt) {
      otpSessions.delete(transactionId);
    }
  }
}, 5 * 60 * 1000); // Clean up every 5 minutes

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
Python Integration
Python implementation using the requests library.
python
import requests
import json
import base64
from typing import Dict, Optional, Any

class FaydaAuth:
    def __init__(self, api_key: str, base_url: str = "https://fayda-auth.vercel.app", timeout: int = 30):
        self.api_key = api_key
        self.base_url = base_url.rstrip('/')
        self.timeout = timeout
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json',
            'User-Agent': 'FaydaAuth-Python/1.0.0'
        })

    def initiate_otp(self, fcn: str) -> Dict[str, Any]:
        if not fcn or len(fcn) != 16 or not fcn.isdigit():
            raise FaydaAuthError("INVALID_FCN", "FCN must be exactly 16 digits", 400)
        
        url = f"{self.base_url}/api/fayda/otp/initiate"
        payload = {"fcn": fcn}
        
        try:
            response = self.session.post(url, json=payload, timeout=self.timeout);
            data = response.json();
            
            if not data.get('success'):
                raise FaydaAuthError(
                    data.get('error', 'UNKNOWN_ERROR'),
                    data.get('message', 'Unknown error occurred'),
                    response.status_code
                );
            
            return data;
            
        except requests.exceptions.RequestException as e:
            raise FaydaAuthError("NETWORK_ERROR", f"Network error: {str(e)}", None);

    def verify_otp(self, transaction_id: str, otp: str, fcn: str) -> Dict[str, Any]:
        if not transaction_id:
            raise FaydaAuthError("INVALID_TRANSACTION_ID", "Transaction ID is required", 400);
        
        if not otp or len(otp) != 6 or not otp.isdigit():
            raise FaydaAuthError("INVALID_OTP", "OTP must be exactly 6 digits", 400);
        
        if not fcn or len(fcn) != 16 or not fcn.isdigit():
            raise FaydaAuthError("INVALID_FCN", "FCN must be exactly 16 digits", 400);
        
        url = f"{self.base_url}/api/fayda/otp/verify";
        payload = {
            "transactionId": transaction_id,
            "otp": otp,
            "fcn": fcn
        };
        
        try:
            response = self.session.post(url, json=payload, timeout=self.timeout);
            data = response.json();
            
            if not data.get('success'):
                raise FaydaAuthError(
                    data.get('error', 'UNKNOWN_ERROR'),
                    data.get('message', 'Unknown error occurred'),
                    response.status_code
                );
            
            return data;
            
        except requests.exceptions.RequestException as e:
            raise FaydaAuthError("NETWORK_ERROR", f"Network error: {str(e)}", None);

    def save_user_photo(self, photo_data: Dict[str, str], filename: str) -> None:
        if not photo_data or 'data' not in photo_data:
            raise ValueError("Invalid photo data");
        
        image_data = base64.b64decode(photo_data['data']);
        with open(filename, 'wb') as f:
            f.write(image_data);

    def save_qr_code(self, qr_data: Dict[str, str], filename: str) -> None:
        if not qr_data or 'data' not in qr_data:
            raise ValueError("Invalid QR code data");
        
        image_data = base64.b64decode(qr_data['data']);
        with open(filename, 'wb') as f:
            f.write(image_data);


class FaydaAuthError(Exception):
    def __init__(self, error_code: str, message: str, status_code: Optional[int]):
        self.error_code = error_code
        self.message = message
        self.status_code = status_code
        super().__init__(message);


# Usage example
def authenticate_user(fcn: str) -> Optional[Dict[str, Any]]:
    fayda = FaydaAuth(api_key="your-api-key-here");
    
    try:
        # Step 1: Initiate OTP
        otp_result = fayda.initiate_otp(fcn);
        print(f"OTP sent to: {otp_result['maskedMobile']}");
        
        # Step 2: Get OTP from user
        otp = input("Enter OTP code: ");
        
        # Step 3: Verify OTP
        verify_result = fayda.verify_otp(otp_result['transactionId'], otp, fcn);
        
        # Step 4: Process user data
        user = verify_result['user'];
        print(f"Welcome, {user['fullName'][0]['value']}");
        print(f"UIN: {user['uin']}");
        
        # Save photo and QR code
        fayda.save_user_photo(verify_result['photo'], f"user_{user['uin']}_photo.jpg");
        fayda.save_qr_code(verify_result['qrCode'], f"user_{user['uin']}_qr.png");
        
        return user;
        
    except FaydaAuthError as e:
        print(f"Authentication failed: {e.message}");
        return None;
    except Exception as e:
        print(f"Unexpected error: {str(e)}");
        return None;


if __name__ == "__main__":
    user = authenticate_user("1234567890123456");
    if user:
        print("Authentication successful!");
    else:
        print("Authentication failed!");