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:
theshy
2025-08-01 20:14:23 +08:00
parent 8940101f8d
commit da41306918
4 changed files with 211 additions and 1 deletions

View File

@ -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(),
};