Move to git.themmonk.com
This commit is contained in:
69
web/js/auth.js
Normal file
69
web/js/auth.js
Normal file
@@ -0,0 +1,69 @@
|
||||
const accessToken = localStorage.getItem('accessToken');
|
||||
|
||||
async function isAccessTokenOkay() {
|
||||
try {
|
||||
const response = await fetch('/auth/check_access_token', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
}
|
||||
});
|
||||
|
||||
if (response.status === 200) return true;
|
||||
if (response.status === 401) return false;
|
||||
|
||||
console.error('Error: server sent unexpected HTTP status code', response.status);
|
||||
return false;
|
||||
} catch (err) {
|
||||
console.error('Network or server error:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (!accessToken) return;
|
||||
|
||||
const valid = await isAccessTokenOkay();
|
||||
if (valid && window.location.pathname === '/web/login') {
|
||||
window.location.href = '/web/libraries';
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
window.location.href = '/web/login';
|
||||
}
|
||||
})();
|
||||
|
||||
//used in /web/login, not a general purpose function
|
||||
async function getAccessToken() {
|
||||
const username = document.getElementById('username').value;
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
try {
|
||||
const response = await fetch('/auth/user_and_pass', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
if (response.status === 200) {
|
||||
const data = await response.json();
|
||||
const accessToken = data.AccessToken;
|
||||
|
||||
if (!accessToken) {
|
||||
alert('Login failed: no token returned');
|
||||
return;
|
||||
}
|
||||
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
window.location.href = '/web/libraries';
|
||||
} else if (response.status === 401) {
|
||||
alert('Invalid username or password');
|
||||
} else {
|
||||
alert('Server error, please try again later.');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Network error, please try again later.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user