fix: resolve OAuth redirect_uri error - Add URL validation and cleanup in auth config - Create environment variable check script - Add OAuth setup guide documentation
This commit is contained in:
29
lib/auth.ts
29
lib/auth.ts
@ -7,6 +7,32 @@ import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import { UserService } from "./services/user.service";
|
||||
import { AuthOptions } from "next-auth";
|
||||
|
||||
// 验证和清理 NEXTAUTH_URL
|
||||
function getValidatedNextAuthUrl(): string {
|
||||
const url = process.env.NEXTAUTH_URL;
|
||||
if (!url) {
|
||||
throw new Error("NEXTAUTH_URL 环境变量未设置");
|
||||
}
|
||||
|
||||
// 清理 URL,移除多余的引号
|
||||
let cleanUrl = url.trim();
|
||||
if (cleanUrl.startsWith('"') && cleanUrl.endsWith('"')) {
|
||||
cleanUrl = cleanUrl.slice(1, -1);
|
||||
}
|
||||
if (cleanUrl.startsWith("'") && cleanUrl.endsWith("'")) {
|
||||
cleanUrl = cleanUrl.slice(1, -1);
|
||||
}
|
||||
|
||||
// 确保 URL 格式正确
|
||||
try {
|
||||
new URL(cleanUrl);
|
||||
} catch (error) {
|
||||
throw new Error(`无效的 NEXTAUTH_URL: ${cleanUrl}`);
|
||||
}
|
||||
|
||||
return cleanUrl;
|
||||
}
|
||||
|
||||
export const authOptions: AuthOptions = {
|
||||
adapter: PrismaAdapter(prisma),
|
||||
|
||||
@ -94,4 +120,7 @@ export const authOptions: AuthOptions = {
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
|
||||
// 使用验证后的 URL
|
||||
url: getValidatedNextAuthUrl(),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user