Skip to content

Commit

Permalink
fix: use correct next-auth server-side api (#885)
Browse files Browse the repository at this point in the history
* fix: use correct next-auth server-side api
  • Loading branch information
vnugent authored Jun 23, 2023
1 parent 5a6cd72 commit 849f33a
Show file tree
Hide file tree
Showing 13 changed files with 49 additions and 28 deletions.
6 changes: 3 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
"type": "node-terminal",
"request": "launch",
"command": "npm run dev",
"env": {
"NEXT_PUBLIC_API_SERVER": "http://localhost:4000"
},
// "env": {
// "NEXT_PUBLIC_API_SERVER": "http://localhost:4000"
// },
},
{
"name": "Next.js: debug client-side",
Expand Down
7 changes: 5 additions & 2 deletions src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import NextAuth from 'next-auth'
import type { NextAuthOptions } from 'next-auth'
import Auth0Provider from 'next-auth/providers/auth0'

import { AUTH_CONFIG_SERVER } from '../../../Config'
Expand All @@ -15,7 +16,7 @@ if (process.env.NODE_ENV === 'production' && clientSecret.length === 0) {
throw new Error('AUTH0_CLIENT_SECRET is required in production')
}

export default NextAuth({
export const authOptions: NextAuthOptions = {
providers: [
Auth0Provider({
clientId,
Expand Down Expand Up @@ -69,4 +70,6 @@ export default NextAuth({
return session
}
}
})
}

export default NextAuth(authOptions)
10 changes: 8 additions & 2 deletions src/pages/api/basecamp/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { NextApiHandler } from 'next'
import { getSession } from 'next-auth/react'
import { getServerSession } from 'next-auth'

import withAuth from '../withAuth'
import { CreateUserData } from 'auth0'
import { customAlphabet } from 'nanoid'
import { nolookalikesSafe } from 'nanoid-dictionary'
import { UserRole } from '../../../js/types'

import { auth0ManagementClient } from '../../../js/auth/ManagementClient'
import { authOptions } from '../auth/[...nextauth]'

/**
* @deprecated This endpoint was created to migrate Auth0 passwordless accounts to
* email/password
*/
const handler: NextApiHandler<any> = async (req, res) => {
try {
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
if (session?.user.metadata?.roles?.includes(UserRole.USER_ADMIN) ?? false) {
const userId = req.query?.id as string
if (userId == null) throw new Error('Invalid user id')
Expand Down
6 changes: 4 additions & 2 deletions src/pages/api/basecamp/user.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
import { getSession } from 'next-auth/react'
import { getServerSession } from 'next-auth'

import withAuth from '../withAuth'
import { updateUser } from '../../../js/auth/ManagementClient'
import { UserRole } from '../../../js/types'
import { IUserMetadataOriginal } from '../../../js/types/User'
import { authOptions } from '../auth/[...nextauth]'

const handler: NextApiHandler<any> = async (req, res) => {
try {
Expand All @@ -29,7 +31,7 @@ const handler: NextApiHandler<any> = async (req, res) => {
* @returns
*/
async function handlePostRequest (req: NextApiRequest, res: NextApiResponse): Promise<void> {
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
if (session?.user.metadata?.roles?.includes(UserRole.USER_ADMIN) ?? false) {
res.setHeader('Cache-Control', 'no-store')
const userId = req.query?.userId
Expand Down
6 changes: 4 additions & 2 deletions src/pages/api/basecamp/userRoles.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
import { getSession } from 'next-auth/react'
import { getServerSession } from 'next-auth'

import withAuth from '../withAuth'
import { getUserRoles, setUserRoles } from '../../../js/auth/ManagementClient'
import { UserRole } from '../../../js/types'
import { authOptions } from '../auth/[...nextauth]'

const handler: NextApiHandler<any> = async (req, res) => {
try {
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
if (session?.user.metadata?.roles?.includes(UserRole.USER_ADMIN) ?? false) {
res.setHeader('Cache-Control', 'no-store')
const userId = req.query?.userId
Expand Down
6 changes: 4 additions & 2 deletions src/pages/api/basecamp/users.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { NextApiHandler } from 'next'
import { getSession } from 'next-auth/react'
import { getServerSession } from 'next-auth'

import withAuth from '../withAuth'
import { getAllUsersMetadata } from '../../../js/auth/ManagementClient'
import { UserRole } from '../../../js/types'
import { authOptions } from '../auth/[...nextauth]'

const handler: NextApiHandler<any> = async (req, res) => {
try {
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
if (session?.user.metadata?.roles?.includes(UserRole.USER_ADMIN) ?? false) {
res.setHeader('Cache-Control', 'no-store')
const page = req.query?.page ?? 1
Expand Down
5 changes: 3 additions & 2 deletions src/pages/api/media/get-signed-url.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { NextApiHandler } from 'next'
import { getSession } from 'next-auth/react'
import { customAlphabet } from 'nanoid'
import { nolookalikesSafe } from 'nanoid-dictionary'
import { extname } from 'path'
import { getServerSession } from 'next-auth'

import withAuth from '../withAuth'
import { s3Client, SIRV_CONFIG } from '../../../js/sirv/SirvClient'
import { authOptions } from '../auth/[...nextauth]'

export interface MediaPreSignedProps {
url: string
Expand All @@ -25,7 +26,7 @@ const handler: NextApiHandler<MediaPreSignedProps> = async (req, res) => {
if (Array.isArray(filename)) {
throw new Error('Expect only 1 filename param')
}
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
if (session?.user?.metadata?.uuid == null) {
throw new Error('Missing user metadata')
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/user/fav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function backToJSONSafe (collections: ReifiedFavouriteCollections): APIFavourite
*/
const handler: NextApiHandler<any> = async (req, res) => {
try {
const metadataClient = await createMetadataClient(req)
const metadataClient = await createMetadataClient(req, res)
if (metadataClient == null) throw new Error('Can\'t create ManagementAPI client')

/**
Expand Down
6 changes: 3 additions & 3 deletions src/pages/api/user/me.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { NextApiHandler } from 'next'
import { getSession } from 'next-auth/react'
import { getServerSession } from 'next-auth'
import { authOptions } from '../auth/[...nextauth]'

import withAuth from '../withAuth'
import useUserProfileCmd from '../../../js/hooks/useUserProfileCmd'

const handler: NextApiHandler<any> = async (req, res) => {
const session = await getSession({ req })

const session = await getServerSession(req, res, authOptions)
const uuid = session?.user.metadata.uuid

if (uuid == null) {
Expand Down
10 changes: 6 additions & 4 deletions src/pages/api/user/metadataClient.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { NextApiRequest } from 'next'
import { getSession } from 'next-auth/react'
import { NextApiRequest, NextApiResponse } from 'next'
import { getServerSession } from 'next-auth'

import { reshapeAuth0UserToProfile, extractUpdatableMetadataFromProfile, auth0ManagementClient } from '../../../js/auth/ManagementClient'
import { IUserProfile } from '../../../js/types/User'
import { authOptions } from '../auth/[...nextauth]'

const allowedFields = ['name', 'nick', 'bio', 'website', 'ticksImported', 'collections'] as const
type AllowedField = typeof allowedFields[number]
Expand Down Expand Up @@ -67,9 +68,10 @@ interface MetadataClient {
}

const createMetadataClient = async (
req: NextApiRequest
req: NextApiRequest,
res: NextApiResponse
): Promise<MetadataClient|null> => {
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
if (session == null) return null
const { id, accessToken } = session as unknown as {id: string, accessToken: string}

Expand Down
4 changes: 2 additions & 2 deletions src/pages/api/user/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { checkUsername, checkWebsiteUrl } from '../../../js/utils'
type Handler = NextApiHandler<Auth0UserMetadata | { message: string }>

const getProfile: Handler = async (req, res) => {
const metadataClient = await createMetadataClient(req)
const metadataClient = await createMetadataClient(req, res)
if (metadataClient == null) {
return res.status(401).end()
}
Expand All @@ -24,7 +24,7 @@ const getProfile: Handler = async (req, res) => {
}

const updateMyProfile: Handler = async (req, res) => {
const metadataClient = await createMetadataClient(req)
const metadataClient = await createMetadataClient(req, res)
if (metadataClient == null) {
return res.status(401).end()
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/user/ticks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async function getMPTicks (uid: string): Promise<MPTick[]> {

const handler: NextApiHandler<any> = async (req, res) => {
try {
const metadataClient = await createMetadataClient(req)
const metadataClient = await createMetadataClient(req, res)
if (metadataClient == null) throw new Error('Can\'t create ManagementAPI client')
const meta = await metadataClient.getUserMetadata()
if (req.method === 'GET') {
Expand Down
7 changes: 5 additions & 2 deletions src/pages/api/withAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
* Wrap an API Route to check that the user has a valid session.
* If the user is not logged in the handler will return a 401 Unauthorized.
*/
import { getSession } from 'next-auth/react'
import { NextApiHandler } from 'next'
import { getServerSession } from 'next-auth'
import { authOptions } from './auth/[...nextauth]'

const withAuth = (handler: NextApiHandler): NextApiHandler => {
return async (req, res) => {
const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)

console.log('#withAuth', session)
if (session != null) {
await handler(req, res)
} else {
Expand Down

1 comment on commit 849f33a

@vercel
Copy link

@vercel vercel bot commented on 849f33a Jun 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.