2019-02-20 16:10:37 +00:00
|
|
|
const storageName = 'logintoken'
|
|
|
|
|
|
|
|
const Authentication = {
|
|
|
|
currentUser: null,
|
2019-10-01 03:45:44 +00:00
|
|
|
isAdmin: false,
|
2019-02-20 16:10:37 +00:00
|
|
|
loadedGoogle: false,
|
|
|
|
loadingGoogle: false,
|
|
|
|
loadingListeners: [],
|
2019-10-01 03:45:44 +00:00
|
|
|
authListeners: [],
|
2019-02-20 16:10:37 +00:00
|
|
|
|
|
|
|
updateToken: function(token) {
|
|
|
|
if (!token) return Authentication.clearToken()
|
|
|
|
localStorage.setItem(storageName, token)
|
2019-09-13 13:33:10 +00:00
|
|
|
Authentication.currentUser = JSON.parse(atob(token.split('.')[1]))
|
2019-10-01 03:45:44 +00:00
|
|
|
|
|
|
|
if (Authentication.authListeners.length) {
|
|
|
|
Authentication.authListeners.forEach(function(x) { x(Authentication.currentUser) })
|
|
|
|
}
|
2019-02-20 16:10:37 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
clearToken: function() {
|
|
|
|
Authentication.currentUser = null
|
|
|
|
localStorage.removeItem(storageName)
|
2019-10-01 03:45:44 +00:00
|
|
|
Authentication.isAdmin = false
|
|
|
|
},
|
|
|
|
|
|
|
|
addEvent: function(event) {
|
|
|
|
Authentication.authListeners.push(event)
|
|
|
|
},
|
|
|
|
|
|
|
|
setAdmin: function(item) {
|
|
|
|
Authentication.isAdmin = item
|
2019-02-20 16:10:37 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
createGoogleScript: function() {
|
|
|
|
if (Authentication.loadedGoogle) return Promise.resolve()
|
|
|
|
return new Promise(function (res) {
|
|
|
|
if (Authentication.loadedGoogle) return res()
|
|
|
|
Authentication.loadingListeners.push(res)
|
|
|
|
|
|
|
|
if (Authentication.loadingGoogle) return
|
|
|
|
Authentication.loadingGoogle = true
|
|
|
|
|
|
|
|
let gscript = document.createElement('script')
|
|
|
|
gscript.type = 'text/javascript'
|
|
|
|
gscript.async = true
|
|
|
|
gscript.defer = true
|
|
|
|
gscript.src = 'https://apis.google.com/js/platform.js?onload=googleLoaded'
|
|
|
|
document.body.appendChild(gscript)
|
|
|
|
})
|
2019-02-22 14:53:43 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
getToken: function() {
|
|
|
|
return localStorage.getItem(storageName)
|
|
|
|
},
|
2019-02-20 16:10:37 +00:00
|
|
|
}
|
|
|
|
|
2019-10-01 03:45:44 +00:00
|
|
|
if (!window.googleLoaded) {
|
|
|
|
window.googleLoaded = function() {
|
|
|
|
Authentication.loadedGoogle = true
|
|
|
|
while (Authentication.loadingListeners.length) {
|
|
|
|
Authentication.loadingListeners.pop()()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-20 16:10:37 +00:00
|
|
|
Authentication.updateToken(localStorage.getItem(storageName))
|
|
|
|
|
|
|
|
module.exports = Authentication
|