Skip to content

Commit

Permalink
refresh JWT via setMultiAuthCookies
Browse files Browse the repository at this point in the history
  • Loading branch information
Soxasora committed Feb 15, 2025
1 parent 025c646 commit abed173
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 29 deletions.
3 changes: 2 additions & 1 deletion pages/api/auth/[...nextauth].js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ function getCallbacks (req, res) {
*/
async jwt ({ token, user, account, profile, isNewUser }) {
if (user) {
console.log('user', user)
// token won't have an id on it for new logins, we add it
// note: token is what's kept in the jwt
token.id = Number(user.id)
Expand Down Expand Up @@ -199,7 +200,7 @@ async function pubkeyAuth (credentials, req, res, pubkeyColumnName) {
let user = await prisma.user.findUnique({ where: { [pubkeyColumnName]: pubkey } })

// make following code aware of cookie pointer for account switching
req = await multiAuthMiddleware(req)
req = multiAuthMiddleware(req)
// token will be undefined if we're not logged in at all or if we switched to anon
const token = await getToken({ req })
if (!user) {
Expand Down
33 changes: 5 additions & 28 deletions pages/api/graphql.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import lnd from '@/api/lnd'
import typeDefs from '@/api/typeDefs'
import { getServerSession } from 'next-auth/next'
import { getAuthOptions } from './auth/[...nextauth]'
import { decode as decodeJWT, encode as encodeJWT } from 'next-auth/jwt'
import search from '@/api/search'
import {
ApolloServerPluginLandingPageLocalDefault,
Expand Down Expand Up @@ -68,8 +67,8 @@ export default startServerAndCreateNextHandler(apolloServer, {
session = { user: { ...sessionFields, apiKey: true } }
}
} else {
req = await multiAuthMiddleware(req)
session = await getServerSession(req, res, getAuthOptions(req))
req = multiAuthMiddleware(req)
session = await getServerSession(req, res, getAuthOptions(req, res))
}
return {
models,
Expand All @@ -83,15 +82,14 @@ export default startServerAndCreateNextHandler(apolloServer, {
}
})

export async function multiAuthMiddleware (request) {
export function multiAuthMiddleware (request) {
// switch next-auth session cookie with multi_auth cookie if cookie pointer present

// is there a cookie pointer?
const cookiePointerName = 'multi_auth.user-id'
const hasCookiePointer = !!request.cookies[cookiePointerName]

// for development purposes, TODO REMOVE THIS
const secure = process.env.NODE_ENV === 'development'
const secure = process.env.NODE_ENV === 'production'

// is there a session?
const sessionCookieName = secure ? '__Secure-next-auth.session-token' : 'next-auth.session-token'
Expand All @@ -117,30 +115,9 @@ export async function multiAuthMiddleware (request) {

if (userJWT) {
// use JWT found in cookie pointed to by cookie pointer
// refresh JWT if possible
request.cookies[sessionCookieName] = await refreshJWT(userJWT)
request.cookies[sessionCookieName] = userJWT
return request
}

return request
}

async function refreshJWT (userJWT) {
try {
const secret = process.env.NEXTAUTH_SECRET
const decodedJWT = await decodeJWT({ token: userJWT, secret })
// check if JWT is almost expired
const timestampNow = Math.floor(Date.now() / 1000)
const tokenExpiry = decodedJWT.exp || 0
const refreshThreshold = 60 * 60 * 24 // 24 hours
if (tokenExpiry - timestampNow < refreshThreshold) {
console.log('refreshing almost expired JWT')
const refreshedJWT = await encodeJWT({ token: decodedJWT, secret })
return refreshedJWT
}
return userJWT
} catch (e) {
console.error('error refreshing JWT', e)
return userJWT
}
}

0 comments on commit abed173

Please sign in to comment.