2023-11-14 07:27:04 +00:00
|
|
|
const m = require('mithril')
|
2023-11-09 09:44:04 +00:00
|
|
|
const storageName = 'nfp_sites_filadelfia_web_logintoken'
|
|
|
|
|
|
|
|
const Authentication = {
|
|
|
|
currentUser: null,
|
|
|
|
isAdmin: false,
|
|
|
|
loadingListeners: [],
|
|
|
|
authListeners: [],
|
|
|
|
|
|
|
|
updateToken: function(token) {
|
|
|
|
if (!token) return Authentication.clearToken()
|
|
|
|
localStorage.setItem(storageName, token)
|
|
|
|
Authentication.currentUser = JSON.parse(atob(token.split('.')[1]))
|
|
|
|
|
|
|
|
if (Authentication.authListeners.length) {
|
|
|
|
Authentication.authListeners.forEach(function(x) { x(Authentication.currentUser) })
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
clearToken: function() {
|
|
|
|
Authentication.currentUser = null
|
|
|
|
localStorage.removeItem(storageName)
|
|
|
|
Authentication.isAdmin = false
|
|
|
|
},
|
|
|
|
|
|
|
|
addEvent: function(event) {
|
|
|
|
Authentication.authListeners.push(event)
|
|
|
|
},
|
|
|
|
|
|
|
|
setAdmin: function(item) {
|
|
|
|
Authentication.isAdmin = item
|
|
|
|
},
|
|
|
|
|
|
|
|
getToken: function() {
|
|
|
|
return localStorage.getItem(storageName)
|
|
|
|
},
|
2023-11-14 07:27:04 +00:00
|
|
|
|
2023-11-20 07:12:08 +00:00
|
|
|
getTokenDecoded: function() {
|
|
|
|
let token = Authentication.getToken()
|
|
|
|
var base64Url = token.split('.')[1];
|
|
|
|
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
|
|
|
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
|
|
|
|
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
|
|
|
|
}).join(''));
|
|
|
|
|
|
|
|
return JSON.parse(jsonPayload);
|
|
|
|
},
|
|
|
|
|
2023-11-14 07:27:04 +00:00
|
|
|
requiresLogin: function() {
|
|
|
|
if (Authentication.currentUser) return
|
|
|
|
m.route.set('/')
|
|
|
|
},
|
|
|
|
|
|
|
|
requiresNotLogin: function() {
|
|
|
|
if (!Authentication.currentUser) return
|
|
|
|
m.route.set('/browse')
|
|
|
|
},
|
2023-11-09 09:44:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Authentication.updateToken(localStorage.getItem(storageName))
|
|
|
|
|
|
|
|
window.Authentication = Authentication
|
|
|
|
|
|
|
|
module.exports = Authentication
|