Skip to content

Commit

Permalink
feat: Expire session cookie (#419)
Browse files Browse the repository at this point in the history
* Set session cookie to expire after 4 hours

* Handle unauthenticated GraphQL errors
  • Loading branch information
Suzanne Rozier authored Dec 10, 2021
1 parent 02faafd commit 14ccee4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 9 deletions.
32 changes: 30 additions & 2 deletions src/apolloClient.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@
import { ApolloClient, InMemoryCache } from '@apollo/client'
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client'
import { onError } from '@apollo/client/link/error'

const httpLink = new HttpLink({
uri: `/api/graphql`,
})

const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path, extensions }) => {
// TODO - log error
// eslint-disable-next-line no-console
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)

// Check for auth
if (extensions.code === 'UNAUTHENTICATED') {
// Redirect
window.location.href = '/login'
}
})

if (networkError) {
// TODO - log error
// eslint-disable-next-line no-console
console.error(`[Network error]: ${networkError}`)
}
})

export const client = new ApolloClient({
uri: '/api/graphql',
link: from([errorLink, httpLink]),
cache: new InMemoryCache(),
})
3 changes: 1 addition & 2 deletions src/lib/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ export const getSession = nextSession({
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
// TODO: set cookie max age
maxAge: 2 * 7 * 24 * 60 * 60, // 2 weeks
maxAge: 60 * 60 * 4, // 4 hours
sameSite: 'strict',
},
})
Expand Down
11 changes: 6 additions & 5 deletions src/pages/api/graphql.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,16 @@ export const apolloServer = new ApolloServer({
resolvers,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground],
context: async ({ req, res }) => {
const session = await getSession(req, res)

if (!session || !session.passport || !session.passport.user) {
throw new AuthenticationError('No user in session')
}

try {
const session = await getSession(req, res)
const client = await clientPromise
const db = client.db(process.env.MONGODB_DB)

if (!session || !session.passport || !session.passport.user) {
throw new AuthenticationError('No user in session')
}

const user = session.passport.user as SessionUser
const { userId } = user

Expand Down

0 comments on commit 14ccee4

Please sign in to comment.