feat: upgrade to latest next-auth

This commit is contained in:
shadcn 2022-11-07 16:37:47 +04:00
parent 7788df0b6b
commit 0f73a7509f
17 changed files with 194 additions and 165 deletions

View file

@ -1,8 +1,7 @@
import { headers } from "next/headers"
import { notFound } from "next/navigation"
import Link from "next/link"
import { getSession } from "@/lib/session"
import { getCurrentUser } from "@/lib/session"
import { DashboardNav } from "@/components/dashboard-nav"
import { UserAccountNav } from "@/components/user-account-nav"
import { Icons } from "@/components/icons"
@ -11,20 +10,10 @@ interface DashboardLayoutProps {
children?: React.ReactNode
}
async function getUser() {
const session = await getSession(headers().get("cookie"))
if (!session?.user) {
return null
}
return session.user
}
export default async function DashboardLayout({
children,
}: DashboardLayoutProps) {
const user = await getUser()
const user = await getCurrentUser()
if (!user) {
return notFound()

View file

@ -1,8 +1,9 @@
import { headers } from "next/headers"
import { User } from "@/lib/prisma"
import { redirect } from "next/navigation"
import { db } from "@/lib/db"
import { getSession } from "@/lib/session"
import { getCurrentUser } from "@/lib/session"
import { User } from "@/lib/prisma"
import { authOptions } from "@/lib/auth"
import { DashboardHeader } from "@/components/dashboard-header"
import { PostCreateButton } from "@/components/post-create-button"
import { DashboardShell } from "@/components/dashboard-shell"
@ -27,8 +28,13 @@ async function getPostsForUser(userId: User["id"]) {
}
export default async function DashboardPage() {
const session = await getSession(headers().get("cookie"))
const posts = await getPostsForUser(session?.user.id)
const user = await getCurrentUser()
if (!user) {
return redirect(authOptions.pages.signIn)
}
const posts = await getPostsForUser(user.id)
return (
<DashboardShell>

View file

@ -1,26 +1,16 @@
import { headers } from "next/headers"
import { notFound } from "next/navigation"
import { redirect } from "next/navigation"
import { getSession } from "@/lib/session"
import { getCurrentUser } from "@/lib/session"
import { authOptions } from "@/lib/auth"
import { DashboardHeader } from "@/components/dashboard-header"
import { DashboardShell } from "@/components/dashboard-shell"
import { UserNameForm } from "@/components/user-name-form"
async function getUser() {
const session = await getSession(headers().get("cookie"))
if (!session?.user) {
return null
}
return session.user
}
export default async function SettingsPage() {
const user = await getUser()
const user = await getCurrentUser()
if (!user) {
notFound()
return redirect(authOptions.pages.signIn)
}
return (

View file

@ -1,10 +1,10 @@
import { notFound } from "next/navigation"
import { headers } from "next/headers"
import { Post, User } from "@/lib/prisma"
import { notFound, redirect } from "next/navigation"
import { Editor } from "@/components/editor"
import { Post, User } from "@/lib/prisma"
import { db } from "@/lib/db"
import { getSession } from "@/lib/session"
import { getCurrentUser } from "@/lib/session"
import { authOptions } from "@/lib/auth"
import { Editor } from "@/components/editor"
async function getPostForUser(postId: Post["id"], userId: User["id"]) {
return await db.post.findFirst({
@ -20,8 +20,13 @@ interface EditorPageProps {
}
export default async function EditorPage({ params }: EditorPageProps) {
const session = await getSession(headers().get("cookie"))
const post = await getPostForUser(params.postId, session?.user.id)
const user = await getCurrentUser()
if (!user) {
return redirect(authOptions.pages.signIn)
}
const post = await getPostForUser(params.postId, user.id)
if (!post) {
notFound()

View file

@ -1,9 +1,11 @@
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
import { getSession } from "next-auth/react"
import { unstable_getServerSession } from "next-auth"
import { authOptions } from "@/lib/auth"
export function withAuthentication(handler: NextApiHandler) {
return async function (req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req })
const session = await unstable_getServerSession(req, res, authOptions)
if (!session) {
return res.status(403).end()

View file

@ -1,18 +1,20 @@
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
import { getSession } from "next-auth/react"
import { unstable_getServerSession } from "next-auth"
import * as z from "zod"
import { authOptions } from "@/lib/auth"
export const schema = z.object({
userId: z.string(),
})
export function withUser(handler: NextApiHandler) {
export function withCurrentUser(handler: NextApiHandler) {
return async function (req: NextApiRequest, res: NextApiResponse) {
try {
const query = await schema.parse(req.query)
// Check if the user has access to this user.
const session = await getSession({ req })
const session = await unstable_getServerSession(req, res, authOptions)
if (query.userId !== session?.user.id) {
return res.status(403).end()

View file

@ -1,7 +1,9 @@
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
import { getSession } from "next-auth/react"
import { unstable_getServerSession } from "next-auth"
import * as z from "zod"
import { db } from "../db"
import { authOptions } from "@/lib/auth"
import { db } from "@/lib/db"
export const schema = z.object({
postId: z.string(),
@ -13,7 +15,7 @@ export function withPost(handler: NextApiHandler) {
const query = await schema.parse(req.query)
// Check if the user has access to this post.
const session = await getSession({ req })
const session = await unstable_getServerSession(req, res, authOptions)
const count = await db.post.count({
where: {
id: query.postId,

110
lib/auth.ts Normal file
View file

@ -0,0 +1,110 @@
import { NextAuthOptions } from "next-auth"
import GitHubProvider from "next-auth/providers/github"
import EmailProvider from "next-auth/providers/email"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { Client } from "postmark"
import { PrismaClient } from "@/lib/prisma"
import { db } from "@/lib/db"
const postmarkClient = new Client(process.env.POSTMARK_API_TOKEN)
const POSTMARK_SIGN_IN_TEMPLATE = 29559329
const POSTMARK_ACTIVATION_TEMPLATE = 29559329
const prisma = new PrismaClient()
export const authOptions: NextAuthOptions = {
// huh any! I know.
// This is a temporary fix for prisma client.
// @see https://github.com/prisma/prisma/issues/16117
adapter: PrismaAdapter(prisma as any),
session: {
strategy: "jwt",
},
pages: {
signIn: "/login",
},
providers: [
GitHubProvider({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
EmailProvider({
server: {
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
from: process.env.SMTP_FROM,
sendVerificationRequest: async ({ identifier, url, provider }) => {
const user = await db.user.findUnique({
where: {
email: identifier,
},
select: {
emailVerified: true,
},
})
const result = await postmarkClient.sendEmailWithTemplate({
TemplateId: user?.emailVerified
? POSTMARK_SIGN_IN_TEMPLATE
: POSTMARK_ACTIVATION_TEMPLATE,
To: identifier,
From: provider.from,
TemplateModel: {
action_url: url,
product_name: "Taxonomy",
},
Headers: [
{
// Set this to prevent Gmail from threading emails.
// See https://stackoverflow.com/questions/23434110/force-emails-not-to-be-grouped-into-conversations/25435722.
Name: "X-Entity-Ref-ID",
Value: new Date().getTime() + "",
},
],
})
if (result.ErrorCode) {
throw new Error(result.Message)
}
},
}),
],
callbacks: {
async session({ token, session }) {
if (token) {
session.user.id = token.id
session.user.name = token.name
session.user.email = token.email
session.user.image = token.picture
}
return session
},
async jwt({ token, user }) {
const dbUser = await db.user.findFirst({
where: {
email: token.email,
},
})
if (!dbUser) {
token.id = user.id
return token
}
return {
id: dbUser.id,
name: dbUser.name,
email: dbUser.email,
picture: dbUser.image,
}
},
},
}

View file

@ -1,15 +1,13 @@
import { Session } from "next-auth"
import { unstable_getServerSession } from "next-auth"
export async function getSession(cookie: string): Promise<Session> {
const response = await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`, {
headers: { cookie },
})
import { authOptions } from "@/lib/auth"
if (!response?.ok) {
return null
}
const session = await response.json()
return Object.keys(session).length > 0 ? session : null
export async function getSession() {
return await unstable_getServerSession(authOptions)
}
export async function getCurrentUser() {
const session = await getSession()
return session?.user
}

View file

@ -1,25 +1,24 @@
import { NextResponse } from "next/server"
import { getToken } from "next-auth/jwt"
import { withAuth } from "next-auth/middleware"
import { getSession } from "@/lib/session"
import { NextResponse } from "next/server"
export default withAuth(
async function middleware(req) {
const session = await getSession(req.headers.get("cookie"))
const token = await getToken({ req })
const isAuth = !!token
const isAuthPage =
req.nextUrl.pathname.startsWith("/login") ||
req.nextUrl.pathname.startsWith("/register")
if (isAuthPage) {
if (session) {
if (isAuth) {
return NextResponse.redirect(new URL("/dashboard", req.url))
}
return null
}
if (!session) {
if (!isAuth) {
return NextResponse.redirect(new URL("/login", req.url))
}
},
@ -36,5 +35,5 @@ export default withAuth(
)
export const config = {
matcher: ["/dashboard/:path*", "/editor", "/login", "/register"],
matcher: ["/dashboard/:path*", "/editor/:path*", "/login", "/register"],
}

View file

@ -38,7 +38,7 @@
"hasha": "^5.2.2",
"lucide-react": "^0.92.0",
"next": "^13.0.3-canary.0",
"next-auth": "^4.15.0",
"next-auth": "^4.16.3",
"next-mdx-remote": "^4.1.0",
"node-cache": "^5.1.2",
"nodemailer": "^6.8.0",

View file

@ -1,83 +1,5 @@
import NextAuth, { NextAuthOptions } from "next-auth"
import GitHubProvider from "next-auth/providers/github"
import EmailProvider from "next-auth/providers/email"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { PrismaClient } from "@/lib/prisma"
import { Client } from "postmark"
import { db } from "@/lib/db"
const postmarkClient = new Client(process.env.POSTMARK_API_TOKEN)
const POSTMARK_SIGN_IN_TEMPLATE = 29559329
const POSTMARK_ACTIVATION_TEMPLATE = 29559329
const prisma = new PrismaClient()
export const authOptions: NextAuthOptions = {
// huh any! I know.
// This is a temporary fix for prisma client.
// @see https://github.com/prisma/prisma/issues/16117
adapter: PrismaAdapter(prisma as any),
pages: {
signIn: "/login",
},
providers: [
GitHubProvider({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
EmailProvider({
server: {
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
from: process.env.SMTP_FROM,
sendVerificationRequest: async ({ identifier, url, provider }) => {
const user = await db.user.findUnique({
where: {
email: identifier,
},
select: {
emailVerified: true,
},
})
const result = await postmarkClient.sendEmailWithTemplate({
TemplateId: user?.emailVerified
? POSTMARK_SIGN_IN_TEMPLATE
: POSTMARK_ACTIVATION_TEMPLATE,
To: identifier,
From: provider.from,
TemplateModel: {
action_url: url,
product_name: "Taxonomy",
},
Headers: [
{
// Set this to prevent Gmail from threading emails.
// See https://stackoverflow.com/questions/23434110/force-emails-not-to-be-grouped-into-conversations/25435722.
Name: "X-Entity-Ref-ID",
Value: new Date().getTime() + "",
},
],
})
if (result.ErrorCode) {
throw new Error(result.Message)
}
},
}),
],
callbacks: {
async session({ session, token, user }) {
session.user.id = user.id
return session
},
},
}
import NextAuth from "next-auth"
import { authOptions } from "@/lib/auth"
// @see ./lib/auth
export default NextAuth(authOptions)

View file

@ -1,7 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next"
import * as z from "zod"
import { withAuthentication } from "@/lib/api-middlewares/with-authentication"
import { withMethods } from "@/lib/api-middlewares/with-methods"
import { withPost } from "@/lib/api-middlewares/with-post"
import { db } from "@/lib/db"
@ -56,7 +55,4 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
}
export default withMethods(
["DELETE", "PATCH"],
withAuthentication(withPost(handler))
)
export default withMethods(["DELETE", "PATCH"], withPost(handler))

View file

@ -5,7 +5,6 @@ import * as z from "zod"
import { db } from "@/lib/db"
import { withMethods } from "@/lib/api-middlewares/with-methods"
import { withAuthentication } from "@/lib/api-middlewares/with-authentication"
import { withPost } from "@/lib/api-middlewares/with-post"
const postCreateSchema = z.object({
title: z.string().optional(),

View file

@ -2,10 +2,9 @@ import { NextApiRequest, NextApiResponse } from "next"
import * as z from "zod"
import { getSession } from "next-auth/react"
import { withAuthentication } from "@/lib/api-middlewares/with-authentication"
import { withMethods } from "@/lib/api-middlewares/with-methods"
import { db } from "@/lib/db"
import { withUser } from "@/lib/api-middlewares/with-user"
import { withMethods } from "@/lib/api-middlewares/with-methods"
import { withCurrentUser } from "@/lib/api-middlewares/with-current-user"
import { userNameSchema } from "@/lib/validations/user"
async function handler(req: NextApiRequest, res: NextApiResponse) {
@ -31,6 +30,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
return res.end()
} catch (error) {
console.log(error)
if (error instanceof z.ZodError) {
return res.status(422).json(error.issues)
}
@ -40,4 +40,4 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
}
export default withMethods(["PATCH"], withAuthentication(withUser(handler)))
export default withMethods(["PATCH"], withCurrentUser(handler))

11
types/next-auth.d.ts vendored
View file

@ -1,9 +1,18 @@
import { User } from "next-auth"
import { JWT } from "next-auth/jwt"
type UserId = string
declare module "next-auth/jwt" {
interface JWT {
id: UserId
}
}
declare module "next-auth" {
interface Session {
user: User & {
id: string
id: UserId
}
}
}

View file

@ -2731,10 +2731,10 @@ natural-compare@^1.4.0:
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==
next-auth@^4.15.0:
version "4.15.0"
resolved "https://registry.yarnpkg.com/next-auth/-/next-auth-4.15.0.tgz#1e350258b240cff7e09e81f066e26ad8fe540c85"
integrity sha512-IasNzGLM2VlmyioDdZaRwBBBm8b5xo+zbbqVWHFh0bY6iQUZ3vuudrsdHNdxkXV3LSHdKNaoWEpYr4BydB7mCw==
next-auth@^4.16.3:
version "4.16.3"
resolved "https://registry.yarnpkg.com/next-auth/-/next-auth-4.16.3.tgz#896ddeebb16c42899f916722be11acb99ec969fa"
integrity sha512-xDQHQJRpB/pjBDj53r4Br03jvhM1TI73J9OCX0afBTOHZEfpQ6ZrjsBFdSrdx6NeQSEMq6R/ZRny2Y6Nt/XqrA==
dependencies:
"@babel/runtime" "^7.16.3"
"@panva/hkdf" "^1.0.1"