Notes/static/js/session.mjs
2024-01-06 11:40:58 +01:00

77 lines
2.0 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.Error === undefined) {
// Session exists on server.
// Not necessarily authenticated.
this.UserID = res.Session.UserID // could be 0
this.initialized = true
this.app.forceUpdate()
}
})
.catch(this.app.responseError)
}//}}}
create() {//{{{
this.app.request('/_session/new', {})
.then(res => {
this.UUID = res.Session.UUID
window.localStorage.setItem('session.UUID', this.UUID)
this.initialized = true
this.app.forceUpdate()
})
.catch(this.responseError)
}//}}}
reset() {//{{{
window.localStorage.removeItem('session.UUID')
this.initialized = false
this.UserID = 0
}//}}}
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.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