Notes/static/js/session.mjs

75 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-06-16 07:11:27 +02:00
export class Session {
2024-01-05 21:14:55 +01:00
constructor(app) {//{{{
2023-06-16 07:11:27 +02:00
this.app = app
this.UUID = ''
this.initialized = false
this.UserID = 0
2024-01-05 21:14:55 +01:00
}//}}}
2023-06-16 07:11:27 +02:00
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.
2024-01-05 20:00:02 +01:00
let uuid = window.localStorage.getItem("session.UUID")
if (uuid === null) {
2023-06-16 07:11:27 +02:00
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
2024-01-05 20:00:02 +01:00
this.app.request('/_session/retrieve', {})
.then(res => {
if (res.Error === undefined) {
// Session exists on server.
// Not necessarily authenticated.
2024-01-05 21:14:55 +01:00
this.UserID = res.Session.UserID // could be 0
2024-01-05 20:00:02 +01:00
this.initialized = true
this.app.forceUpdate()
} else {
// Session has probably expired. A new is required.
this.create()
}
})
.catch(this.app.responseError)
2023-06-16 07:11:27 +02:00
}//}}}
create() {//{{{
2024-01-05 20:00:02 +01:00
this.app.request('/_session/new', {})
.then(res => {
this.UUID = res.Session.UUID
window.localStorage.setItem('session.UUID', this.Session.UUID)
this.initialized = true
this.app.forceUpdate()
})
.catch(this.responseError)
2023-06-16 07:11:27 +02:00
}//}}}
authenticate(username, password) {//{{{
2023-06-17 09:11:14 +02:00
this.app.login.current.authentication_failed.value = false
2024-01-05 20:00:02 +01:00
this.app.request('/_session/authenticate', {
2023-06-16 07:11:27 +02:00
username,
password,
})
2024-01-05 20:00:02 +01:00
.then(res => {
if (res.Authenticated) {
2024-01-05 21:14:55 +01:00
this.UserID = res.UserID
2024-01-05 20:00:02 +01:00
this.app.forceUpdate()
} else {
this.app.login.current.authentication_failed.value = true
}
})
.catch(this.app.responseError)
2023-06-16 07:11:27 +02:00
}//}}}
authenticated() {//{{{
return this.UserID != 0
}//}}}
}
// vim: foldmethod=marker