🔐 Byve Registration API

v1.0

Central Registration & Authentication API for Byve Platform

📋 Overview

The Byve Registration API provides a centralized authentication system for all Byve platform applications. It supports user registration, password-based login, and OTP-based authentication via email.

🎯 Features

  • User Registration
  • Password Authentication
  • OTP Email Verification
  • JWT Token Generation
  • Secure Password Hashing

🔒 Security

  • BCrypt Password Hashing
  • JWT Bearer Tokens
  • API Key Authentication
  • OTP Expiration (5 mins)
  • HTTPS Only
  • Rate Limiting (1000/hour)

📧 Email Features

  • Beautiful HTML Templates
  • SMTP Integration
  • OTP Delivery
  • Security Warnings
  • Professional Design

🌐 API Endpoints

Base URL: https://registrationapi.byve.io/api/auth

POST /register

Description: Register a new user account with email, phone, and password

Auth Required: X-API-Key header (Production only)

Request Body:

{
  "firstName": "string" (required, max 100 chars),
  "lastName": "string" (required, max 100 chars),
  "email": "string" (required, valid email format),
  "phoneNumber": "string" (required, valid phone format),
  "password": "string" (required, min 8 chars),
  "confirmPassword": "string" (required, must match password)
}

Response: 200 OK with JWT token and user details, or 400 Bad Request

POST /login

Description: Login with email/phone and password

Auth Required: X-API-Key header (Production only)

Request Body:

{
  "identifier": "string" (required, email OR phone number),
  "password": "string" (required)
}

Response: 200 OK with JWT token and user details, or 401 Unauthorized

POST /otp/request

Description: Request OTP code via email for passwordless login

Auth Required: X-API-Key header (Production only)

Request Body:

{
  "identifier": "string" (required, email OR phone number)
}

Response: 200 OK with success message (OTP sent to email)

Note: OTP valid for 5 minutes, check email inbox

POST /otp/verify

Description: Verify OTP code and receive JWT token

Auth Required: X-API-Key header (Production only)

Request Body:

{
  "identifier": "string" (required, email OR phone number),
  "code": "string" (required, 6-digit OTP code)
}

Response: 200 OK with JWT token and user details, or 401 Unauthorized

💻 Complete Integration Guide

Follow these step-by-step examples to integrate the Byve Registration API into your application.

Step 1: Register a New User

JavaScript
// Registration function with validation
const registerUser = async (userData) => {
  try {
    const response = await fetch('https://registrationapi.byve.io/api/auth/register', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'X-API-Key': 'your-api-key-here' // Production only, remove in dev
      },
      body: JSON.stringify({
        firstName: userData.firstName,
        lastName: userData.lastName,
        email: userData.email,
        phoneNumber: userData.phoneNumber,
        password: userData.password,
        confirmPassword: userData.confirmPassword
      })
    });

    const data = await response.json();
    
    if (data.success) {
      // Store JWT token
      localStorage.setItem('authToken', data.token);
      console.log('Registration successful:', data.user);
      return { success: true, user: data.user };
    } else {
      console.error('Registration failed:', data.message);
      return { success: false, error: data.message };
    }
  } catch (error) {
    console.error('Network error:', error);
    return { success: false, error: 'Network error occurred' };
  }
};

// Example usage
registerUser({
  firstName: 'John',
  lastName: 'Doe',
  email: 'john@example.com',
  phoneNumber: '+1234567890',
  password: 'SecurePass123!',
  confirmPassword: 'SecurePass123!'
});

Step 2: Login with Password

JavaScript
// Password login function
const loginWithPassword = async (identifier, password) => {
  try {
    const response = await fetch('https://registrationapi.byve.io/api/auth/login', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'X-API-Key': 'your-api-key-here' // Production only
      },
      body: JSON.stringify({
        identifier: identifier, // Email or phone number
        password: password
      })
    });

    const data = await response.json();
    
    if (data.success) {
      // Store JWT token
      localStorage.setItem('authToken', data.token);
      console.log('Login successful:', data.user);
      return { success: true, user: data.user, token: data.token };
    } else {
      console.error('Login failed:', data.message);
      return { success: false, error: data.message };
    }
  } catch (error) {
    console.error('Network error:', error);
    return { success: false, error: 'Network error occurred' };
  }
};

// Example usage
await loginWithPassword('john@example.com', 'SecurePass123!');

Step 3: Request OTP (Passwordless Login)

JavaScript
// Request OTP code
const requestOTP = async (identifier) => {
  try {
    const response = await fetch('https://registrationapi.byve.io/api/auth/otp/request', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'X-API-Key': 'your-api-key-here' // Production only
      },
      body: JSON.stringify({
        identifier: identifier // Email or phone number
      })
    });

    const data = await response.json();
    
    if (data.success) {
      console.log('OTP sent successfully:', data.message);
      return { success: true, message: 'Check your email for OTP code' };
    } else {
      console.error('OTP request failed:', data.message);
      return { success: false, error: data.message };
    }
  } catch (error) {
    console.error('Network error:', error);
    return { success: false, error: 'Network error occurred' };
  }
};

// Example usage
await requestOTP('john@example.com');

Step 4: Verify OTP and Login

JavaScript
// Verify OTP code and login
const verifyOTP = async (identifier, otpCode) => {
  try {
    const response = await fetch('https://registrationapi.byve.io/api/auth/otp/verify', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'X-API-Key': 'your-api-key-here' // Production only
      },
      body: JSON.stringify({
        identifier: identifier,
        code: otpCode // 6-digit code from email
      })
    });

    const data = await response.json();
    
    if (data.success) {
      // Store JWT token
      localStorage.setItem('authToken', data.token);
      console.log('OTP verified, logged in:', data.user);
      return { success: true, user: data.user, token: data.token };
    } else {
      console.error('OTP verification failed:', data.message);
      return { success: false, error: data.message };
    }
  } catch (error) {
    console.error('Network error:', error);
    return { success: false, error: 'Network error occurred' };
  }
};

// Example usage
await verifyOTP('john@example.com', '123456');

Step 5: Using JWT Token for Protected Requests

JavaScript
// Make authenticated requests with JWT token
const makeAuthenticatedRequest = async (endpoint, method = 'GET', body = null) => {
  const token = localStorage.getItem('authToken');
  
  if (!token) {
    console.error('No auth token found');
    return { success: false, error: 'Not authenticated' };
  }

  try {
    const options = {
      method: method,
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    };

    if (body) {
      options.body = JSON.stringify(body);
    }

    const response = await fetch(endpoint, options);
    
    if (response.status === 401) {
      // Token expired or invalid
      localStorage.removeItem('authToken');
      console.error('Token expired, please login again');
      return { success: false, error: 'Token expired' };
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Request failed:', error);
    return { success: false, error: 'Request failed' };
  }
};

// Example: Get user profile (if you have such endpoint)
// await makeAuthenticatedRequest('https://registrationapi.byve.io/api/user/profile');
'Content-Type': 'application/json', 'X-API-Key': 'your-api-key-here' // Production only }, body: JSON.stringify({ identifier: 'john@example.com' }) }); const data = await response.json(); console.log(data.message); // Check email for OTP };

OTP Login (Verify)

JavaScript
const verifyOtp = async (otpCode) => {
  const response = await fetch('https://registrationapi.byve.io/api/auth/otp/verify', {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json',
      'X-API-Key': 'your-api-key-here' // Production only
    },
    body: JSON.stringify({
      identifier: 'john@example.com',
      code: otpCode
    })
  });
  
  const { token, user } = await response.json();
  localStorage.setItem('authToken', token);
  console.log('Logged in:', user);
};

Step 1: Setup HTTP Client with API Key

C#
using System.Net.Http.Json;

public class ByveAuthClient
{
    private readonly HttpClient _httpClient;
    private const string BaseUrl = "https://registrationapi.byve.io/api/auth";
    private string? _authToken;

    public ByveAuthClient(string apiKey)
    {
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
    }

    // Set JWT token after login/registration
    public void SetAuthToken(string token)
    {
        _authToken = token;
        _httpClient.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    }
}

Step 2: User Registration

C#
public async Task<AuthResponse> RegisterAsync(RegisterDto registerDto)
{
    try
    {
        var response = await _httpClient.PostAsJsonAsync(
            $"{BaseUrl}/register",
            registerDto
        );

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<AuthResponse>();
            if (result?.Success == true && result.Token != null)
            {
                SetAuthToken(result.Token);
            }
            return result;
        }

        var error = await response.Content.ReadFromJsonAsync<AuthResponse>();
        return error ?? new AuthResponse { Success = false, Message = "Registration failed" };
    }
    catch (Exception ex)
    {
        return new AuthResponse { Success = false, Message = ex.Message };
    }
}

// Usage
var client = new ByveAuthClient("your-api-key-here");
var result = await client.RegisterAsync(new RegisterDto
{
    FirstName = "John",
    LastName = "Doe",
    Email = "john@example.com",
    PhoneNumber = "+1234567890",
    Password = "SecurePass123!",
    ConfirmPassword = "SecurePass123!"
});

Step 3: Password Login

C#
public async Task<AuthResponse> LoginAsync(LoginDto loginDto)
{
    try
    {
        var response = await _httpClient.PostAsJsonAsync(
            $"{BaseUrl}/login",
            loginDto
        );

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<AuthResponse>();
            if (result?.Success == true && result.Token != null)
            {
                SetAuthToken(result.Token);
            }
            return result;
        }

        return new AuthResponse { Success = false, Message = "Login failed" };
    }
    catch (Exception ex)
    {
        return new AuthResponse { Success = false, Message = ex.Message };
    }
}

// Usage
var result = await client.LoginAsync(new LoginDto
{
    Identifier = "john@example.com",
    Password = "SecurePass123!"
});

Step 4: OTP Request and Verification

C#
public async Task<AuthResponse> RequestOtpAsync(string identifier)
{
    var response = await _httpClient.PostAsJsonAsync(
        $"{BaseUrl}/otp/request",
        new { Identifier = identifier }
    );

    return await response.Content.ReadFromJsonAsync<AuthResponse>() 
        ?? new AuthResponse { Success = false };
}

public async Task<AuthResponse> VerifyOtpAsync(string identifier, string code)
{
    var response = await _httpClient.PostAsJsonAsync(
        $"{BaseUrl}/otp/verify",
        new { Identifier = identifier, Code = code }
    );

    var result = await response.Content.ReadFromJsonAsync<AuthResponse>();
    if (result?.Success == true && result.Token != null)
    {
        SetAuthToken(result.Token);
    }
    return result ?? new AuthResponse { Success = false };
}

// Usage - OTP Flow
await client.RequestOtpAsync("john@example.com");
// User receives OTP in email
var otpResult = await client.VerifyOtpAsync("john@example.com", "123456");

DTO Models

C#
public class RegisterDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
}

public class LoginDto
{
    public string Identifier { get; set; } // Email or Phone
    public string Password { get; set; }
}

public class AuthResponse
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public string? Token { get; set; }
    public UserDto? User { get; set; }
}

public class UserDto
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsEmailVerified { get; set; }
    public bool IsPhoneVerified { get; set; }
}

User Registration (Production)

Python
import requests

url = "https://registrationapi.byve.io/api/auth/register"
headers = {
    "Content-Type": "application/json",
    "X-API-Key": "your-api-key-here"  # Production only
}
data = {
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "phoneNumber": "+1234567890",
    "password": "SecurePass123!"
}

response = requests.post(url, json=data, headers=headers)
result = response.json()
print(result)

Password Login

Python
url = "https://registrationapi.byve.io/api/auth/login"
headers = {"X-API-Key": "your-api-key-here"}  # Production only
data = {
    "identifier": "john@example.com",
    "password": "SecurePass123!"
}

response = requests.post(url, json=data, headers=headers)
result = response.json()
token = result["token"]
user = result["user"]

User Registration (Production)

bash
curl -X POST https://registrationapi.byve.io/api/auth/register \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "phoneNumber": "+1234567890",
    "password": "SecurePass123!"
  }'

Password Login

bash
curl -X POST https://registrationapi.byve.io/api/auth/login \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "identifier": "john@example.com",
    "password": "SecurePass123!"
  }'

OTP Request

bash
curl -X POST https://registrationapi.byve.io/api/auth/otp/request \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{"identifier": "john@example.com"}'

OTP Verify

bash
curl -X POST https://registrationapi.byve.io/api/auth/otp/verify \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here

                    

OTP Verify

bash
curl -X POST https://registrationapi.byve.io/api/auth/otp/verify \
  -H "Content-Type: application/json" \
  -d '{
    "identifier": "john@example.com",
    "code": "123456"
  }'

🔑 Authentication

🛡️ API Key (Production Only)

In production environment, all requests require an API Key header. Development mode bypasses this for easy testing.

HTTP Header
X-API-Key: your-api-key-here

📝 Development Mode

  • No API Key required
  • Test freely in Swagger
  • All endpoints accessible
  • Perfect for local testing

🔒 Production Mode

  • X-API-Key header required
  • Rate limiting active (1000/hour)
  • Per-application keys
  • Key expiration support

JWT Token Usage

After successful login, you'll receive a JWT token. Include it in subsequent API requests to protected endpoints:

HTTP Header
Authorization: Bearer YOUR_JWT_TOKEN_HERE

Token Properties

Token Structure

  • Type: Bearer
  • Algorithm: HS256
  • Expiration: 60 minutes
  • Claims: User ID, Email, Name, Phone

OTP Configuration

  • Length: 6 digits
  • Expiration: 5 minutes
  • Delivery: Email (SMTP)
  • Single Use: Yes

📦 API Response Format

Standard Success Response

JSON
{
  "success": true,
  "message": "Operation successful",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "phoneNumber": "+1234567890",
    "isEmailVerified": false,
    "isPhoneVerified": false
  }
}

Error Response

JSON
{
  "success": false,
  "message": "Validation error or operation failed",
  "token": null,
  "user": null
}

Validation Error Response

JSON
{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "email": ["Invalid email format"],
    "password": ["Password must be at least 8 characters"],
    "phoneNumber": ["Invalid phone number format"]
  },
  "traceId": "00-0580d90696aeae526998ef11be1ad6f8-90d9ce50dc76b762-00"
}

✅ Validation Rules

Registration Fields

  • firstName: Required, max 100 characters
  • lastName: Required, max 100 characters
  • email: Required, valid email format, unique
  • phoneNumber: Required, valid phone format, unique
  • password: Required, minimum 8 characters
  • confirmPassword: Required, must match password

Login Fields

  • identifier: Required (email OR phone number)
  • password: Required

OTP Fields

  • identifier: Required (email OR phone number)
  • code: Required, 6-digit numeric code
  • Expiration: OTP valid for 5 minutes
  • Single Use: Each OTP can only be used once

📊 HTTP Status Codes

400 Bad Request - Invalid input data
401 Unauthorized - Invalid credentials or token
500 Internal Server Error - Server error occurred

✨ Best Practices

Security

  • Always use HTTPS
  • Store tokens securely
  • Never expose tokens in URLs
  • Implement token refresh logic
  • Handle expired tokens gracefully

Error Handling

  • Check response status codes
  • Parse error messages
  • Implement retry logic
  • Log errors appropriately
  • Show user-friendly messages

Performance

  • Reuse HTTP clients
  • Implement connection pooling
  • Cache tokens until expiry
  • Use async/await patterns
  • Handle timeouts properly

📞 Support

For questions, issues, or feature requests: