1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2025-05-08 09:23:22 +02:00
ntfy/web/src/app/Session.js
nimbleghost 8ccfa5c3fb Fix session replica behaviour (merge with session)
The harder-to-refactor parts are the places where exists/username/token
are called within a React component. However, `resetAndRedirect` and
`store` are already called from async contexts, so adding an `await`
is simple.

This thus merges the logic, keeping localStorage for the components to
call, but making sure reset/store behaviour works correctly for the
replica.
2023-06-13 14:00:51 +02:00

50 lines
1.1 KiB
JavaScript

import Dexie from "dexie";
/**
* Manages the logged-in user's session and access token.
* The session replica is stored in IndexedDB so that the service worker can access it.
*/
class Session {
constructor() {
const db = new Dexie("session-replica");
db.version(1).stores({
kv: "&key",
});
this.db = db;
}
async store(username, token) {
await this.db.kv.bulkPut([
{ key: "user", value: username },
{ key: "token", value: token },
]);
localStorage.setItem("user", username);
localStorage.setItem("token", token);
}
async resetAndRedirect(url) {
await this.db.delete();
localStorage.removeItem("user");
localStorage.removeItem("token");
window.location.href = url;
}
async usernameAsync() {
return (await this.db.kv.get({ key: "user" }))?.value;
}
exists() {
return this.username() && this.token();
}
username() {
return localStorage.getItem("user");
}
token() {
return localStorage.getItem("token");
}
}
const session = new Session();
export default session;