Authentication - Smart-Cart-System/backend-fastapi GitHub Wiki

Authentication Module Documentation for Frontend

Endpoints

1. User Signup

  • URL: /auth/signup
  • Method: POST
  • Description: Creates a new user account with hashed password storage.
  • Address: can be null.
  • Request Body: UserCreate schema (JSON format)
    {
      "username": "string",
      "email": "string",
      "password": "string",
      "mobile_number": "string",
      "age": "integer",
      "full_name": "string",
      "address": "string"
    }
    
  • Response:
    • 200 OK: User created successfully, returns User schema.
    • 400 Bad Request: Username already registered.

2. User Login

  • URL: /auth/login
  • Method: POST
  • Description: Authenticates user credentials and returns access token with user details.
  • Request Body: OAuth2 form data with username and password
  • Response:
    • 200 OK: Returns authentication token and complete user profile.
      {
        "username": "string",
        "email": "string",
        "phone_number": "string",
        "full_name": "string",
        "access_token": "string",
        "token_type": "bearer",
        "user_id": "integer",
        "expires_in": 21600,
        "address": "string"
      }
      
    • 401 Unauthorized: Incorrect username or password.

Schemas

1. UserCreate

  • Fields:
    • username (str): Unique username for the account.
    • email (str): User's email address.
    • password (str): Plain text password (will be hashed automatically).
    • mobile_number (str): User's mobile phone number.
    • age (int): User's age.
    • full_name (str): User's complete name.
    • address (str): User's physical address.

2. User

  • Fields:
    • id (int): Unique user identifier.
    • username (str): User's username.
    • email (str): User's email address.
    • mobile_number (str): User's mobile phone number.
    • age (int): User's age.
    • full_name (str): User's complete name.
    • address (str): User's physical address.
    • hashed_password (str): Encrypted password (for internal use only).

Authentication Flow

Token Management

  • Token Type: Bearer token
  • Expiration: 6 hours (21600 seconds) from creation
  • Storage: Include expires_in field to track token validity
  • Usage: Include in Authorization header as Bearer <access_token> for protected endpoints

Security Features

  • Password Hashing: All passwords are securely hashed before storage
  • Token-Based Authentication: Uses JWT tokens for stateless session management
  • Username Uniqueness: Enforces unique usernames across the system
  • Comprehensive User Data: Returns complete user profile on successful login

Frontend Integration Guide

Signup Implementation

// Example signup request
const signupData = {
  username: "john_doe",
  email: "[email protected]",
  password: "securePassword123",
  mobile_number: "+1234567890",
  age: 30,
  full_name: "John Doe",
  address: "123 Main St, City"
};

const response = await fetch('/auth/signup', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(signupData)
});

Login Implementation

// Example login request
const formData = new FormData();
formData.append('username', 'john_doe');
formData.append('password', 'securePassword123');

const response = await fetch('/auth/login', {
  method: 'POST',
  body: formData
});

const loginData = await response.json();
// Store token and user data
localStorage.setItem('access_token', loginData.access_token);
localStorage.setItem('user_id', loginData.user_id);
localStorage.setItem('expires_at', Date.now() + (loginData.expires_in * 1000));

Token Usage in Subsequent Requests

// Include token in API requests
const token = localStorage.getItem('access_token');
const response = await fetch('/protected-endpoint', {
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});

Error Handling

Common Error Responses

  1. 400 Bad Request: "Username already registered" - Username exists during signup
  2. 401 Unauthorized: "Incorrect username or password" - Invalid login credentials
  3. 422 Unprocessable Entity: Invalid request data format or missing required fields

Best Practices for Frontend

Token Management

  • Store access_token securely (consider httpOnly cookies for production)
  • Monitor expires_in to implement token refresh logic
  • Clear all stored data on logout
  • Handle token expiration gracefully with automatic logout

User Data Handling

  • Store essential user data (user_id, username, email, etc.) for UI personalization
  • Use phone_number and address for checkout/delivery processes
  • Display full_name in user interface elements

Security Considerations

  • Never store passwords in frontend code
  • Validate token expiration before making API calls
  • Implement proper logout functionality that clears all stored tokens
  • Use HTTPS in production environments

Admin Authentication

1. Admin User Creation

URL

POST /auth/signup

Description

Creates a new admin user with elevated privileges. This endpoint requires a special admin secret key for authorization.

Headers

  • Content-Type: application/json
  • admin_secret: YOUR_ADMIN_SECRET_KEY (Required for admin creation)

Request Body

{
  "username": "adminuser",
  "email": "[email protected]",
  "password": "strongPassword123",
  "mobile_number": "+1234567890",
  "age": 30,
  "full_name": "Admin User",
  "address": "123 Admin St",
  "is_admin": true
}

Response

200 OK: Admin user created successfully

{
  "username": "adminuser",
  "email": "[email protected]",
  "mobile_number": "+1234567890",
  "age": 30,
  "full_name": "Admin User",
  "address": "123 Admin St",
  "id": 1,
  "is_admin": true
}

400 Bad Request: Username already exists

{
  "detail": "Username already registered"
}

403 Forbidden: Invalid admin secret key

{
  "status_code": 403,
  "message": "Invalid admin secret key",
  "details": {}
}

2. Admin Login

URL

POST /auth/login

Description

Authenticates an admin user and returns an access token with admin privileges.

Request Body

Form data with username and password:

username=adminuser
password=strongPassword123

Response

200 OK: Returns authentication token and user profile with admin status

{
  "username": "adminuser",
  "email": "[email protected]",
  "phone_number": "+1234567890",
  "full_name": "Admin User",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "user_id": 1,
  "expires_in": 21600,
  "address": "123 Admin St",
  "is_admin": true
}

401 Unauthorized: Incorrect username or password

Admin API Endpoints

1. List All Users

URL

GET /admin/users

Description

Retrieves a list of all users in the system. This endpoint is restricted to admin users only.

Headers

Authorization: Bearer YOUR_ADMIN_TOKEN

Response

200 OK: Returns a list of all users

[
  {
    "id": 1,
    "username": "adminuser",
    "email": "[email protected]",
    "mobile_number": "+1234567890",
    "age": 30,
    "full_name": "Admin User",
    "address": "123 Admin St",
    "is_admin": true
  },
  {
    "id": 2,
    "username": "regularuser",
    "email": "[email protected]",
    "mobile_number": "+0987654321",
    "age": 25,
    "full_name": "Regular User",
    "address": "456 User St",
    "is_admin": false
  }
]

403 Forbidden: Caller is not an admin

{
  "detail": "This operation requires admin privileges"
}

2. Access User-Specific Data

Other user-specific APIs can be accessed by admins regardless of the user ID, including:

  • Product suggestions for any user
  • User session data
  • User shopping history
  • User feedback

Example: Get Product Suggestions for Any User

GET /products/suggestions/{user_id}?count=8
Authorization: Bearer YOUR_ADMIN_TOKEN

Non-admin users can only access their own suggestions, but admin users can access suggestions for any user.

Admin Configuration

Environment Setup

To enable admin functionality, add the following to your .env file: ####ask the backend team for the admin secret key This secret key will be required when creating admin users.