Skip to content

Commit

Permalink
feat: Add refresh method to the auth SDK
Browse files Browse the repository at this point in the history
  • Loading branch information
sradevski committed Sep 5, 2024
1 parent 19bb46e commit 1861e4e
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions packages/core/js-sdk/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,7 @@ export class Auth {
return { location }
}

// By default we just set the token in memory, if configured to use sessions we convert it into session storage instead.
if (this.config?.auth?.type === "session") {
await this.client.fetch("/auth/session", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
})
} else {
this.client.setToken(token as string)
}

await this.setToken_(token as string)
return token as string
}

Expand All @@ -76,16 +67,21 @@ export class Auth {
}
)

// By default we just set the token in memory, if configured to use sessions we convert it into session storage instead.
if (this.config?.auth?.type === "session") {
await this.client.fetch("/auth/session", {
await this.setToken_(token)
return token
}

refresh = async () => {
const { token } = await this.client.fetch<{ token: string }>(
"/auth/token/refresh",
{
method: "POST",
headers: { Authorization: `Bearer ${token}` },
})
} else {
this.client.setToken(token)
}
}
)

// Putting the token in session after refreshing is only useful when the new token has updated info (eg. actor_id).
// Ideally we don't use the full JWT in session as key, but just store a pseudorandom key that keeps the rest of the auth context as value.
await this.setToken_(token)
return token
}

Expand All @@ -98,4 +94,16 @@ export class Auth {

this.client.clearToken()
}

private setToken_ = async (token: string) => {
// By default we just set the token in the configured storage, if configured to use sessions we convert it into session storage instead.
if (this.config?.auth?.type === "session") {
await this.client.fetch("/auth/session", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
})
} else {
this.client.setToken(token)
}
}
}

0 comments on commit 1861e4e

Please sign in to comment.