Notes/static/js/session.mjs

77 lines
2.0 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()
}
})
.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
2024-01-06 11:40:58 +01:00
window.localStorage.setItem('session.UUID', this.UUID)
2024-01-05 20:00:02 +01:00
this.initialized = true
this.app.forceUpdate()
})
.catch(this.responseError)
2023-06-16 07:11:27 +02:00
}//}}}
2024-01-06 11:40:58 +01:00
reset() {//{{{
window.localStorage.removeItem('session.UUID')
this.initialized = false
this.UserID = 0
}//}}}
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