Code Examples

1. Python

User Registration

import requests
import json

# Base URL
BASE_URL = "http://auth.fabric.dev:8000/api/v1/auth"

# 1. Register a new user
def register_user(email, password):
    url = f"{BASE_URL}/signup/"
    data = {
        "identifier": email,
        "password": password,
        "method": "email",
        "verification_type": "otp"
    }
    
    response = requests.post(url, json=data)
    if response.status_code == 200:
        print("Registration successful! Check email for OTP.")
        return True
    else:
        print(f"Registration failed: {response.json()}")
        return False

# 2. Confirm registration with OTP
def confirm_registration(email, otp_code):
    url = f"{BASE_URL}/signup/confirm/"
    data = {
        "identifier": email,
        "code": otp_code
    }
    
    response = requests.post(url, json=data)
    if response.status_code == 200:
        print("Email verified successfully!")
        return True
    else:
        print(f"Verification failed: {response.json()}")
        return False

# 3. Login user
def login_user(email, password):
    url = f"{BASE_URL}/login/basic/"
    data = {
        "identifier": email,
        "password": password
    }
    
    response = requests.post(url, json=data)
    if response.status_code == 200:
        tokens = response.json()
        print("Login successful!")
        return tokens
    else:
        print(f"Login failed: {response.json()}")
        return None

# 4. Get user profile
def get_user_profile(access_token):
    url = "http://auth.fabric.dev:8000/api/v1/me"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        user_data = response.json()
        print(f"User profile: {user_data}")
        return user_data
    else:
        print(f"Failed to get profile: {response.json()}")
        return None

# 5. Refresh token
def refresh_access_token(refresh_token):
    url = f"{BASE_URL}/token/refresh/"
    data = {
        "refresh": refresh_token
    }
    
    response = requests.post(url, json=data)
    if response.status_code == 200:
        tokens = response.json()
        print("Token refreshed successfully!")
        return tokens
    else:
        print(f"Token refresh failed: {response.json()}")
        return None

# Usage example
if __name__ == "__main__":
    email = "[email protected]"
    password = "MySecretPassword123"
    
    # Register user
    if register_user(email, password):
        # In real application, user would enter OTP from email
        otp_code = input("Enter OTP from email: ")
        
        if confirm_registration(email, otp_code):
            # Login user
            tokens = login_user(email, password)
            if tokens:
                access_token = tokens["access"]
                refresh_token = tokens["refresh"]
                
                # Get user profile
                profile = get_user_profile(access_token)
                
                # Refresh token when needed
                new_tokens = refresh_access_token(refresh_token)

2. Javascript

Passwordless Login

// Base URL
const BASE_URL = "http://auth.fabric.dev:8000/api/v1/auth";

// 1. Request passwordless login
async function requestPasswordlessLogin(email) {
    const url = `${BASE_URL}/login/passwordless/`;
    const data = {
        identifier: email,
        method: "email",
        verification_type: "otp"
    };
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            console.log("OTP sent to email!");
            return true;
        } else {
            console.error("Failed to send OTP:", result);
            return false;
        }
    } catch (error) {
        console.error("Network error:", error);
        return false;
    }
}

// 2. Confirm passwordless login
async function confirmPasswordlessLogin(email, otpCode) {
    const url = `${BASE_URL}/login/passwordless/confirm/`;
    const data = {
        identifier: email,
        code: otpCode
    };
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            console.log("Login successful!");
            // Store tokens securely
            localStorage.setItem('access_token', result.access);
            localStorage.setItem('refresh_token', result.refresh);
            return result;
        } else {
            console.error("Login failed:", result);
            return null;
        }
    } catch (error) {
        console.error("Network error:", error);
        return null;
    }
}

// 3. Get user profile
async function getUserProfile() {
    const accessToken = localStorage.getItem('access_token');
    const url = "http://auth.fabric.dev:8000/api/v1/me";
    
    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });
        
        const result = await response.json();
        
        if (response.ok) {
            console.log("User profile:", result);
            return result;
        } else {
            console.error("Failed to get profile:", result);
            return null;
        }
    } catch (error) {
        console.error("Network error:", error);
        return null;
    }
}

// 4. Refresh token
async function refreshToken() {
    const refreshToken = localStorage.getItem('refresh_token');
    const url = `${BASE_URL}/token/refresh/`;
    const data = {
        refresh: refreshToken
    };
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            console.log("Token refreshed!");
            localStorage.setItem('access_token', result.access);
            localStorage.setItem('refresh_token', result.refresh);
            return result;
        } else {
            console.error("Token refresh failed:", result);
            return null;
        }
    } catch (error) {
        console.error("Network error:", error);
        return null;
    }
}

// 5. Password reset
async function requestPasswordReset(email) {
    const url = `${BASE_URL}/password/reset/`;
    const data = {
        identifier: email,
        method: "email",
        verification_type: "otp"
    };
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            console.log("Password reset OTP sent!");
            return true;
        } else {
            console.error("Password reset request failed:", result);
            return false;
        }
    } catch (error) {
        console.error("Network error:", error);
        return false;
    }
}

// 6. Confirm password reset
async function confirmPasswordReset(email, otpCode, newPassword) {
    const url = `${BASE_URL}/password/reset/confirm/`;
    const data = {
        identifier: email,
        code: otpCode,
        new_password: newPassword,
        confirm_password: newPassword
    };
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            console.log("Password reset successful!");
            return true;
        } else {
            console.error("Password reset failed:", result);
            return false;
        }
    } catch (error) {
        console.error("Network error:", error);
        return false;
    }
}

// Usage example
async function main() {
    const email = "[email protected]";
    
    // Request passwordless login
    if (await requestPasswordlessLogin(email)) {
        // In real application, user would enter OTP from email
        const otpCode = prompt("Enter OTP from email:");
        
        if (otpCode) {
            const tokens = await confirmPasswordlessLogin(email, otpCode);
            if (tokens) {
                // Get user profile
                const profile = await getUserProfile();
                
                // Example: Request password reset
                if (await requestPasswordReset(email)) {
                    const resetOtp = prompt("Enter password reset OTP:");
                    const newPassword = prompt("Enter new password:");
                    
                    if (resetOtp && newPassword) {
                        await confirmPasswordReset(email, resetOtp, newPassword);
                    }
                }
            }
        }
    }
}

// Run the example
// main();

Last updated

Was this helpful?