Check if token expired before refresh (#2101)
This commit is contained in:
parent
fd7ffb90f5
commit
1103f04f4b
23
lib/auth.js
23
lib/auth.js
@ -135,6 +135,13 @@ async function resetMultiAuthCookies (req, res) {
|
|||||||
setMultiAuthCookies(req, res, { ...decoded, jwt: token })
|
setMultiAuthCookies(req, res, { ...decoded, jwt: token })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class JwtExpiredError extends Error {
|
||||||
|
constructor () {
|
||||||
|
super('token expired')
|
||||||
|
this.name = 'JwtExpiredError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshMultiAuthCookies (req, res) {
|
async function refreshMultiAuthCookies (req, res) {
|
||||||
const httpOnlyOptions = cookieOptions()
|
const httpOnlyOptions = cookieOptions()
|
||||||
const jsOptions = { ...httpOnlyOptions, httpOnly: false }
|
const jsOptions = { ...httpOnlyOptions, httpOnly: false }
|
||||||
@ -145,8 +152,12 @@ async function refreshMultiAuthCookies (req, res) {
|
|||||||
|
|
||||||
const refreshToken = async (token) => {
|
const refreshToken = async (token) => {
|
||||||
const secret = process.env.NEXTAUTH_SECRET
|
const secret = process.env.NEXTAUTH_SECRET
|
||||||
|
const decoded = await decodeJWT({ token, secret })
|
||||||
|
if (decoded.exp <= Date.now() / 1000) {
|
||||||
|
throw new JwtExpiredError()
|
||||||
|
}
|
||||||
return await encodeJWT({
|
return await encodeJWT({
|
||||||
token: await decodeJWT({ token, secret }),
|
token: decoded,
|
||||||
secret
|
secret
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -161,7 +172,15 @@ async function refreshMultiAuthCookies (req, res) {
|
|||||||
|
|
||||||
if (MULTI_AUTH_JWT_REGEXP.test(key) || key === SESSION_COOKIE) {
|
if (MULTI_AUTH_JWT_REGEXP.test(key) || key === SESSION_COOKIE) {
|
||||||
const oldToken = value
|
const oldToken = value
|
||||||
const newToken = await refreshToken(oldToken)
|
let newToken
|
||||||
|
try {
|
||||||
|
newToken = await refreshToken(oldToken)
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof JwtExpiredError) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
throw err
|
||||||
|
}
|
||||||
res.appendHeader('Set-Cookie', cookie.serialize(key, newToken, httpOnlyOptions))
|
res.appendHeader('Set-Cookie', cookie.serialize(key, newToken, httpOnlyOptions))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user