Skip to content

Commit

Permalink
Fix login flow when session expires
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Oliver authored and n4bb12 committed Jun 5, 2024
1 parent e6a74c4 commit 6988705
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/client/plugin/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// thinks we are logged in.
//

import { parseJwt } from "./lib"

export interface Credentials {
username: string
uiToken: string
Expand Down Expand Up @@ -31,6 +33,22 @@ export function isLoggedIn() {
)
}

export function isTokenExpired() {
const token = localStorage.getItem("token")
if (typeof token !== "string") {
return true
}

const payload = parseJwt(token)
if (!payload) {
return true
}

// Report as expired before (real expiry - 30s)
const jsTimestamp = payload.exp * 1000 - 30000
return Date.now() >= jsTimestamp
}

export function validateCredentials(credentials: Credentials) {
return (
true && credentials.username && credentials.uiToken && credentials.npmToken
Expand Down
5 changes: 5 additions & 0 deletions src/client/plugin/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@ import {
clearCredentials,
Credentials,
isLoggedIn,
isTokenExpired,
saveCredentials,
validateCredentials,
} from "./credentials"
import { interruptClick, parseCookies, retry } from "./lib"

function saveAndRemoveCookies() {
if (isTokenExpired()) {
clearCredentials()
}

if (isLoggedIn()) {
return
}
Expand Down
13 changes: 13 additions & 0 deletions src/client/plugin/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ export function parseCookies(cookieStr: string) {
)
}

export function parseJwt(token: string) {
const base64Url = token.split(".")[1]
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/")
const jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
.join(""),
)

return JSON.parse(jsonPayload)
}

export function retry(action: () => void) {
for (let i = 0; i < 10; i++) {
setTimeout(() => action(), 100 * i)
Expand Down

0 comments on commit 6988705

Please sign in to comment.