Skip to content

de.auth - Authentication Service

Central authentication and user management service for the De. platform.

Service Overview

de.auth handles all authentication flows, user management, and session control across the entire De. platform. It provides secure, scalable authentication with support for multiple channels.

Base URL: https://auth.dedot.io

Key Features

Multi-Channel Auth

Phone (SMS), email/password, and OAuth (Google, Apple) support

Session Management

JWT-based tokens with automatic refresh and revocation

User Profiles

Complete profile management with avatar uploads and preferences

Security First

Encrypted storage, rate limiting, and audit logging built-in

Architecture

de.auth Request Flow
Client App de.auth API Fastify Server MongoDB User Database AWS S3 File Storage

Technology Stack

Tech Stack
Component
Technology
Purpose
Web Framework
Fastify
High-performance HTTP server
Database
MongoDB
User data and sessions
Authentication
JWT
Token generation and validation
File Storage
AWS S3
Avatar and document uploads
SMS Provider
Twilio
Verification code delivery

API Endpoints

Authentication Routes

1

POST /auth/signin

Initiate authentication flow

Request:

typescript
{
  phone?: string        // For phone auth
  email?: string        // For email auth
  password?: string     // For email auth
  type: 'phone' | 'email' | 'oauth'
}

Response:

typescript
{
  success: boolean
  message: string
  data?: {
    verification_sent: boolean
  }
}
2

POST /auth/verify

Verify authentication code

Request:

typescript
{
  phone: string
  code: string
}

Response:

typescript
{
  success: boolean
  data: {
    token: string
    refreshToken: string
    expiresAt: number
    user: User
  }
}
3

POST /auth/refresh

Refresh access token

Request:

typescript
{
  refreshToken: string
}

Response:

typescript
{
  success: boolean
  data: {
    token: string
    expiresAt: number
  }
}
4

POST /auth/signout

Revoke tokens and end session

Headers:

Authorization: Bearer {access_token}

Response:

typescript
{
  success: boolean
  message: string
}

User Management Routes

1

GET /user

Get current user profile

Headers:

Authorization: Bearer {access_token}

Response:

typescript
{
  success: boolean
  data: {
    uid: string
    profile: {
      firstName: string
      lastName: string
      phone: string
      email?: string
      photo?: string
    }
    account: {
      types: string[]
      workspace: string
      createdAt: string
    }
  }
}
2

PATCH /user/profile

Update user profile

Headers:

Authorization: Bearer {access_token}

Request:

typescript
{
  profile: {
    firstName?: string
    lastName?: string
    email?: string
  }
}

Response:

typescript
{
  success: boolean
  data: User
}
3

GET /user/active-ids

Get active user IDs

Headers:

Authorization: Bearer {access_token}

Query Parameters:

limit?: number (default: 100)
offset?: number (default: 0)

Response:

typescript
{
  success: boolean
  data: {
    users: string[]
    total: number
  }
}

Utility Routes

1

POST /utilities/upload

Upload avatar or documents

Headers:

Authorization: Bearer {access_token}
Content-Type: multipart/form-data

Request:

file: File (image or document)

Response:

typescript
{
  success: boolean
  data: {
    url: string
    filename: string
    size: number
    mimeType: string
  }
}

Data Models

User Object

typescript
interface User {
  uid: string
  profile: {
    firstName: string
    lastName: string
    phone: string
    email?: string
    photo?: string
    bio?: string
  }
  account: {
    types: ('customer' | 'driver' | 'admin' | 'developer')[]
    workspace: string
    createdAt: string
    updatedAt: string
  }
  connection?: {
    lastLogin: string
    ipAddress: string
    userAgent: string
  }
  settings?: {
    notifications: boolean
    language: string
    timezone: string
  }
}

Token Object

typescript
interface TokenResponse {
  token: string           // JWT access token
  refreshToken: string    // Refresh token
  expiresAt: number      // Unix timestamp
  tokenType: 'Bearer'
}

Security Features

Encryption

  • Passwords hashed with bcrypt (cost factor 12)
  • JWT tokens signed with RS256
  • TLS 1.3 for all connections
  • Data encrypted at rest in MongoDB

Rate Limiting

  • 5 sign-in attempts per phone/email per hour
  • 3 verification attempts per code
  • 100 API requests per user per minute
  • IP-based throttling for suspicious activity

Session Management

  • Access tokens expire in 1 hour
  • Refresh tokens expire in 30 days
  • Automatic token refresh before expiration
  • Device tracking and session revocation

Audit Logging

  • All authentication attempts logged
  • User profile changes tracked
  • Failed login attempts monitored
  • Suspicious activity alerts

Configuration

Environment Variables

bash
# Server Configuration
AUTH_PORT=3001
AUTH_HOST=0.0.0.0

# Database
MONGODB_URI=mongodb://localhost:27017/de-auth
MONGODB_DATABASE=de-auth

# JWT Configuration
JWT_SECRET=your-secret-key
JWT_EXPIRY=3600
REFRESH_TOKEN_EXPIRY=2592000

# AWS S3
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
AWS_BUCKET=de-auth-uploads

# Twilio (SMS)
TWILIO_ACCOUNT_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-auth-token
TWILIO_PHONE_NUMBER=+1234567890

# Redis (Optional - for rate limiting)
REDIS_URL=redis://localhost:6379

Usage Examples

Phone Authentication Flow

typescript
import De from '@de./sdk'

const access = new De.Access({
  workspace: 'your-workspace-id',
  env: 'prod'
})

// Step 1: Request verification code
await access.request({
  url: '/auth/signin',
  method: 'POST',
  body: {
    phone: '+1234567890',
    type: 'phone'
  }
})

// User receives SMS with code

// Step 2: Verify code
const result = await access.request({
  url: '/auth/verify',
  method: 'POST',
  body: {
    phone: '+1234567890',
    code: '123456'
  }
})

// Store token
const { token, refreshToken } = result.data
localStorage.setItem('access_token', token)
localStorage.setItem('refresh_token', refreshToken)

// Step 3: Use authenticated access
const authenticatedAccess = new De.Access({
  workspace: 'your-workspace-id',
  accessToken: token,
  env: 'prod'
})

// Get user profile
const user = await authenticatedAccess.request({
  url: '/user',
  method: 'GET'
})

console.log('Welcome,', user.data.profile.firstName)

Token Refresh

typescript
async function refreshAccessToken() {
  const refreshToken = localStorage.getItem('refresh_token')
  
  const result = await access.request({
    url: '/auth/refresh',
    method: 'POST',
    body: { refreshToken }
  })
  
  localStorage.setItem('access_token', result.data.token)
  return result.data.token
}

// Auto-refresh before expiration
setInterval(async () => {
  try {
    await refreshAccessToken()
  } catch (error) {
    // Redirect to login if refresh fails
    window.location.href = '/login'
  }
}, 55 * 60 * 1000) // Refresh every 55 minutes

Error Handling

Common Errors

Error Codes
Status Code
Error
Description
400
INVALID_PHONE
Phone number format invalid
401
INVALID_CODE
Verification code incorrect
401
TOKEN_EXPIRED
Access token has expired
429
RATE_LIMIT
Too many attempts
409
USER_EXISTS
User already registered

Deployment

Docker Compose

yaml
version: '3.8'

services:
  de-auth:
    image: dedot/de-auth:latest
    ports:
      - "3001:3001"
    environment:
      - MONGODB_URI=mongodb://mongo:27017/de-auth
      - JWT_SECRET=${JWT_SECRET}
      - AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
      - AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
    depends_on:
      - mongo
    networks:
      - de-network

  mongo:
    image: mongo:6
    volumes:
      - auth-data:/data/db
    networks:
      - de-network

volumes:
  auth-data:

networks:
  de-network:
    driver: bridge

Monitoring

Health Check Endpoint

bash
GET /health

Response:
{
  "status": "healthy",
  "uptime": 86400,
  "version": "1.0.0",
  "database": "connected",
  "redis": "connected"
}

Metrics

Monitor these key metrics:

  • Authentication success rate
  • Token refresh rate
  • Average response time
  • Active sessions count
  • Failed login attempts
  • Database connection pool

Next Steps