mirror of
https://github.com/Alvin-Zilverstand/Challenge_15_Magazijn_App_Maken.git
synced 2026-03-06 11:06:34 +01:00
init
This commit is contained in:
36
public/js/auth.js
Normal file
36
public/js/auth.js
Normal file
@@ -0,0 +1,36 @@
|
||||
// Authentication related functions
|
||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const username = document.getElementById('username').value.toLowerCase(); // Convert to lowercase
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
localStorage.setItem('token', data.token);
|
||||
localStorage.setItem('userRole', data.role);
|
||||
localStorage.setItem('username', data.username.toLowerCase());
|
||||
|
||||
// Redirect based on role
|
||||
if (data.role === 'admin') {
|
||||
window.location.href = '/admin.html';
|
||||
} else {
|
||||
window.location.href = '/student.html';
|
||||
}
|
||||
} else {
|
||||
alert(data.message || 'Login failed');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
alert('An error occurred during login');
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user