Client Auth

Table of Contents

  1. User Authentication - Login
  2. Get User Profile
  3. User Registration

User Authentication - Login

Endpoint: POST /auth/login
Description: Authenticates a user using their email and password and returns a JSON Web Token (JWT) for subsequent API requests.


Request

Method: POST
URL: https://your-domain.com/auth/login

Headers:

  • Content-Type: application/json

Request Body:
A JSON object containing the user's email and password.

FieldTypeRequiredDescription
emailStringYesThe user's email address.
passwordStringYesThe user's password.

Example Request

curl -X POST "https://your-domain.com/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "yourpassword"
  }'

Response

Status Codes:

  • 200 OK: Returned when the user is successfully authenticated.
  • 400 Bad Request: If the email or password is not provided.
  • 401 Unauthorized: If the provided credentials are invalid.
  • 500 Internal Server Error: An unexpected error occurred on the server.

Response Body:
Returns a JSON object containing the authentication token if the login is successful.

Example Successful Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Example Error Response (Missing Fields)

{
  "message": "Username and password are required"
}

Example Error Response (Invalid Credentials)

{
  "message": "Invalid username or password"
}

Notes

  • The provided email and password must match a user in the database.
  • Passwords are securely hashed using bcrypt and validated during login.
  • On successful authentication:
    • A JWT is generated for the user.
    • The lastLogin field in the user's record is updated with the current timestamp.
  • Ensure the token is stored securely on the client side and included in the Authorization header for future API requests.

User Schema

FieldTypeRequiredDefaultDescription
googleIdStringNonullThe user's Google ID for OAuth integration.
emailStringYesThe user's email address (unique identifier).
displayNameStringNonullThe user's display name.
familyNameStringNonullThe user's family/last name.
givenNameStringNonullThe user's given/first name.
photosStringNonullA URL to the user's profile picture.
phoneStringNonullThe user's phone number.
passwordStringYesThe hashed password of the user.
lastLoginDateNonullThe timestamp of the user's last login.

Security Notes

  • Ensure the password field is securely hashed using bcrypt during registration and validated during login.
  • JWT tokens should be securely stored (e.g., HTTP-only cookies or secure storage).
  • Use HTTPS to encrypt all requests containing sensitive information like credentials.

Get User Profile

Endpoint: GET /profile
Description: Retrieves the authenticated user's profile, including customer data if available.


Request

Method: GET
URL: https://your-domain.com/profile

Headers:

  • Authorization: Bearer JWTTOKEN (Required)

Authentication Middleware:
The authenticateToken middleware is required to verify the user's JWT token.


Response

Status Codes:

  • 200 OK: The user's profile data (and associated customer data, if available) is returned.
  • 401 Unauthorized: If the token is invalid, missing, or does not include user information.
  • 404 Not Found: If no user is found for the provided email.
  • 500 Internal Server Error: If an unexpected error occurs during data fetching.

Response Body:
Returns a JSON object containing the user's profile data. If a customer record is associated with the user's email, it will be included in the response under the customer field.

Example Successful Response

{
  "_id": "64f9c0fa8b1234567890abcd",
  "email": "user@example.com",
  "displayName": "John Doe",
  "familyName": "Doe",
  "givenName": "John",
  "photos": "https://example.com/profile.jpg",
  "phone": "1234567890",
  "lastLogin": "2024-12-07T10:30:00.000Z",
  "createdAt": "2024-12-01T12:00:00.000Z",
  "updatedAt": "2024-12-07T12:00:00.000Z",
  "customer": {
    "UniqueId": "CUST-12345",
    "CompanyName": "Example Corp",
    "FirstName": "John",
    "LastName": "Doe",
    "Phone": "1234567890",
    "Email": "user@example.com",
    "Dob": "1990-01-01",
    "TaxDetails": {
      "IsTaxRegistered": "Yes",
      "TaxId": "TAX-123456"
    },
    "BillingAddress": {
      "Address": "123 Main St",
      "City": "Example City",
      "Country": "Example Country",
      "ZipCode": "123456"
    },
    "CustomerType": "Corporate",
    "AccountSetting": {
      "OpeningBalance": 5000,
      "OpeningBalanceAsOn": "2024-01-01T00:00:00.000Z",
      "OpeningBalanceRemarks": "Initial deposit"
    },
    "Travellers": [
      {
        "name": "Jane Doe",
        "relation": "Spouse"
      }
    ]
  }
}

Example Error Response (Unauthorized)

{
  "message": "Unauthorized: No user information found in token"
}

Example Error Response (User Not Found)

{
  "message": "User not found"
}

Example Error Response (Server Error)

{
  "message": "Error fetching user data"
}

Notes

  • The Authorization header must include a valid JWT token.
  • The email is extracted from the token payload (req.user) and is used to fetch the user profile.
  • If a Customer record exists for the user, it is included in the customer field of the response.
  • Password fields are excluded in the response for security reasons.

Customer Schema

FieldTypeRequiredDefaultDescription
UniqueIdStringYesA unique identifier for the customer.
UserStringNoAssociated user identifier.
CompanyNameStringNoThe company name for corporate customers.
FirstNameStringNoThe customer's first name.
LastNameStringNoThe customer's last name.
PhoneStringNoThe customer's phone number.
EmailStringYesThe customer's email address.
DobStringNonullDate of birth of the customer.
TaxDetails.IsTaxRegisteredStringNonullWhether the customer is registered for tax.
TaxDetails.TaxIdStringNonullTax ID of the customer.
BillingAddress.AddressStringNoThe billing address of the customer.
BillingAddress.CityStringNoThe city in the billing address.
BillingAddress.CountryStringNoThe country in the billing address.
BillingAddress.ZipCodeStringNoThe ZIP code in the billing address.
CustomerTypeStringNonullType of customer (B2C, B2B, Corporate).
AccountSetting.OpeningBalanceNumberNo0Opening balance of the customer account.
AccountSetting.OpeningBalanceAsOnDateNoCurrent dateThe date of the opening balance.
AccountSetting.OpeningBalanceRemarksStringNonullRemarks for the opening balance.
TravellersArrayNo[]List of travellers associated with the customer.

User Registration

Endpoint: POST /register
Description: Registers a new user, hashes their password securely, and returns a JSON Web Token (JWT) upon successful registration.


Request

Method: POST
URL: https://your-domain.com/register

Headers:

  • Content-Type: application/json

Request Body:
A JSON object containing the user's registration details.

FieldTypeRequiredDescription
emailStringYesThe user's email address.
passwordStringYesThe user's chosen password.
givenNameStringNoThe user's first name.
familyNameStringNoThe user's last name.

Example Request

curl -X POST "https://your-domain.com/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "yourpassword",
    "givenName": "John",
    "familyName": "Doe"
  }'

Example Request body

{
  "email": "user@example.com",
  "password": "yourpassword",
  "givenName": "John",
  "familyName": "Doe"
}

Response

Status Codes:

  • 201 Created: The user was successfully registered and a JWT is returned.
  • 400 Bad Request: If the email or password fields are missing.
  • 409 Conflict: If a user with the provided email already exists.
  • 500 Internal Server Error: If user registration fails due to a server-side issue.

Response Body:
Returns a JSON object containing the authentication token if registration is successful.

Example Successful Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Example Error Response (Missing Fields)

{
  "message": "Email and password are required"
}

Example Error Response (User Already Exists)

{
  "message": "User already exists"
}

Example Error Response (Server Error)

{
  "message": "User registration failed"
}

Notes

  • Passwords are hashed using bcrypt before being stored in the database to ensure security.
  • The email field must be unique. If a user with the same email already exists, a 409 Conflict error is returned.
  • A JWT token is generated upon successful registration and should be securely stored on the client side for future API requests.

Security Notes

  • Ensure the password is hashed using a secure algorithm like bcrypt before storing it in the database.
  • Use HTTPS to encrypt all requests containing sensitive information like registration details.
  • JWT tokens should be securely stored (e.g., HTTP-only cookies or secure storage) to prevent unauthorized access.