diff --git a/src/lib/authOptions.ts b/src/lib/authOptions.ts index 076dd95..f81b57e 100644 --- a/src/lib/authOptions.ts +++ b/src/lib/authOptions.ts @@ -1,6 +1,11 @@ import type { NextAuthOptions } from "next-auth"; import GithubProvider from "next-auth/providers/github"; +const allowedEmails = (process.env.ALLOWED_EMAILS ?? "") + .split(",") + .map((e) => e.trim().toLowerCase()) + .filter(Boolean); + export const authOptions: NextAuthOptions = { providers: [ GithubProvider({ @@ -13,6 +18,10 @@ export const authOptions: NextAuthOptions = { signIn: "/login", }, callbacks: { + async signIn({ user }) { + if (allowedEmails.length === 0) return true; + return allowedEmails.includes((user.email ?? "").toLowerCase()); + }, async session({ session, token }) { if (session.user && token.sub) { (session.user as { id?: string }).id = token.sub; diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 0000000..ce1269d --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,14 @@ +export { default } from "next-auth/middleware"; + +export const config = { + matcher: [ + /* + * 保护所有路由,以下除外: + * - /login 登录页 + * - /api/auth/* NextAuth 回调 + * - /_next/* Next.js 静态资源 + * - /favicon.ico + */ + "/((?!login|api/auth|_next/static|_next/image|favicon\\.ico).*)", + ], +};