2
0

🚑 (auth) Fix bad requests with getSession on server side

This commit is contained in:
Baptiste Arnaud
2023-04-03 16:42:10 +02:00
parent b96a3a6a8e
commit 49071b73b6
39 changed files with 112 additions and 91 deletions

View File

@@ -1,19 +1,27 @@
import prisma from '@/lib/prisma'
import { authOptions } from '@/pages/api/auth/[...nextauth]'
import { setUser } from '@sentry/nextjs'
import { User } from '@typebot.io/prisma'
import { NextApiRequest } from 'next'
import { getSession } from 'next-auth/react'
import { NextApiRequest, NextApiResponse } from 'next'
import { getServerSession } from 'next-auth'
import { mockedUser } from '../mockedUser'
import { env } from '@typebot.io/lib'
export const getAuthenticatedUser = async (
req: NextApiRequest
req: NextApiRequest,
res: NextApiResponse
): Promise<User | undefined> => {
const bearerToken = extractBearerToken(req)
if (bearerToken) return authenticateByToken(bearerToken)
const session = await getSession({ req })
if (!session?.user || !('id' in session.user)) return
const user = session.user as User
const user =
env('E2E_TEST') === 'true'
? mockedUser
: ((await getServerSession(req, res, authOptions))?.user as
| User
| undefined)
if (!user || !('id' in user)) return
setUser({ id: user.id, email: user.email ?? undefined })
return session?.user as User
return user
}
const authenticateByToken = async (

View File

@@ -3,7 +3,7 @@ import { inferAsyncReturnType } from '@trpc/server'
import * as trpcNext from '@trpc/server/adapters/next'
export async function createContext(opts: trpcNext.CreateNextContextOptions) {
const user = await getAuthenticatedUser(opts.req)
const user = await getAuthenticatedUser(opts.req, opts.res)
return {
user,

View File

@@ -1,4 +1,4 @@
import NextAuth, { Account } from 'next-auth'
import NextAuth, { Account, AuthOptions } from 'next-auth'
import EmailProvider from 'next-auth/providers/email'
import GitHubProvider from 'next-auth/providers/github'
import GitlabProvider from 'next-auth/providers/gitlab'
@@ -128,47 +128,53 @@ if (isNotEmpty(process.env.CUSTOM_OAUTH_WELL_KNOWN_URL)) {
})
}
const handler = (req: NextApiRequest, res: NextApiResponse) => {
if (req.url === '/api/auth/session' && env('E2E_TEST') === 'true')
return res.send({ user: mockedUser })
if (req.method === 'HEAD') return res.status(200)
return NextAuth(req, res, {
adapter: CustomAdapter(prisma),
secret: process.env.ENCRYPTION_SECRET,
providers,
session: {
strategy: 'database',
export const authOptions: AuthOptions = {
adapter: CustomAdapter(prisma),
secret: process.env.ENCRYPTION_SECRET,
providers,
session: {
strategy: 'database',
},
pages: {
signIn: '/signin',
},
callbacks: {
session: async ({ session, user }) => {
const userFromDb = user as User
await updateLastActivityDate(userFromDb)
return {
...session,
user: userFromDb,
}
},
pages: {
signIn: '/signin',
signIn: async ({ account, user }) => {
if (!account) return false
const isNewUser = !('createdAt' in user && isDefined(user.createdAt))
if (process.env.DISABLE_SIGNUP === 'true' && isNewUser && user.email) {
const { invitations, workspaceInvitations } =
await getNewUserInvitations(prisma, user.email)
if (invitations.length === 0 && workspaceInvitations.length === 0)
return false
}
const requiredGroups = getRequiredGroups(account.provider)
if (requiredGroups.length > 0) {
const userGroups = await getUserGroups(account)
return checkHasGroups(userGroups, requiredGroups)
}
return true
},
callbacks: {
session: async ({ session, user }) => {
const userFromDb = user as User
await updateLastActivityDate(userFromDb)
return {
...session,
user: userFromDb,
}
},
signIn: async ({ account, user }) => {
if (!account) return false
const isNewUser = !('createdAt' in user && isDefined(user.createdAt))
if (process.env.DISABLE_SIGNUP === 'true' && isNewUser && user.email) {
const { invitations, workspaceInvitations } =
await getNewUserInvitations(prisma, user.email)
if (invitations.length === 0 && workspaceInvitations.length === 0)
return false
}
const requiredGroups = getRequiredGroups(account.provider)
if (requiredGroups.length > 0) {
const userGroups = await getUserGroups(account)
return checkHasGroups(userGroups, requiredGroups)
}
return true
},
},
})
},
}
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const isMockingSession =
req.method === 'GET' &&
req.url === '/api/auth/session' &&
env('E2E_TEST') === 'true'
if (isMockingSession) return res.send({ user: mockedUser })
const requestIsFromCompanyFirewall = req.method === 'HEAD'
if (requestIsFromCompanyFirewall) return res.status(200).end()
return await NextAuth(req, res, authOptions)
}
const updateLastActivityDate = async (user: User) => {

View File

@@ -11,7 +11,7 @@ import {
} from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const workspaceId = req.query.workspaceId as string | undefined
if (!workspaceId) return badRequest(res)

View File

@@ -8,7 +8,7 @@ import {
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const workspaceId = req.query.workspaceId as string | undefined
if (!workspaceId) return badRequest(res)

View File

@@ -8,7 +8,7 @@ import { oauth2Client } from '@/lib/googleSheets'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const state = req.query.state as string | undefined
if (!state) return badRequest(res)

View File

@@ -11,7 +11,7 @@ import {
} from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const workspaceId = req.query.workspaceId as string | undefined
if (!workspaceId) return badRequest(res)

View File

@@ -9,7 +9,7 @@ import { got } from 'got'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const workspaceId = req.query.workspaceId as string | undefined
if (!workspaceId) return badRequest(res)

View File

@@ -9,7 +9,7 @@ import {
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const parentFolderId = req.query.parentId

View File

@@ -5,7 +5,7 @@ import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const id = req.query.id as string

View File

@@ -5,7 +5,7 @@ import { notAuthenticated } from '@typebot.io/lib/api'
import { SmtpCredentials } from '@typebot.io/schemas'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'POST') {
const { from, port, isTlsEnabled, username, password, host, to } = (

View File

@@ -10,7 +10,7 @@ import { setUser } from '@sentry/nextjs'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
setUser({ email: user.email ?? undefined, id: user.id })

View File

@@ -11,7 +11,7 @@ import { setUser } from '@sentry/nextjs'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
setUser({ email: user.email ?? undefined, id: user.id })

View File

@@ -4,7 +4,7 @@ import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const publicId = req.query.publicId as string | undefined

View File

@@ -11,7 +11,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { sendTelemetryEvents } from '@typebot.io/lib/telemetry/sendTelemetryEvent'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
try {
if (req.method === 'POST') {

View File

@@ -11,7 +11,7 @@ import {
import { sendTelemetryEvents } from '@typebot.io/lib/telemetry/sendTelemetryEvent'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const id = req.query.id as string

View File

@@ -13,7 +13,7 @@ const handler = async (
): Promise<void> => {
res.setHeader('Access-Control-Allow-Origin', '*')
if (req.method === 'GET') {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (

View File

@@ -6,7 +6,7 @@ import Stripe from 'stripe'
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const session = await createCheckoutSession(user.id)

View File

@@ -15,7 +15,7 @@ import { omit } from '@typebot.io/lib'
import { sendTelemetryEvents } from '@typebot.io/lib/telemetry/sendTelemetryEvent'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
try {
if (req.method === 'POST') {

View File

@@ -11,7 +11,7 @@ import { isReadTypebotForbidden } from '@/features/typebot/helpers/isReadTypebot
import { removeTypebotOldProperties } from '@/features/typebot/helpers/removeTypebotOldProperties'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const typebotId = req.query.typebotId as string

View File

@@ -6,7 +6,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { canReadTypebots } from '@/helpers/databaseRules'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const typebotId = req.query.typebotId as string

View File

@@ -6,7 +6,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const typebotId = req.query.typebotId as string

View File

@@ -9,7 +9,7 @@ import {
} from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const typebotId = req.query.typebotId as string

View File

@@ -5,7 +5,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const typebotId = req.query.typebotId as string
if (req.method === 'GET') {

View File

@@ -5,7 +5,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const typebotId = req.query.typebotId as string
const userId = req.query.userId as string

View File

@@ -17,7 +17,7 @@ import { env } from '@typebot.io/lib'
import { sendGuestInvitationEmail } from '@typebot.io/emails'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const typebotId = req.query.typebotId as string | undefined
if (!typebotId) return badRequest(res)

View File

@@ -6,7 +6,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const typebotId = req.query.typebotId as string
const email = req.query.email as string

View File

@@ -10,7 +10,7 @@ import {
import { getTypebot } from '@/features/typebot/helpers/getTypebot'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'POST') {
const typebotId = req.query.typebotId as string

View File

@@ -13,7 +13,7 @@ import { getTypebot } from '@/features/typebot/helpers/getTypebot'
import { omit } from '@typebot.io/lib'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
const typebotId = req.query.typebotId as string
const webhookId = req.query.webhookId as string
if (!user) return notAuthenticated(res)

View File

@@ -5,7 +5,7 @@ import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
import { User } from '@typebot.io/prisma'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const id = req.query.userId as string

View File

@@ -5,7 +5,7 @@ import { generateId } from '@typebot.io/lib'
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const apiTokens = await prisma.apiToken.findMany({

View File

@@ -4,7 +4,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'DELETE') {

View File

@@ -12,7 +12,7 @@ import { env } from '@typebot.io/lib'
import { isSeatsLimitReached } from '@typebot.io/lib/pricing'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'POST') {
const data = req.body as Omit<WorkspaceInvitation, 'id' | 'createdAt'>

View File

@@ -5,7 +5,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'PATCH') {
const data = req.body as Omit<WorkspaceInvitation, 'createdAt'>

View File

@@ -8,7 +8,7 @@ import {
} from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const id = req.query.workspaceId as string

View File

@@ -5,7 +5,7 @@ import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUs
import { methodNotAllowed, notAuthenticated } from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
if (req.method === 'PATCH') {
const workspaceId = req.query.workspaceId as string

View File

@@ -1,15 +1,16 @@
import { getSession } from 'next-auth/react'
import { NextPageContext } from 'next'
import { GetServerSidePropsContext } from 'next'
import { User } from '@typebot.io/prisma'
import { isNotDefined } from '@typebot.io/lib'
import { sign } from 'jsonwebtoken'
import { getServerSession } from 'next-auth'
import { authOptions } from './api/auth/[...nextauth]'
export default function Page() {
return null
}
export async function getServerSideProps(context: NextPageContext) {
const session = await getSession(context)
export async function getServerSideProps(context: GetServerSidePropsContext) {
const session = await getServerSession(context.req, context.res, authOptions)
if (isNotDefined(session?.user))
return {
redirect: {

View File

@@ -1,15 +1,16 @@
import { getSession } from 'next-auth/react'
import { NextPageContext } from 'next'
import { getServerSession } from 'next-auth'
import { User } from '@typebot.io/prisma'
import { isNotDefined } from '@typebot.io/lib'
import { sign } from 'jsonwebtoken'
import { authOptions } from '../api/auth/[...nextauth]'
import { GetServerSidePropsContext } from 'next'
export default function Page() {
return null
}
export async function getServerSideProps(context: NextPageContext) {
const session = await getSession(context)
export async function getServerSideProps(context: GetServerSidePropsContext) {
const session = await getServerSession(context.req, context.res, authOptions)
const feedbackId = context.query.feedbackId?.toString() as string
if (isNotDefined(session?.user))
return {

View File

@@ -1,6 +1,7 @@
import { getLocaleProps } from '@/locales'
import { GetServerSidePropsContext } from 'next'
import { getSession } from 'next-auth/react'
import { getServerSession } from 'next-auth'
import { authOptions } from './api/auth/[...nextauth]'
export default function Page() {
return null
@@ -8,7 +9,11 @@ export default function Page() {
export const getServerSideProps = getLocaleProps(
async (context: GetServerSidePropsContext) => {
const session = await getSession(context)
const session = await getServerSession(
context.req,
context.res,
authOptions
)
if (!session?.user) {
return {
redirect: {