Identity Access Service ‐ API Integration Guide API Overview - Wiz-DevTech/prettygirllz GitHub Wiki

Identity Access Service - API Integration Guide

API Overview

The Identity Access Service exposes both REST APIs and gRPC services for user authentication, authorization, and avatar management. This document provides comprehensive integration details for frontend developers.

Base URLs

  • REST API: http://localhost:8080
  • gRPC: http://localhost:9090
  • WebUI: http://localhost:8080/admin

Authentication & Authorization

JWT Token Authentication

All protected endpoints require a JWT token in the Authorization header:

Authorization: Bearer <JWT_TOKEN>

Token Structure

{
  "sub": "[email protected]",
  "roles": ["ROLE_USER", "ROLE_ADMIN"],
  "iat": 1640995200,
  "exp": 1641081600
}

Permission Levels

  • ROLE_USER: Basic user operations, own data access
  • ROLE_ADMIN: Administrative operations, all user data access

REST API Endpoints

Authentication Endpoints

1. Login

  • URL: POST /admin/auth/api/login
  • Description: Authenticate user and receive JWT token
  • Authentication: None required
  • Request Body:
{
  "email": "[email protected]",
  "password": "password123"
}
  • Response (200 OK):
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "id": 1,
  "email": "[email protected]",
  "roles": ["ROLE_USER"]
}
  • Error Responses:
    • 401 Unauthorized: Invalid credentials
    • 400 Bad Request: Invalid request format

2. Register

  • URL: POST /admin/auth/api/register
  • Description: Create new user account
  • Authentication: None required
  • Request Body:
{
  "email": "[email protected]",
  "password": "securepassword",
  "roles": ["ROLE_USER"]
}
  • Response (200 OK):
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "id": 2,
  "email": "[email protected]",
  "roles": ["ROLE_USER"]
}

User Management Endpoints

3. Get All Users (Admin View)

  • URL: GET /admin/auth/users
  • Description: Retrieve paginated list of users with search
  • Authentication: Required
  • Query Parameters:
    • page (optional): Page number (default: 1)
    • size (optional): Page size (default: 10)
    • search (optional): Search term
  • Response: HTML page (for web UI)

4. Get User by ID

  • URL: GET /admin/auth/users/{id}
  • Description: Get specific user details
  • Authentication: Required (ADMIN or own data)
  • Response (200 OK):
{
  "id": 1,
  "email": "[email protected]",
  "enabled": true,
  "roles": ["ROLE_USER"],
  "createdAt": "2025-01-01T10:00:00Z",
  "updatedAt": "2025-01-01T10:00:00Z"
}

5. Get User Avatar

  • URL: GET /admin/auth/users/{userId}/avatar
  • Description: Retrieve user's avatar image
  • Authentication: Required (ADMIN or own data)
  • Response: Image binary data
  • Headers:
    • Content-Type: image/png or image/jpeg
    • Cache-Control: max-age=604800

6. Upload User Avatar

  • URL: POST /admin/auth/users/{userId}/avatar
  • Description: Upload new avatar image
  • Authentication: Required (ADMIN or own data)
  • Content-Type: multipart/form-data
  • Form Data:
    • avatar: Image file (max 2MB)
  • Response (200 OK):
{
  "success": true,
  "message": "Avatar updated successfully"
}

Avatar Management Endpoints

7. Get User Avatar (API)

  • URL: GET /api/avatars/user/{userId}
  • Description: Get user's avatar configuration and image
  • Authentication: Required (own data or ADMIN)
  • Response (200 OK):
{
  "id": 1,
  "userId": 1,
  "imageUrl": "/static/avatars/user_1_avatar.png",
  "config": {
    "type": "CARTOON",
    "engine": "UNITY",
    "style": "MEDIUM_HAIR"
  },
  "version": 2
}

8. Preview Avatar

  • URL: POST /api/avatars/preview
  • Description: Generate avatar preview without saving
  • Authentication: None required
  • Request Body:
{
  "type": "CARTOON",
  "engine": "UNITY",
  "options": {
    "hair": "MEDIUM",
    "style": "CASUAL"
  }
}
  • Response (200 OK):
{
  "previewUrl": "/static/avatars/preview_temp_123.png",
  "expiresAt": "2025-01-01T11:00:00Z"
}

9. Update User Avatar

  • URL: POST /api/avatars/user/{userId}
  • Description: Update user's avatar configuration
  • Authentication: Required (own data or ADMIN)
  • Request Body:
{
  "type": "REALISTIC",
  "engine": "UNITY",
  "options": {
    "hair": "LONG",
    "style": "PROFESSIONAL"
  }
}

10. Upload Avatar Image

  • URL: POST /api/avatars/user/{userId}/upload
  • Description: Upload custom avatar image
  • Authentication: Required (own data or ADMIN)
  • Content-Type: multipart/form-data
  • Form Data:
    • file: Image file

Database Admin Endpoints

11. Get All Users (DB Admin)

  • URL: GET /admin/db/users
  • Description: Database administration view of users
  • Authentication: Required (ADMIN)
  • Query Parameters:
    • page: Page number
    • search: Search term
    • status: Filter by status
    • sort: Sort field
    • direction: Sort direction
  • Response: HTML page

12. Enable User

  • URL: POST /admin/db/users/{id}/enable
  • Description: Enable a disabled user
  • Authentication: Required (ADMIN)
  • Response: Redirect to users list

13. Disable User

  • URL: POST /admin/db/users/{id}/disable
  • Description: Disable an active user
  • Authentication: Required (ADMIN)
  • Response: Redirect to users list

gRPC Services

AuthService Definition

service AuthService {
  rpc Login (LoginRequest) returns (LoginResponse);
  rpc Register (RegisterRequest) returns (RegisterResponse);
  rpc ValidateToken (ValidateTokenRequest) returns (ValidateTokenResponse);
}

gRPC Message Types

LoginRequest

message LoginRequest {
  string email = 1;
  string password = 2;
}

LoginResponse

message LoginResponse {
  bool success = 1;
  string message = 2;
  string token = 3;
  User user = 4;
}

RegisterRequest

message RegisterRequest {
  string email = 1;
  string password = 2;
  repeated string roles = 3;
  string sensitive_data = 4;
}

ValidateTokenRequest

message ValidateTokenRequest {
  string token = 1;
}

Error Handling

Standardized Error Response Format

{
  "error": "Error Type",
  "message": "Human-readable error message",
  "status": 400,
  "timestamp": 1640995200000
}

Common HTTP Status Codes

  • 200 OK: Success
  • 201 Created: Resource created successfully
  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Authentication required or failed
  • 403 Forbidden: Insufficient permissions
  • 404 Not Found: Resource not found
  • 409 Conflict: Resource already exists
  • 422 Unprocessable Entity: Validation error
  • 500 Internal Server Error: Server error

Data Schemas

User Entity

{
  "id": "number",
  "email": "string",
  "password": "string (hashed)",
  "enabled": "boolean",
  "roles": ["string"],
  "createdAt": "ISO 8601 datetime",
  "updatedAt": "ISO 8601 datetime"
}

Avatar Configuration

{
  "type": "CARTOON | REALISTIC | ANIME | 3D",
  "engine": "UNITY | BLENDER | PHOTOREALISTIC",
  "options": {
    "hair": "SHORT | MEDIUM | LONG",
    "style": "CASUAL | BUSINESS | CREATIVE"
  }
}

Rate Limiting

Default Limits

  • Authentication endpoints: 10 requests/minute per IP
  • Avatar operations: 30 requests/minute per user
  • Administrative operations: 100 requests/minute per admin

CORS Configuration

Allowed Origins

  • Development: http://localhost:3000
  • Staging: https://staging.example.com
  • Production: https://example.com

Allowed Methods

  • GET, POST, PUT, DELETE, OPTIONS

Allowed Headers

  • Authorization, Content-Type, Accept

Security Considerations

Input Validation

  • Email format validation
  • Password strength requirements
  • File type validation for uploads
  • File size limits (2MB for avatars)

Data Sanitization

  • HTML escaping for display
  • SQL injection prevention
  • XSS protection

Secure Headers

Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Client Integration Examples

JavaScript/TypeScript

// Login example
const login = async (email: string, password: string) => {
  const response = await fetch('/admin/auth/api/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email, password }),
  });
  
  if (response.ok) {
    const data = await response.json();
    localStorage.setItem('authToken', data.token);
    return data;
  }
  throw new Error('Login failed');
};

// Authenticated request example
const getUser = async (userId: number) => {
  const token = localStorage.getItem('authToken');
  const response = await fetch(`/admin/auth/users/${userId}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  if (response.ok) {
    return response.json();
  }
  throw new Error('Failed to get user');
};

Python (requests)

import requests

# Login
def login(email, password):
    response = requests.post('/admin/auth/api/login', 
                           json={'email': email, 'password': password})
    if response.status_code == 200:
        return response.json()['token']
    raise Exception('Login failed')

# Authenticated request
def get_user(user_id, token):
    headers = {'Authorization': f'Bearer {token}'}
    response = requests.get(f'/admin/auth/users/{user_id}', headers=headers)
    if response.status_code == 200:
        return response.json()
    raise Exception('Failed to get user')

Testing

Postman Collection

Import the provided Postman collection to test all endpoints with pre-configured requests and environment variables.

Test Accounts

Performance Considerations

Caching Strategy

  • Static avatars: 7 days cache
  • User data: No cache (real-time updates)
  • JWT tokens: Client-side storage only

Pagination

  • Default page size: 10
  • Maximum page size: 100
  • Total count included in responses

Response Compression

  • Gzip compression enabled for JSON responses > 2KB
  • Image compression for avatars

Monitoring & Analytics

Key Metrics

  • Authentication success rate
  • Average response time
  • Avatar generation time
  • Error rate by endpoint

Health Checks

  • /actuator/health: Application health
  • Database connectivity
  • External service availability

Versioning Strategy

API Versioning

  • Current version: v1
  • Version header: Accept: application/vnd.api+json;version=1
  • Backward compatibility maintained for 1 major version

Support & Documentation

Additional Resources

  • OpenAPI/Swagger UI: /swagger-ui.html
  • API Documentation: /api-docs
  • Health Endpoint: /actuator/health

Contact Information

⚠️ **GitHub.com Fallback** ⚠️