Skip to main content

Authentication Module

The auth module handles user authentication, registration, and session management for BRDZ SDK.

Import

const auth = await brdzSDK.auth;

Methods Overview

MethodDescriptionAuth RequiredHTTP Endpoint
loginUserTraditional login with email/passwordPOST /auth/login
registerUserRegister new user accountPOST /clients/create_with_admin
completeLoginWith2FAComplete login with 2FA tokenPOST /auth/complete-login
initiateMobileLoginStart mobile push authenticationPOST /auth/mobile-login
checkMobileLoginStatusCheck mobile auth statusGET /auth/mobile-status/:sessionId
approveMobileLoginApprove mobile authenticationPOST /auth/mobile-approve
forgotPasswordRequest password resetPOST /password/request_reset
getUserProfileGet authenticated user profileGET /users/:user_id

loginUser

Traditional login with email/username and password.

Syntax

const result = await auth.loginUser(usernameOrEmail, password);

Parameters

ParameterTypeRequiredDescription
usernameOrEmailstringUser's email address or username
passwordstringUser's password

Returns

Promise<{
success: boolean;
token?: string; // JWT token if login successful
user_id?: number; // User ID
requires_2fa?: boolean; // True if 2FA is enabled
message: string;
}>

Example

try {
const result = await auth.loginUser('john@example.com', 'password123');

if (result.requires_2fa) {
// Handle 2FA flow
console.log('2FA required for user:', result.user_id);
// Proceed to completeLoginWith2FA()
} else {
// Login successful - store token
localStorage.setItem('auth_token', result.token);

// Update SDK configuration
const config = await brdzSDK.config;
config.setToken(result.token);
}
} catch (error) {
console.error('Login failed:', error.message);
}

HTTP Endpoint

  • Method: POST
  • URL: https://api.brdz.link/api/auth/login
  • Headers: x-api-key required

registerUser

Register a new user account.

Syntax

const result = await auth.registerUser(userData);

Parameters

interface RegisterData {
email: string; // User's email address
username: string; // Unique username
client_alias?: string; // Optional client alias
client_type?: string; // Optional client type
country_code?: string; // Optional country code
phone?: string; // Optional phone number
}

Returns

Promise<{
success: boolean;
user_id: number;
client_id: number;
message: string;
}>

Example

try {
const newUser = await auth.registerUser({
email: 'newuser@example.com',
username: 'newuser',
country_code: 'ID',
phone: '+628123456789'
});

console.log('User registered successfully:', newUser.user_id);
console.log('Client ID:', newUser.client_id);
} catch (error) {
console.error('Registration failed:', error.message);
}

HTTP Endpoint

  • Method: POST
  • URL: https://api.brdz.link/api/clients/create_with_admin
  • Headers: x-api-key required

completeLoginWith2FA

Complete the login process after initial authentication when 2FA is enabled.

Syntax

const result = await auth.completeLoginWith2FA(userId, twoFAToken);

Parameters

ParameterTypeRequiredDescription
userIdnumberUser ID from initial login response
twoFATokenstring6-digit token from authenticator app

Returns

Promise<{
success: boolean;
token: string; // JWT token for authenticated sessions
user_id: number;
message: string;
}>

Example

// After initial login requires 2FA
const loginResult = await auth.loginUser('user@example.com', 'password');

if (loginResult.requires_2fa) {
// User enters 2FA token from authenticator app
const twoFAToken = '123456'; // 6-digit code

try {
const completeResult = await auth.completeLoginWith2FA(
loginResult.user_id,
twoFAToken
);

// Store the final JWT token
localStorage.setItem('auth_token', completeResult.token);

// Update SDK configuration
const config = await brdzSDK.config;
config.setToken(completeResult.token);

console.log('2FA login completed successfully');
} catch (error) {
console.error('2FA verification failed:', error.message);
}
}

HTTP Endpoint

  • Method: POST
  • URL: https://api.brdz.link/api/auth/complete-login
  • Headers: x-api-key required

initiateMobileLogin

Start mobile push authentication flow for passwordless login.

Syntax

const result = await auth.initiateMobileLogin(emailOrUsername);

Parameters

ParameterTypeRequiredDescription
emailOrUsernamestringUser's email or username

Returns

Promise<{
success: boolean;
sessionId: string; // Session ID for tracking auth status
message: string;
expires_at: string; // Session expiration timestamp
}>

Example

try {
const mobileAuth = await auth.initiateMobileLogin('user@example.com');

console.log('Push notification sent');
console.log('Session ID:', mobileAuth.sessionId);

// Start polling for approval status
const sessionId = mobileAuth.sessionId;
// Use checkMobileLoginStatus() to poll for approval
} catch (error) {
console.error('Mobile auth initiation failed:', error.message);
}

HTTP Endpoint

  • Method: POST
  • URL: https://api.brdz.link/api/auth/mobile-login
  • Headers: x-api-key required

checkMobileLoginStatus

Check the status of a mobile authentication session.

Syntax

const result = await auth.checkMobileLoginStatus(sessionId);

Parameters

ParameterTypeRequiredDescription
sessionIdstringSession ID from initiateMobileLogin

Returns

Promise<{
success: boolean;
data: {
status: 'pending' | 'approved' | 'denied' | 'expired';
token?: string; // JWT token if approved
user_id?: number; // User ID if approved
};
message: string;
}>

Example

// Poll for mobile authentication approval
const pollMobileAuth = async (sessionId) => {
const maxAttempts = 30; // 5 minutes max
let attempts = 0;

const poll = async () => {
try {
const status = await auth.checkMobileLoginStatus(sessionId);

if (status.data.status === 'approved') {
// Authentication successful
localStorage.setItem('auth_token', status.data.token);

const config = await brdzSDK.config;
config.setToken(status.data.token);

console.log('Mobile authentication approved!');
return true;
} else if (status.data.status === 'denied') {
console.log('Mobile authentication denied');
return false;
} else if (status.data.status === 'expired') {
console.log('Mobile authentication session expired');
return false;
}

// Still pending, continue polling
attempts++;
if (attempts < maxAttempts) {
setTimeout(poll, 10000); // Poll every 10 seconds
} else {
console.log('Mobile authentication timeout');
return false;
}
} catch (error) {
console.error('Error checking mobile auth status:', error.message);
return false;
}
};

poll();
};

// Usage
const mobileAuth = await auth.initiateMobileLogin('user@example.com');
pollMobileAuth(mobileAuth.sessionId);

HTTP Endpoint

  • Method: GET
  • URL: https://api.brdz.link/api/auth/mobile-status/:sessionId
  • Headers: x-api-key required

approveMobileLogin

Approve mobile authentication (typically called by mobile app).

Syntax

const result = await auth.approveMobileLogin(sessionId, deviceId);

Parameters

ParameterTypeRequiredDescription
sessionIdstringSession ID from mobile auth initiation
deviceIdstringUnique device identifier

Returns

Promise<{
success: boolean;
token: string; // JWT token for authenticated session
user_id: number;
message: string;
}>

Example

// Typically called by mobile application
try {
const approval = await auth.approveMobileLogin(sessionId, deviceId);

console.log('Mobile login approved');
console.log('Token:', approval.token);
} catch (error) {
console.error('Mobile approval failed:', error.message);
}

HTTP Endpoint

  • Method: POST
  • URL: https://api.brdz.link/api/auth/mobile-approve
  • Headers: x-api-key required

forgotPassword

Request password reset for user account.

Syntax

const result = await auth.forgotPassword(email);

Parameters

ParameterTypeRequiredDescription
emailstringUser's email address

Returns

Promise<{
success: boolean;
message: string;
}>

Example

try {
const result = await auth.forgotPassword('user@example.com');

console.log('Password reset email sent');
console.log('Message:', result.message);
} catch (error) {
console.error('Password reset request failed:', error.message);
}

HTTP Endpoint

  • Method: POST
  • URL: https://api.brdz.link/api/password/request_reset
  • Headers: x-api-key required

getUserProfile

Get authenticated user's profile information.

Syntax

const result = await auth.getUserProfile(userId);

Parameters

ParameterTypeRequiredDescription
userIdstringUser ID of the authenticated user

Returns

Promise<{
success: boolean;
data: {
user_id: number;
username: string;
email: string;
phone?: string;
country_code?: string;
// Additional profile fields
};
message: string;
}>

Example

try {
const userId = localStorage.getItem('user_id');
const profile = await auth.getUserProfile(userId);

console.log('User profile:', profile.data);
console.log('Username:', profile.data.username);
console.log('Email:', profile.data.email);
} catch (error) {
console.error('Failed to get user profile:', error.message);
}

HTTP Endpoint

  • Method: GET
  • URL: https://api.brdz.link/api/users/:user_id
  • Headers: Authorization: Bearer <JWT_TOKEN>, x-api-key required

Authentication Flow Examples

Complete Login Flow

class AuthService {
constructor() {
this.sdk = null;
this.initSDK();
}

async initSDK() {
this.sdk = brdzSDK;
const config = await this.sdk.config;
config.setBaseUrl('https://api.brdz.link/api');
config.setApiKey(process.env.BRDZ_API_KEY);
}

async login(email, password) {
const auth = await this.sdk.auth;

try {
const result = await auth.loginUser(email, password);

if (result.requires_2fa) {
return {
requires2FA: true,
userId: result.user_id,
message: 'Please enter your 2FA code'
};
}

// Complete login
localStorage.setItem('auth_token', result.token);
localStorage.setItem('user_id', result.user_id);

const config = await this.sdk.config;
config.setToken(result.token);

return {
success: true,
token: result.token,
userId: result.user_id
};
} catch (error) {
throw new Error(`Login failed: ${error.message}`);
}
}

async complete2FA(userId, twoFACode) {
const auth = await this.sdk.auth;

try {
const result = await auth.completeLoginWith2FA(userId, twoFACode);

localStorage.setItem('auth_token', result.token);
localStorage.setItem('user_id', result.user_id);

const config = await this.sdk.config;
config.setToken(result.token);

return {
success: true,
token: result.token
};
} catch (error) {
throw new Error(`2FA verification failed: ${error.message}`);
}
}

async logout() {
localStorage.removeItem('auth_token');
localStorage.removeItem('user_id');

const config = await this.sdk.config;
config.setToken('');
}
}

// Usage
const authService = new AuthService();

// Traditional login
const loginResult = await authService.login('user@example.com', 'password');

if (loginResult.requires2FA) {
// Show 2FA input form
const twoFACode = '123456'; // From user input
await authService.complete2FA(loginResult.userId, twoFACode);
}

Mobile Authentication Flow

class MobileAuthService {
async initiateMobileAuth(email) {
const auth = await brdzSDK.auth;

try {
const result = await auth.initiateMobileLogin(email);

// Start polling for approval
this.pollForApproval(result.sessionId);

return {
sessionId: result.sessionId,
message: 'Push notification sent to your mobile device'
};
} catch (error) {
throw new Error(`Mobile auth failed: ${error.message}`);
}
}

async pollForApproval(sessionId) {
const auth = await brdzSDK.auth;
const maxAttempts = 30;
let attempts = 0;

const poll = async () => {
try {
const status = await auth.checkMobileLoginStatus(sessionId);

switch (status.data.status) {
case 'approved':
localStorage.setItem('auth_token', status.data.token);
const config = await brdzSDK.config;
config.setToken(status.data.token);

// Redirect to dashboard or emit event
window.location.href = '/dashboard';
return;

case 'denied':
alert('Mobile authentication was denied');
return;

case 'expired':
alert('Mobile authentication session expired');
return;

default: // pending
attempts++;
if (attempts < maxAttempts) {
setTimeout(poll, 10000);
} else {
alert('Mobile authentication timeout');
}
}
} catch (error) {
console.error('Polling error:', error.message);
}
};

poll();
}
}

Error Handling

Common error scenarios and solutions:

ErrorDescriptionSolution
401: Invalid credentialsWrong email/passwordCheck credentials
429: Too many attemptsRate limitingWait before retry
400: API key missingNo API key configuredCall config.setApiKey()
400: Invalid 2FA tokenWrong authenticator codeCheck 6-digit code
404: User not foundUser doesn't existRegister new user
403: Account lockedToo many failed attemptsContact support

Always wrap authentication calls in try-catch blocks for proper error handling.