Skip to content

Commit

Permalink
Refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
rkyslyy committed Jul 2, 2024
1 parent d64e95c commit 6e3b0ce
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 5 deletions.
6 changes: 5 additions & 1 deletion web/auth.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { NextAuthConfig, Session } from 'next-auth'
import CognitoProvider from 'next-auth/providers/cognito'
import { COGNITO_CLIENT_ID, COGNITO_USER_POOL_ID, REGION } from './config'
import { refreshTokensIfNeeded } from './auth'

if (process.env.NEXTAUTH_URL && process.env.NEXTAUTH_URL.includes('set-me-in-.env')) {
console.error(`Please set WEB_DOMAIN in .env.${process.env.SST_STAGE} to the URL of your frontend site.`)
Expand Down Expand Up @@ -52,7 +53,10 @@ export const authConfig = {
}
}

return token
// already logged-in
// refresh access token if needed
const session: Session = token as Session
return await refreshTokensIfNeeded(session)
},
},
pages: { signIn: '/' },
Expand Down
57 changes: 53 additions & 4 deletions web/auth.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,60 @@
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import NextAuth, { Session } from 'next-auth'
import { authConfig } from './auth.config'
import type { JWT } from 'next-auth/jwt'
import { COGNITO_CLIENT_ID, COGNITO_DOMAIN_NAME } from './config'

export const handler = NextAuth({ ...authConfig });
interface CognitoRefreshTokenResult {
access_token: string
expires_in: number
id_token: string
refresh_token: string
}

export const refreshCognitoAccessToken = async (tokens: JWT): Promise<CognitoRefreshTokenResult> => {
if (!COGNITO_CLIENT_ID) throw new Error('COGNITO_CLIENT_ID is not set')
if (!COGNITO_DOMAIN_NAME) throw new Error('COGNITO_DOMAIN_NAME is not set')

const res = await fetch(`https://${COGNITO_DOMAIN_NAME}/oauth2/token`, {
method: 'POST',
headers: new Headers({ 'content-type': 'application/x-www-form-urlencoded' }),
body: Object.entries({
grant_type: 'refresh_token',
client_id: COGNITO_CLIENT_ID,
refresh_token: tokens.refreshToken,
})
.map(([k, v]) => `${k}=${v}`)
.join('&'),
})

if (!res.ok) {
throw new Error(JSON.stringify(await res.json()))
}

const newTokens = (await res.json()) as CognitoRefreshTokenResult

return newTokens
}

export const refreshTokensIfNeeded = async (session: Session): Promise<Session> => {
// return current token if the access token has not expired yet
// 10s buffer for clock skew etc
if (Date.now() + 10000 < session.accessTokenExpires) return session

// access token has expired, try to get a new one
const refreshedTokens = await refreshCognitoAccessToken(session)

// return session with updated tokens
return {
...session,
accessToken: refreshedTokens?.access_token,
accessTokenExpires: refreshedTokens?.expires_in ? Date.now() + refreshedTokens?.expires_in * 1000 : 0,
refreshToken: refreshedTokens?.refresh_token ?? session.refreshToken, // Fall back to old refresh token
}
}

export const {
auth,
signIn,
signOut,
handlers: { GET, POST },
} = handler;
} = NextAuth({ ...authConfig })

0 comments on commit 6e3b0ce

Please sign in to comment.