Notes/static/js/session.mjs

76 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-06-16 07:11:27 +02:00
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.
2023-06-17 09:11:14 +02:00
// 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")
2023-06-16 07:11:27 +02:00
if(uuid === null) {
this.create()
2023-06-17 09:11:14 +02:00
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
2023-06-16 07:11:27 +02:00
this.initialized = true
this.app.forceUpdate()
2023-06-17 09:11:14 +02:00
} else {
// Session has probably expired. A new is required.
this.create()
}
})
.catch(this.app.responseError)
2023-06-16 07:11:27 +02:00
}//}}}
create() {//{{{
this.app.request('/session/create', {})
.then(res=>{
this.UUID = res.Session.UUID
window.localStorage.setItem('session.UUID', this.UUID)
2023-06-17 09:11:14 +02:00
this.initialized = true
2023-06-16 07:11:27 +02:00
this.app.forceUpdate()
})
.catch(this.responseError)
}//}}}
authenticate(username, password) {//{{{
2023-06-17 09:11:14 +02:00
this.app.login.current.authentication_failed.value = false
2023-06-16 07:11:27 +02:00
this.app.request('/session/authenticate', {
username,
password,
})
.then(res=>{
2023-06-17 09:11:14 +02:00
if(res.Authenticated) {
this.UserID = res.Session.UserID
this.app.forceUpdate()
} else {
this.app.login.current.authentication_failed.value = true
}
2023-06-16 07:11:27 +02:00
})
.catch(this.app.responseError)
}//}}}
authenticated() {//{{{
return this.UserID != 0
}//}}}
}
// vim: foldmethod=marker