Documentation
Guides
Authentication

Authentication Guide

Complete guide to implementing authentication in your app.

Overview

Moontraze authentication supports:

  • Email/password registration
  • Login with optional TOTP 2FA
  • MON Authenticator enrollment
  • Password reset via TOTP
  • Change password while logged in
  • Logout

Signup Flow

Step 1: Register User

const result = await moon.auth.register('user@example.com', 'secret123', 'John');
moon.setToken(result.token);

Step 2: Enroll TOTP (Optional)

const enroll = await moon.auth.enrollTotp();
// enroll.qrPayload — otpauth:// URL
// Show this as QR code to user

Step 3: Confirm TOTP

const code = await promptUser('Enter 6-digit code from app');
await moon.auth.confirmTotp(code);

Login Flow

Step 1: Login

const result = await moon.auth.login('user@example.com', 'secret123');

Step 2: Check if TOTP required

if (result.requiresTotp) {
  const code = await promptUser('Enter code');
  const verified = await moon.auth.verifyTotp(result.loginTicket, code);
  moon.setToken(verified.token);
} else {
  moon.setToken(result.token);
}

Logout

moon.auth.logout();

Change Password (Logged In)

await moon.auth.changePassword('currentSecret', 'newSecret123');

Forgot Password Flow

Step 1: Verify TOTP

const verify = await moon.auth.forgotPasswordVerify('user@example.com', '123456');
// verify.verifyToken — short-lived

Step 2: Reset Password

await moon.auth.forgotPasswordReset(
  'user@example.com',
  verify.verifyToken,
  'newSecret123',
);

Best Practices

  • Never store TOTP secret on client
  • Show QR code as image (not text)
  • Handle errors gracefully
  • Always use HTTPS
  • Store tokens securely (not in localStorage for sensitive apps)