filesafe/public/js/auth.js

75 lines
2.0 KiB
JavaScript
Raw Normal View History

/* global swal, axios */
2018-10-09 19:52:41 +00:00
const page = {
// user token
token: localStorage.token,
// HTML elements
user: null,
pass: null
}
page.do = function (dest) {
2018-10-09 19:52:41 +00:00
const user = page.user.value
const pass = page.pass.value
if (!user)
return swal('An error occurred!', 'You need to specify a username.', 'error')
if (!pass)
return swal('An error occurred!', 'You need to specify a password.', 'error')
2018-10-09 19:52:41 +00:00
axios.post(`api/${dest}`, {
username: user,
password: pass
2018-10-09 19:52:41 +00:00
}).then(function (response) {
if (response.data.success === false)
return swal(`Unable to ${dest}!`, response.data.description, 'error')
2018-10-09 19:52:41 +00:00
localStorage.token = response.data.token
window.location = 'dashboard'
}).catch(function (error) {
console.error(error)
return swal('An error occurred!', 'There was an error with the request, please check the console for more information.', 'error')
})
}
page.verify = function () {
if (!page.token) return
axios.post('api/tokens/verify', {
token: page.token
2018-10-09 19:52:41 +00:00
}).then(function (response) {
if (response.data.success === false)
2018-10-09 19:52:41 +00:00
return swal('An error occurred!', response.data.description, 'error')
2018-10-09 19:52:41 +00:00
window.location = 'dashboard'
}).catch(function (error) {
console.log(error)
const description = error.response.data && error.response.data.description
? error.response.data.description
: 'There was an error with the request, please check the console for more information.'
return swal(`${error.response.status} ${error.response.statusText}`, description, 'error')
2018-10-09 19:52:41 +00:00
})
}
window.onload = function () {
page.verify()
page.user = document.querySelector('#user')
page.pass = document.querySelector('#pass')
// Prevent default form's submit action
document.querySelector('#authForm').addEventListener('submit', function (event) {
event.preventDefault()
})
document.querySelector('#loginBtn').addEventListener('click', function () {
page.do('login')
})
document.querySelector('#registerBtn').addEventListener('click', function () {
page.do('register')
})
}