Documentation Index
Fetch the complete documentation index at: https://mintlify.com/InsForge/InsForge/llms.txt
Use this file to discover all available pages before exploring further.
Overview
InsForge provides a complete authentication system with JWT tokens, user management, and support for multiple OAuth providers.
Key Features
- Email/Password Auth - Traditional authentication with email verification
- OAuth Providers - Google, GitHub, Discord, LinkedIn, and more
- JWT Tokens - Secure, stateless authentication
- Refresh Tokens - Long-lived sessions with token rotation
- PKCE Flow - Secure OAuth for mobile and desktop apps
- Row Level Security - Database-level access control
- Profile Management - Separate user profiles with custom fields
Authentication Flow
Email/Password Authentication
Registration
import { createClient } from '@insforge/sdk';
const client = createClient({
baseUrl: 'https://your-app.region.insforge.app',
anonKey: 'your-anon-key'
});
const { data, error } = await client.auth.signUp({
email: 'user@example.com',
password: 'securepassword123',
name: 'John Doe'
});
if (error) {
console.error('Registration failed:', error);
} else {
console.log('User:', data.user);
console.log('Access Token:', data.accessToken);
}
If email verification is enabled, accessToken will be null until the user verifies their email.
Login
const { data, error } = await client.auth.signIn({
email: 'user@example.com',
password: 'securepassword123'
});
if (error) {
console.error('Login failed:', error);
} else {
// Access token is automatically stored
console.log('Logged in:', data.user);
}
Response:
{
"user": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"profile": {
"name": "John Doe",
"avatar_url": null
},
"emailVerified": true,
"providers": ["email"],
"createdAt": "2024-01-15T10:30:00Z"
},
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"csrfToken": "abc123..." // Web clients only
}
Get Current User
const { data: user, error } = await client.auth.getUser();
if (error) {
console.log('Not authenticated');
} else {
console.log('Current user:', user);
}
Logout
const { error } = await client.auth.signOut();
if (!error) {
console.log('Logged out successfully');
}
Token Management
Client Types
InsForge supports different client types with different token storage strategies:
| Client Type | Refresh Token Storage | CSRF Protection |
|---|
| Web | httpOnly cookie | Required |
| Mobile | Response body | Not needed |
| Desktop | Response body | Not needed |
Web Clients (Browser)
Register/Login
Refresh token is stored in httpOnly cookie automatically:const { data } = await client.auth.signIn({
email: 'user@example.com',
password: 'password'
});
// csrfToken returned in response
Refresh Token
Use CSRF token for refresh:const { data } = await client.auth.refreshSession();
// New accessToken and csrfToken
Mobile/Desktop Clients
Specify client_type=mobile or client_type=desktop:
const response = await fetch('/api/auth/users?client_type=mobile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com',
password: 'password'
})
});
const { accessToken, refreshToken } = await response.json();
// Store refreshToken securely (e.g., Keychain, EncryptedSharedPreferences)
Automatic Token Refresh
The SDK handles token refresh automatically:
const client = createClient({
baseUrl: 'https://your-app.region.insforge.app',
anonKey: 'your-anon-key',
autoRefresh: true // Default
});
// SDK automatically refreshes when token expires
const { data } = await client.database.from('posts').select();
OAuth Authentication
Supported providers:
- Google
- GitHub
- Discord
- LinkedIn
- Facebook
- Instagram
- TikTok
- Apple
- X (Twitter)
- Spotify
- Microsoft
Web Flow (Browser)
Initiate OAuth
Redirect user to provider:const { data } = await client.auth.signInWithOAuth({
provider: 'google',
redirectTo: 'https://yourapp.com/auth/callback'
});
window.location.href = data.authUrl;
Handle Callback
Extract tokens from callback URL:// On your callback page
const params = new URLSearchParams(window.location.search);
const accessToken = params.get('access_token');
const userId = params.get('user_id');
const csrfToken = params.get('csrf_token');
if (accessToken) {
// Store token and redirect to app
client.auth.setSession({ accessToken, csrfToken });
window.location.href = '/dashboard';
}
PKCE Flow (Mobile/Desktop)
Generate Code Verifier
import { randomBytes, createHash } from 'crypto';
// Generate random code_verifier (43-128 chars)
const codeVerifier = randomBytes(32).toString('base64url');
// Generate code_challenge
const codeChallenge = createHash('sha256')
.update(codeVerifier)
.digest('base64url');
Initiate OAuth with PKCE
const response = await fetch(
`/api/auth/oauth/google?redirect_uri=${redirectUri}&code_challenge=${codeChallenge}`
);
const { authUrl } = await response.json();
// Open authUrl in browser or webview
Handle Callback
// Extract insforge_code from callback URL
const code = new URLSearchParams(callbackUrl).get('insforge_code');
Exchange Code for Tokens
const response = await fetch('/api/auth/oauth/exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: code,
code_verifier: codeVerifier
})
});
const { accessToken, refreshToken, user } = await response.json();
// Store tokens securely
Shared OAuth Keys
InsForge Cloud provides shared OAuth keys for quick setup:
// Automatically uses shared keys if configured
const { data } = await client.auth.signInWithOAuth({
provider: 'google',
useSharedKey: true
});
Email Verification
Configuration
Two verification methods:
- Code - 6-digit OTP sent via email
- Link - Magic link with token
Code Verification
Request Code
const { error } = await client.auth.sendVerificationCode({
email: 'user@example.com'
});
Verify Code
const { data, error } = await client.auth.verifyEmail({
email: 'user@example.com',
otp: '123456'
});
if (!error) {
console.log('Email verified:', data.user);
console.log('Access token:', data.accessToken);
}
Link Verification
Send Link
const { error } = await client.auth.sendVerificationLink({
email: 'user@example.com'
});
User Clicks Link
The backend endpoint handles verification:GET /api/auth/email/verify?otp={64-char-token}
Redirects to verifyEmailRedirectTo URL if configured.
Password Reset
Code Method (Two-Step)
Request Reset Code
const { error } = await client.auth.sendPasswordResetCode({
email: 'user@example.com'
});
Exchange Code for Token
const { data, error } = await client.auth.exchangeResetCode({
email: 'user@example.com',
code: '123456'
});
const resetToken = data.token;
Reset Password
const { error } = await client.auth.resetPassword({
otp: resetToken,
newPassword: 'newSecurePassword123'
});
Link Method (Direct)
Request Reset Link
const { error } = await client.auth.sendPasswordResetLink({
email: 'user@example.com'
});
User Clicks Link
Link contains token:https://yourapp.com/reset-password?token={64-char-token}
Reset Password
const { error } = await client.auth.resetPassword({
otp: tokenFromUrl,
newPassword: 'newSecurePassword123'
});
Profile Management
Update Current User’s Profile
const { data, error } = await client.auth.updateProfile({
name: 'Jane Doe',
avatar_url: 'https://example.com/avatar.jpg',
// Custom fields
bio: 'Software developer',
location: 'San Francisco'
});
Get User Profile by ID
const { data, error } = await client.auth.getProfile(userId);
if (!error) {
console.log('Profile:', data.profile);
}
Password Requirements
Configure password rules via admin API:
{
"passwordMinLength": 8,
"requireNumber": true,
"requireLowercase": true,
"requireUppercase": true,
"requireSpecialChar": false
}
Get public config:
const { data } = await client.auth.getPublicConfig();
console.log('Password requirements:', data);
JWT Token Structure
{
"sub": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"role": "authenticated",
"iat": 1705320600,
"exp": 1705324200
}
sub - User ID
role - authenticated or project_admin
exp - Token expires after 1 hour
API Reference
Endpoints
POST /api/auth/users # Register
POST /api/auth/sessions # Login
POST /api/auth/refresh # Refresh token
POST /api/auth/logout # Logout
GET /api/auth/sessions/current # Get current user
PATCH /api/auth/profiles/current # Update profile
GET /api/auth/profiles/{userId} # Get profile
GET /api/auth/public-config # Get auth config
# Email verification
POST /api/auth/email/send-verification
POST /api/auth/email/verify
# Password reset
POST /api/auth/email/send-reset-password
POST /api/auth/email/exchange-reset-password-token
POST /api/auth/email/reset-password
# OAuth
GET /api/auth/oauth/{provider}
POST /api/auth/oauth/exchange
GET /api/auth/oauth/{provider}/callback
POST /api/auth/oauth/{provider}/callback
Best Practices
Use Refresh Tokens
Implement token refresh to maintain long-lived sessions
Secure Token Storage
- Web: Let SDK handle httpOnly cookies
- Mobile: Use Keychain (iOS) or EncryptedSharedPreferences (Android)
Enable Email Verification
Reduce fake accounts and improve security
Use PKCE for Native Apps
Prevents authorization code interception attacks
Implement RLS Policies
Protect user data at the database level
Next Steps
Database
Protect data with Row Level Security
Storage
Upload user files securely
Real-time
Build live collaborative features
Functions
Add custom authentication logic