Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | import Crowi from './Crowi'
import queryString from 'query-string'
export default class CrowiAuth {
crowi: Crowi
window: Window
location: Crowi['location']
localStorage: Crowi['localStorage']
constructor(crowi: Crowi) {
this.crowi = crowi
this.window = crowi.window
this.location = crowi.location
this.localStorage = crowi.localStorage
this.onStorage = this.onStorage.bind(this)
this.subscribeStorage()
this.updateState()
}
isAuthenticated(): boolean {
const { id = '', name = '' } = this.crowi.getUser() || {}
return !!(id && name)
}
subscribeStorage() {
this.window.addEventListener('storage', this.onStorage)
}
shouldUpdate(): boolean {
return String(this.isAuthenticated()) !== this.localStorage.getItem('authenticated')
}
updateState() {
if (this.shouldUpdate()) {
this.localStorage.setItem('authenticated', String(this.isAuthenticated()))
}
}
onStorage(e: StorageEvent) {
const { key, newValue } = e
const isAuthenticated = newValue === 'true'
if (key === 'authenticated') {
if (isAuthenticated) {
this.onLogin()
} else {
this.onLogout()
}
}
}
onLogin() {
const { continue: continueUrl = '/' } = queryString.parse(this.location.search)
if (continueUrl) {
top.location.href = typeof continueUrl === 'string' ? continueUrl : '/'
} else {
this.location.reload()
}
}
onLogout() {
this.location.reload()
}
}
|