Code Examples
Complete working examples
/
Basic Authentication
A simple login/logout implementation:
HTML + JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Lemma Auth Example</title>
<script src="https://lemma.id/static/js/lemma-wallet.js"></script>
</head>
<body>
<div id="app">
<!-- Guest View -->
<div id="guest">
<h1>Welcome</h1>
<button id="login-btn">Sign in with Lemma</button>
</div>
<!-- Authenticated View -->
<div id="user" style="display: none;">
<h1>Hello, <span id="user-name"></span></h1>
<p>Your ID: <code id="user-id"></code></p>
<button id="logout-btn">Sign Out</button>
</div>
</div>
<script>
(async () => {
// Initialize
const wallet = new LemmaWallet({
siteId: 'your-site-id',
apiKey: 'your-api-key'
});
await wallet.init();
// Check for auth return
const result = await wallet.checkRedirectReturn();
if (result.authenticated) {
showUser(await wallet.derivePPID());
}
// Also check if already authenticated
if (await wallet.isUnlocked()) {
showUser(await wallet.derivePPID());
}
// Login button
document.getElementById('login-btn').onclick = () => {
wallet.startRedirectFlow({
returnUrl: window.location.href
});
};
// Logout button
document.getElementById('logout-btn').onclick = async () => {
await wallet.lock();
showGuest();
};
function showUser(ppid) {
document.getElementById('guest').style.display = 'none';
document.getElementById('user').style.display = 'block';
document.getElementById('user-id').textContent = ppid.slice(0, 16) + '...';
}
function showGuest() {
document.getElementById('guest').style.display = 'block';
document.getElementById('user').style.display = 'none';
}
})();
</script>
</body>
</html>
Protected Content
Show different content based on authentication:
JavaScript
async function loadProtectedContent() {
const wallet = new LemmaWallet({ siteId: 'your-site-id' });
await wallet.init();
if (!await wallet.isUnlocked()) {
document.getElementById('content').innerHTML = `
<p>Please sign in to view this content.</p>
<button onclick="signIn()">Sign In</button>
`;
return;
}
// User is authenticated - show content
const ppid = await wallet.derivePPID();
// Fetch user-specific data
const response = await fetch('/api/user/data', {
headers: {
'X-User-PPID': ppid
}
});
const data = await response.json();
document.getElementById('content').innerHTML = `
<h2>Your Dashboard</h2>
<pre>${JSON.stringify(data, null, 2)}</pre>
`;
}