Refactor multiAuthMiddleware
This commit is contained in:
parent
64e176ce1d
commit
58a1ee929b
|
@ -15,20 +15,39 @@ const referrerMiddleware = (request) => {
|
||||||
|
|
||||||
const multiAuthMiddleware = (request) => {
|
const multiAuthMiddleware = (request) => {
|
||||||
// switch next-auth session cookie with multi_auth cookie if cookie pointer present
|
// switch next-auth session cookie with multi_auth cookie if cookie pointer present
|
||||||
const userId = request.cookies?.get('multi_auth.user-id')?.value
|
|
||||||
|
// is there a cookie pointer?
|
||||||
|
const cookiePointerName = 'multi_auth.user-id'
|
||||||
|
const hasCookiePointer = request.cookies?.has(cookiePointerName)
|
||||||
|
// is there a session?
|
||||||
const sessionCookieName = '__Secure-next-auth.session-token'
|
const sessionCookieName = '__Secure-next-auth.session-token'
|
||||||
const hasSession = request.cookies?.has(sessionCookieName)
|
const hasSession = request.cookies?.has(sessionCookieName)
|
||||||
if (userId && hasSession) {
|
|
||||||
if (userId === 'anonymous') {
|
if (!hasCookiePointer || !hasSession) {
|
||||||
// user switched to anon
|
// no session or no cookie pointer. do nothing.
|
||||||
request.cookies.delete(sessionCookieName)
|
return NextResponse.next({ request })
|
||||||
} else {
|
|
||||||
const userJWT = request.cookies.get(`multi_auth.${userId}`)?.value
|
|
||||||
if (userJWT) request.cookies.set(sessionCookieName, userJWT)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const response = NextResponse.next({ request })
|
|
||||||
return response
|
const userId = request.cookies?.get(cookiePointerName)?.value
|
||||||
|
if (userId === 'anonymous') {
|
||||||
|
// user switched to anon. only delete session cookie.
|
||||||
|
request.cookies.delete(sessionCookieName)
|
||||||
|
return NextResponse.next({ request })
|
||||||
|
}
|
||||||
|
|
||||||
|
const userJWT = request.cookies.get(`multi_auth.${userId}`)?.value
|
||||||
|
if (!userJWT) {
|
||||||
|
// no multi auth JWT found
|
||||||
|
return NextResponse.next({ request })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userJWT) {
|
||||||
|
// multi auth JWT found in cookie that pointed to by cookie pointer that is different to current session cookie.
|
||||||
|
request.cookies.set(sessionCookieName, userJWT)
|
||||||
|
return NextResponse.next({ request })
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next({ request })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function middleware (request) {
|
export function middleware (request) {
|
||||||
|
|
Loading…
Reference in New Issue