Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When using dbAuth, don't call getToken multiple times per page #5816

Merged
merged 21 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/auth/src/authClients/__tests__/dbAuth.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jest.mock('cross-undici-fetch', () => {
})

beforeAll(() => {
global.fetch = jest.fn().mockImplementation(() => {
global.fetch = jest.fn().mockImplementation(async () => {
return { text: () => '', json: () => ({}) }
})
})
Expand Down
70 changes: 54 additions & 16 deletions packages/auth/src/authClients/dbAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,84 +19,122 @@ export type DbAuthConfig = {
credentials: 'include' | 'same-origin'
}
}
const TOKEN_CACHE_TIME = 5000

let getTokenPromise: null | Promise<string | null>
let lastTokenCheckAt = new Date('1970-01-01T00:00:00')
let cachedToken: string | null

export const dbAuth = (
_client: DbAuth,
config: DbAuthConfig = { fetchConfig: { credentials: 'same-origin' } }
): AuthClient => {
const { credentials } = config.fetchConfig

const resetAndFetch = async (...params: Parameters<typeof fetch>) => {
resetTokenCache()
return fetch(...params)
}

const isTokenCacheExpired = () => {
const now = new Date()
return now.getTime() - lastTokenCheckAt.getTime() > TOKEN_CACHE_TIME
}

const resetTokenCache = () => {
lastTokenCheckAt = new Date('1970-01-01T00:00:00')
cachedToken = null
}

const forgotPassword = async (username: string) => {
const response = await fetch(global.RWJS_API_DBAUTH_URL, {
const response = await resetAndFetch(global.RWJS_API_DBAUTH_URL, {
credentials,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, method: 'forgotPassword' }),
})

return await response.json()
}

const getToken = async () => {
const response = await fetch(
`${global.RWJS_API_DBAUTH_URL}?method=getToken`,
{ credentials }
)
const token = await response.text()

if (token.length === 0) {
return null
} else {
return token
// Return the existing fetch promise, so that parallel calls
// to getToken only cause a single fetch
if (getTokenPromise) {
return getTokenPromise
}

if (isTokenCacheExpired()) {
getTokenPromise = fetch(`${global.RWJS_API_DBAUTH_URL}?method=getToken`, {
credentials,
})
.then((response) => response.text())
.then((tokenText) => {
lastTokenCheckAt = new Date()
getTokenPromise = null
cachedToken = tokenText.length === 0 ? null : tokenText

return cachedToken
})

return getTokenPromise
}

return cachedToken
}

const login = async (attributes: LoginAttributes) => {
const { username, password } = attributes
const response = await fetch(global.RWJS_API_DBAUTH_URL, {
const response = await resetAndFetch(global.RWJS_API_DBAUTH_URL, {
credentials,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, method: 'login' }),
})

return await response.json()
}

const logout = async () => {
await fetch(global.RWJS_API_DBAUTH_URL, {
await resetAndFetch(global.RWJS_API_DBAUTH_URL, {
credentials,
method: 'POST',
body: JSON.stringify({ method: 'logout' }),
})

return true
}

const resetPassword = async (attributes: ResetPasswordAttributes) => {
const response = await fetch(global.RWJS_API_DBAUTH_URL, {
const response = await resetAndFetch(global.RWJS_API_DBAUTH_URL, {
credentials,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...attributes, method: 'resetPassword' }),
})

return await response.json()
}

const signup = async (attributes: SignupAttributes) => {
const response = await fetch(global.RWJS_API_DBAUTH_URL, {
const response = await resetAndFetch(global.RWJS_API_DBAUTH_URL, {
credentials,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...attributes, method: 'signup' }),
})

return await response.json()
}

const validateResetToken = async (resetToken: string | null) => {
const response = await fetch(global.RWJS_API_DBAUTH_URL, {
const response = await resetAndFetch(global.RWJS_API_DBAUTH_URL, {
credentials,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ resetToken, method: 'validateResetToken' }),
})

return await response.json()
}

Expand Down