Notes/static/js/session.mjs
Magnus Åhall c255b58335 Wip
2023-06-17 09:11:14 +02:00

76 lines
1.9 KiB
JavaScript

export class Session {
constructor(app) {
this.app = app
this.UUID = ''
this.initialized = false
this.UserID = 0
}
initialize() {//{{{
// Retrieving the stored session UUID, if any.
// If one found, validate with server.
// If the browser doesn't know anything about a session,
// a call to /session/create is necessary to retrieve a session UUID.
let uuid= window.localStorage.getItem("session.UUID")
if(uuid === null) {
this.create()
return
}
// When loading the page, the web app needs to know session information
// such as user ID and possibly some state to render properly.
//
// A call to /session/retrieve with a session UUID validates that the
// session is still valid and returns all session information.
this.UUID = uuid
this.app.request('/session/retrieve', {})
.then(res=>{
if(res.Valid) {
// Session exists on server.
// Not necessarily authenticated.
this.UserID = res.Session.UserID // could be 0
this.initialized = true
this.app.forceUpdate()
} else {
// Session has probably expired. A new is required.
this.create()
}
})
.catch(this.app.responseError)
}//}}}
create() {//{{{
this.app.request('/session/create', {})
.then(res=>{
this.UUID = res.Session.UUID
window.localStorage.setItem('session.UUID', this.UUID)
this.initialized = true
this.app.forceUpdate()
})
.catch(this.responseError)
}//}}}
authenticate(username, password) {//{{{
this.app.login.current.authentication_failed.value = false
this.app.request('/session/authenticate', {
username,
password,
})
.then(res=>{
if(res.Authenticated) {
this.UserID = res.Session.UserID
this.app.forceUpdate()
} else {
this.app.login.current.authentication_failed.value = true
}
})
.catch(this.app.responseError)
}//}}}
authenticated() {//{{{
return this.UserID != 0
}//}}}
}
// vim: foldmethod=marker