Complete implementation examples for user authentication with the Lilith API.
Overview#
This guide demonstrates the complete authentication flow from user login to making authenticated API requests, including token refresh and error handling.
Authentication Flow Diagram#
sequenceDiagram
participant U as User
participant A as App
participant API as Lilith API
participant DB as Token Storage
U->>A: Enter credentials
A->>API: POST /v1/auth/login
API-->>A: JWT + Refresh tokens
A->>DB: Store tokens securely
A->>API: API request with JWT
alt Token valid
API-->>A: Success response
else Token expired
API-->>A: 401 Unauthorized
A->>API: POST /v1/auth/refresh
API-->>A: New JWT token
A->>DB: Update stored token
A->>API: Retry original request
API-->>A: Success response
end
Web Application (JavaScript)#
Complete Authentication Manager#
javascript
class LilithAuthManager {
constructor(options = {}) {
this.baseURL = options.baseURL || 'https://api.lilith.app';
this.tokenKey = 'lilith_access_token';
this.refreshTokenKey = 'lilith_refresh_token';
this.expiryKey = 'lilith_token_expiry';
this.storage = options.storage || localStorage;
this.onTokenExpired =
options.onTokenExpired || this.defaultTokenExpiredHandler;
this.onAuthError = options.onAuthError || console.error;
}
// Primary authentication method
async login(email, password) {
try {
const response = await fetch(`${this.baseURL}/v1/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
const error = await response.json();
throw new AuthenticationError(
error.message,
error.code,
response.status
);
}
const data = await response.json();
// Store authentication data securely
this.storeAuthData(data);
// Return user data
return {
user: data.user,
token: data.token,
expiresIn: data.expires_in,
};
} catch (error) {
this.onAuthError('Login failed', error);
throw error;
}
}
// Store authentication data
storeAuthData(authData) {
const expiryTime = Date.now() + authData.expires_in * 1000;
this.storage.setItem(this.tokenKey, authData.token);
this.storage.setItem(this.refreshTokenKey, authData.refresh_token);
this.storage.setItem(this.expiryKey, expiryTime.toString());
}
// Get current access token
getAccessToken() {
return this.storage.getItem(this.tokenKey);
}
// Check if token is expired
isTokenExpired() {
const expiry = this.storage.getItem(this.expiryKey);
if (!expiry) return true;
return Date.now() >= parseInt(expiry);
}
// Refresh access token
async refreshToken() {
const refreshToken = this.storage.getItem(this.refreshTokenKey);
if (!refreshToken) {
throw new AuthenticationError(
'No refresh token available',
'NO_REFRESH_TOKEN'
);
}
try {
const response = await fetch(`${this.baseURL}/v1/auth/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) {
const error = await response.json();
// If refresh fails, clear all auth data
if (response.status === 401) {
this.logout();
this.onTokenExpired();
}
throw new AuthenticationError(
error.message,
error.code,
response.status
);
}
const data = await response.json();
// Update stored tokens
const expiryTime = Date.now() + data.expires_in * 1000;
this.storage.setItem(this.tokenKey, data.token);
this.storage.setItem(this.expiryKey, expiryTime.toString());
return data.token;
} catch (error) {
this.onAuthError('Token refresh failed', error);
throw error;
}
}
// Get valid token (refreshes if needed)
async getValidToken() {
if (!this.isAuthenticated()) {
throw new AuthenticationError(
'User not authenticated',
'NOT_AUTHENTICATED'
);
}
if (this.isTokenExpired()) {
return await this.refreshToken();
}
return this.getAccessToken();
}
// Make authenticated API request
async makeAuthenticatedRequest(url, options = {}) {
let token;
try {
token = await this.getValidToken();
} catch (error) {
if (error.code === 'NOT_AUTHENTICATED') {
this.onTokenExpired();
}
throw error;
}
const headers = {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
...options.headers,
};
try {
const response = await fetch(url, {
...options,
headers,
});
// Handle token expiration during request
if (response.status === 401) {
try {
const newToken = await this.refreshToken();
// Retry request with new token
return fetch(url, {
...options,
headers: {
...headers,
Authorization: `Bearer ${newToken}`,
},
});
} catch (refreshError) {
// Refresh failed, redirect to login
this.onTokenExpired();
throw refreshError;
}
}
return response;
} catch (error) {
this.onAuthError('API request failed', error);
throw error;
}
}
// Check if user is authenticated
isAuthenticated() {
return !!(
this.getAccessToken() && this.storage.getItem(this.refreshTokenKey)
);
}
// Logout user
logout() {
this.storage.removeItem(this.tokenKey);
this.storage.removeItem(this.refreshTokenKey);
this.storage.removeItem(this.expiryKey);
}
// Default token expired handler
defaultTokenExpiredHandler() {
console.warn('Authentication expired, redirecting to login');
// In a real app, redirect to login page
window.location.href = '/login';
}
// Validate token with server
async validateToken() {
try {
const response = await this.makeAuthenticatedRequest(
`${this.baseURL}/v1/auth/validate`
);
if (response.ok) {
const data = await response.json();
return data.valid;
}
return false;
} catch (error) {
return false;
}
}
}
// Custom authentication error class
class AuthenticationError extends Error {
constructor(message, code, status = null) {
super(message);
this.name = 'AuthenticationError';
this.code = code;
this.status = status;
}
}
// Usage Example
const auth = new LilithAuthManager({
onTokenExpired: () => {
// Show login modal or redirect
showLoginModal();
},
onAuthError: (message, error) => {
console.error(`Auth Error: ${message}`, error);
showNotification(`Authentication error: ${message}`, 'error');
},
});
// Login function
async function handleLogin(email, password) {
try {
const result = await auth.login(email, password);
console.log('Login successful:', result.user);
showNotification('Welcome back!', 'success');
// Redirect to dashboard or close login modal
redirectToDashboard();
} catch (error) {
console.error('Login failed:', error);
if (error.status === 401) {
showNotification('Invalid email or password', 'error');
} else if (error.status === 429) {
showNotification(
'Too many login attempts. Please try again later.',
'error'
);
} else {
showNotification('Login failed. Please try again.', 'error');
}
}
}
// Make API calls
async function fetchUserProfile() {
try {
const response = await auth.makeAuthenticatedRequest(
'https://api.lilith.app/v1/users/profile'
);
if (response.ok) {
const profile = await response.json();
displayUserProfile(profile);
}
} catch (error) {
console.error('Failed to fetch profile:', error);
}
}
// Chat example
async function sendChatMessage(message, persona = 'zen_master') {
try {
const response = await auth.makeAuthenticatedRequest(
'https://api.lilith.app/v1/chat',
{
method: 'POST',
body: JSON.stringify({
persona: persona,
input: { text: message },
mode: 'text',
options: { stream: false, cite: true },
}),
}
);
if (response.ok) {
const chatResult = await response.json();
displayChatResponse(chatResult);
}
} catch (error) {
console.error('Chat request failed:', error);
}
}
React Hook Implementation#
jsx
import React, { createContext, useContext, useReducer, useEffect } from 'react';
// Authentication context
const AuthContext = createContext();
// Authentication reducer
function authReducer(state, action) {
switch (action.type) {
case 'LOGIN_START':
return { ...state, isLoading: true, error: null };
case 'LOGIN_SUCCESS':
return {
...state,
isLoading: false,
isAuthenticated: true,
user: action.payload.user,
token: action.payload.token,
error: null,
};
case 'LOGIN_ERROR':
return {
...state,
isLoading: false,
isAuthenticated: false,
user: null,
token: null,
error: action.payload,
};
case 'LOGOUT':
return {
...state,
isAuthenticated: false,
user: null,
token: null,
error: null,
};
case 'TOKEN_REFRESHED':
return {
...state,
token: action.payload.token,
};
default:
return state;
}
}
// Authentication provider component
export function AuthProvider({ children }) {
const [state, dispatch] = useReducer(authReducer, {
isAuthenticated: false,
isLoading: false,
user: null,
token: null,
error: null,
});
const authManager = new LilithAuthManager({
onTokenExpired: () => {
dispatch({ type: 'LOGOUT' });
},
onAuthError: (message, error) => {
dispatch({ type: 'LOGIN_ERROR', payload: error.message });
},
});
// Check existing authentication on mount
useEffect(() => {
const checkAuth = async () => {
if (authManager.isAuthenticated()) {
try {
const isValid = await authManager.validateToken();
if (isValid) {
// Token is valid, get user info
const response = await authManager.makeAuthenticatedRequest(
'https://api.lilith.app/v1/users/profile'
);
if (response.ok) {
const user = await response.json();
dispatch({
type: 'LOGIN_SUCCESS',
payload: {
user,
token: authManager.getAccessToken(),
},
});
}
}
} catch (error) {
// Invalid token, logout
authManager.logout();
dispatch({ type: 'LOGOUT' });
}
}
};
checkAuth();
}, []);
const login = async (email, password) => {
dispatch({ type: 'LOGIN_START' });
try {
const result = await authManager.login(email, password);
dispatch({
type: 'LOGIN_SUCCESS',
payload: result,
});
return result;
} catch (error) {
dispatch({ type: 'LOGIN_ERROR', payload: error.message });
throw error;
}
};
const logout = () => {
authManager.logout();
dispatch({ type: 'LOGOUT' });
};
const makeAuthenticatedRequest = async (url, options) => {
return authManager.makeAuthenticatedRequest(url, options);
};
return (
<AuthContext.Provider
value={{
...state,
login,
logout,
makeAuthenticatedRequest,
}}
>
{children}
</AuthContext.Provider>
);
}
// Authentication hook
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
// Login component example
export function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const { login, isLoading, error } = useAuth();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(email, password);
} catch (error) {
// Error handled by context
console.error('Login failed:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div>
<label>Password:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
{error && <div className="error">{error}</div>}
<button type="submit" disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login'}
</button>
</form>
);
}
// Protected route component
export function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAuthenticated) {
return <LoginForm />;
}
return children;
}
// Usage in app
function App() {
return (
<AuthProvider>
<div className="app">
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
</div>
</AuthProvider>
);
}
React Native Implementation#
For the React Native mobile app, authentication is handled using the same
patterns as above with secure storage via
@react-native-async-storage/async-storage for tokens and
react-native-keychain for sensitive credentials.