Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make the user login for an offline web app?
Offline web apps require a different authentication approach since they can't always connect to servers. The key is implementing local authentication with data synchronization when online.
How Offline Login Works
When online, authenticate against the server and store user credentials locally. When offline, authenticate against the local storage instead of the remote server.
Implementation Steps
Step 1: Online Authentication and Storage
When online, authenticate with the server and store credentials locally using localStorage or IndexedDB.
async function loginOnline(username, password) {
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, password})
});
if (response.ok) {
const userData = await response.json();
// Store user data locally
localStorage.setItem('userCredentials', JSON.stringify({
username: username,
hashedPassword: await hashPassword(password),
lastLogin: Date.now(),
token: userData.token
}));
console.log('Login successful - data stored locally');
return true;
}
} catch (error) {
console.log('Online login failed, checking offline credentials');
return loginOffline(username, password);
}
}
async function hashPassword(password) {
const encoder = new TextEncoder();
const data = encoder.encode(password);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
Step 2: Offline Authentication
When offline, compare entered credentials against locally stored data.
async function loginOffline(username, password) {
const storedCredentials = localStorage.getItem('userCredentials');
if (!storedCredentials) {
alert('No offline credentials found. Please login online first.');
return false;
}
const credentials = JSON.parse(storedCredentials);
const hashedInputPassword = await hashPassword(password);
if (credentials.username === username &&
credentials.hashedPassword === hashedInputPassword) {
console.log('Offline login successful');
return true;
} else {
console.log('Invalid offline credentials');
return false;
}
}
Step 3: Complete Login Function
Combine online and offline authentication with network detection.
async function handleLogin() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (!username || !password) {
alert('Please enter both username and password');
return;
}
// Check if online
if (navigator.onLine) {
const success = await loginOnline(username, password);
if (success) {
redirectToApp();
} else {
alert('Login failed');
}
} else {
const success = await loginOffline(username, password);
if (success) {
redirectToApp();
} else {
alert('Offline login failed');
}
}
}
function redirectToApp() {
window.location.href = '/dashboard.html';
}
// Example usage
document.addEventListener('DOMContentLoaded', function() {
const loginBtn = document.getElementById('loginBtn');
if (loginBtn) {
loginBtn.addEventListener('click', handleLogin);
}
});
Key Requirements
- Initial Online Login: Users must log in online at least once to store credentials locally
- Secure Storage: Hash passwords before storing them locally
- Sync When Online: Update local credentials when password changes online
- Network Detection: Use navigator.onLine to determine connection status
Security Considerations
Store hashed passwords, not plain text. Use proper encryption for sensitive data and implement token expiration for enhanced security.
Conclusion
Offline web app authentication requires storing user credentials locally after initial online verification. This enables users to access the app even without internet connectivity while maintaining reasonable security.
