| 1 |
import Dexie from "dexie"; |
| 2 |
import { fadeOut } from "./transition"; |
| 3 |
|
| 4 |
/** |
| 5 |
* Manages the logged-in user's session and access token. |
| 6 |
* The session replica is stored in IndexedDB so that the service worker can access it. |
| 7 |
*/ |
| 8 |
class Session { |
| 9 |
constructor() { |
| 10 |
const db = new Dexie("session-replica"); |
| 11 |
db.version(1).stores({ |
| 12 |
kv: "&key", |
| 13 |
}); |
| 14 |
this.db = db; |
| 15 |
|
| 16 |
// existing sessions (pre-v2.6.0) haven't called `store` with the session-replica, |
| 17 |
// so attempt to sync any values from localStorage to IndexedDB |
| 18 |
if (typeof localStorage !== "undefined" && this.exists()) { |
| 19 |
const username = this.username(); |
| 20 |
const token = this.token(); |
| 21 |
|
| 22 |
this.db.kv |
| 23 |
.bulkPut([ |
| 24 |
{ key: "user", value: username }, |
| 25 |
{ key: "token", value: token }, |
| 26 |
]) |
| 27 |
.then(() => { |
| 28 |
console.log("[Session] Synced localStorage session to IndexedDB", { username }); |
| 29 |
}) |
| 30 |
.catch((e) => { |
| 31 |
console.error("[Session] Failed to sync localStorage session to IndexedDB", e); |
| 32 |
}); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
async store(username, token) { |
| 37 |
await this.db.kv.bulkPut([ |
| 38 |
{ key: "user", value: username }, |
| 39 |
{ key: "token", value: token }, |
| 40 |
{ key: "lastExtendedAt", value: Date.now() }, |
| 41 |
]); |
| 42 |
localStorage.setItem("user", username); |
| 43 |
localStorage.setItem("token", token); |
| 44 |
} |
| 45 |
|
| 46 |
async resetAndRedirect(url, { fade = false } = {}) { |
| 47 |
// User-initiated exits (logout, account deletion) fade out first, while data's intact, so the |
| 48 |
// wipe + reload doesn't flash a broken UI. Error redirects pass no options and cut straight through. |
| 49 |
if (fade) { |
| 50 |
await fadeOut(); |
| 51 |
} |
| 52 |
await this.db.delete(); |
| 53 |
localStorage.removeItem("user"); |
| 54 |
localStorage.removeItem("token"); |
| 55 |
window.location.href = url; |
| 56 |
} |
| 57 |
|
| 58 |
async usernameAsync() { |
| 59 |
return (await this.db.kv.get({ key: "user" }))?.value; |
| 60 |
} |
| 61 |
|
| 62 |
async tokenAsync() { |
| 63 |
return (await this.db.kv.get({ key: "token" }))?.value; |
| 64 |
} |
| 65 |
|
| 66 |
async lastExtendedAtAsync() { |
| 67 |
return (await this.db.kv.get({ key: "lastExtendedAt" }))?.value; |
| 68 |
} |
| 69 |
|
| 70 |
async setLastExtendedAtAsync() { |
| 71 |
await this.db.kv.put({ key: "lastExtendedAt", value: Date.now() }); |
| 72 |
} |
| 73 |
|
| 74 |
exists() { |
| 75 |
return this.username() && this.token(); |
| 76 |
} |
| 77 |
|
| 78 |
username() { |
| 79 |
return localStorage.getItem("user"); |
| 80 |
} |
| 81 |
|
| 82 |
token() { |
| 83 |
return localStorage.getItem("token"); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
const session = new Session(); |
| 88 |
export default session; |