1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-11-01 01:21:15 +01:00
ntfy/web/src/app/Session.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

70 lines
1.7 KiB
JavaScript
Raw Normal View History

import Dexie from "dexie";
2023-06-09 20:32:34 +02:00
/**
* 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.
*/
2022-12-02 21:37:48 +01:00
class Session {
constructor() {
const db = new Dexie("session-replica");
db.version(1).stores({
kv: "&key",
});
this.db = db;
// existing sessions (pre-v2.6.0) haven't called `store` with the session-replica,
// so attempt to sync any values from localStorage to IndexedDB
if (typeof localStorage !== "undefined" && this.exists()) {
const username = this.username();
const token = this.token();
this.db.kv
.bulkPut([
{ key: "user", value: username },
{ key: "token", value: token },
])
.then(() => {
console.log("[Session] Synced localStorage session to IndexedDB", { username });
})
.catch((e) => {
console.error("[Session] Failed to sync localStorage session to IndexedDB", e);
});
}
}
async store(username, token) {
await this.db.kv.bulkPut([
{ key: "user", value: username },
{ key: "token", value: token },
]);
2022-12-02 21:37:48 +01:00
localStorage.setItem("user", username);
localStorage.setItem("token", token);
}
async resetAndRedirect(url) {
await this.db.delete();
2022-12-02 21:37:48 +01:00
localStorage.removeItem("user");
localStorage.removeItem("token");
window.location.href = url;
2022-12-02 21:37:48 +01:00
}
async usernameAsync() {
return (await this.db.kv.get({ key: "user" }))?.value;
2022-12-26 04:29:55 +01:00
}
2022-12-08 02:44:20 +01:00
exists() {
return this.username() && this.token();
}
2022-12-02 21:37:48 +01:00
username() {
return localStorage.getItem("user");
}
token() {
return localStorage.getItem("token");
}
}
const session = new Session();
2022-12-02 21:37:48 +01:00
export default session;