谷歌登录按钮用code是sso_config调用find_by_code配置

This commit is contained in:
qikongjian 2025-09-22 13:22:38 +08:00
parent 583f800ab0
commit 2b010a5a44
4 changed files with 255 additions and 30 deletions

View File

@ -0,0 +1,94 @@
/**
* Server Setting API路由
* code获取服务端配置
*/
import { NextRequest, NextResponse } from 'next/server';
/**
* code获取服务端配置
* POST /api/server-setting/find_by_code
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { code } = body;
console.log('📋 获取服务端配置请求:', { code });
if (!code) {
return NextResponse.json({
code: 400,
successful: false,
message: 'code parameter is required',
data: null
}, { status: 400 });
}
// 根据code返回不同的配置匹配实际API格式
let responseData = null;
switch (code) {
case 'sso_config':
// SSO配置 - 控制Google登录按钮显示
responseData = {
id: 8,
code: 'sso_config',
value: '{\n "show": true\n}',
note: 'sso 入口',
updated_at: new Date().toISOString().slice(0, 19)
};
break;
case 'home_tabs':
// 首页标签配置示例
responseData = {
id: 1,
code: 'home_tabs',
value: JSON.stringify([
{
id: '1',
title: '推荐',
subtitle: '为您推荐',
status: 1,
sortOrder: 1,
videos: []
}
], null, 2),
note: '首页标签配置',
updated_at: new Date().toISOString().slice(0, 19)
};
break;
default:
// 默认返回空配置
responseData = {
id: 0,
code: code,
value: '{}',
note: '默认配置',
updated_at: new Date().toISOString().slice(0, 19)
};
break;
}
const response = {
code: 0,
successful: true,
message: 'Success',
data: responseData
};
console.log('✅ 服务端配置获取成功:', { code, hasData: !!responseData });
return NextResponse.json(response);
} catch (error) {
console.error('❌ 获取服务端配置失败:', error);
return NextResponse.json({
code: 500,
successful: false,
message: 'Internal server error',
data: null
}, { status: 500 });
}
}

View File

@ -7,6 +7,7 @@ import { signInWithGoogle, sendVerificationLink, registerUserWithInvite } from "
import { GradientText } from "@/components/ui/gradient-text";
import { GoogleLoginButton } from "@/components/ui/google-login-button";
import { Eye, EyeOff, Mail } from "lucide-react";
import { isGoogleLoginEnabled } from "@/lib/server-config";
export default function SignupPage() {
const [name, setName] = useState("");
@ -26,9 +27,10 @@ export default function SignupPage() {
const [googleLoading, setGoogleLoading] = useState(false);
const [emailFocused, setEmailFocused] = useState(false);
const [passwordFocused, setPasswordFocused] = useState(false);
const [showGoogleLogin, setShowGoogleLogin] = useState(false);
const router = useRouter();
// Handle scroll indicator for small screens
// Handle scroll indicator for small screens and load SSO config
React.useEffect(() => {
try {
const url = new URL(window.location.href);
@ -40,6 +42,20 @@ export default function SignupPage() {
sessionStorage.setItem("inviteCode", code);
}
} catch (err) {}
// 检查是否启用Google登录
const checkGoogleLoginStatus = async () => {
try {
const enabled = await isGoogleLoginEnabled();
setShowGoogleLogin(enabled);
} catch (error) {
console.error("Failed to check Google login status:", error);
setShowGoogleLogin(false);
}
};
checkGoogleLoginStatus();
const handleScroll = () => {
const scrollableElement = document.querySelector('.signup-form > div:nth-child(2)');
const formElement = document.querySelector('.signup-form');
@ -493,21 +509,25 @@ export default function SignupPage() {
{/* Fixed Footer */}
<div className="flex-shrink-0 p-6 pt-4">
{/* 谷歌登录按钮已暂时注释 */}
<div className="mb-4 relative flex items-center">
<div className="flex-grow border-t border-gray-500/30"></div>
<span className="flex-shrink mx-4 text-gray-400">or</span>
<div className="flex-grow border-t border-gray-500/30"></div>
</div>
{/* Google登录按钮 - 根据服务端配置显示/隐藏 */}
{showGoogleLogin && (
<>
<div className="mb-4 relative flex items-center">
<div className="flex-grow border-t border-gray-500/30"></div>
<span className="flex-shrink mx-4 text-gray-400">or</span>
<div className="flex-grow border-t border-gray-500/30"></div>
</div>
<GoogleLoginButton
onClick={handleGoogleSignIn}
loading={googleLoading}
disabled={isSubmitting}
variant="outline"
size="md"
className="w-full"
/>
<GoogleLoginButton
onClick={handleGoogleSignIn}
loading={googleLoading}
disabled={isSubmitting}
variant="outline"
size="md"
className="w-full"
/>
</>
)}
<div className="text-center mt-4">
<p style={{ color: "rgba(255, 255, 255, 0.6)" }}>

View File

@ -9,6 +9,7 @@ import { signInWithGoogle, loginUser } from "@/lib/auth";
import { GradientText } from "@/components/ui/gradient-text";
import { GoogleLoginButton } from "@/components/ui/google-login-button";
import { Eye, EyeOff } from "lucide-react";
import { isGoogleLoginEnabled } from "@/lib/server-config";
export default function Login() {
const [email, setEmail] = useState("");
@ -21,6 +22,7 @@ export default function Login() {
const [googleLoading, setGoogleLoading] = useState(false);
const [emailFocused, setEmailFocused] = useState(false);
const [passwordFocused, setPasswordFocused] = useState(false);
const [showGoogleLogin, setShowGoogleLogin] = useState(false);
const router = useRouter();
const searchParams = useSearchParams();
@ -56,7 +58,7 @@ export default function Login() {
}
};
// Check for registered=true parameter
// Check for registered=true parameter and load SSO config
useEffect(() => {
const registered = searchParams?.get("registered");
if (registered === "true") {
@ -77,6 +79,22 @@ export default function Login() {
setFormError("The old OAuth method is deprecated. Please use the Google login button below for a better experience.");
}
}
// 检查是否启用Google登录
const checkGoogleLoginStatus = async () => {
try {
console.log('🔍 登录页面开始检查Google登录状态...');
const enabled = await isGoogleLoginEnabled();
console.log('📋 登录页面Google登录启用状态:', enabled);
setShowGoogleLogin(enabled);
console.log('📋 登录页面设置showGoogleLogin状态为:', enabled);
} catch (error) {
console.error("❌ 登录页面Failed to check Google login status:", error);
setShowGoogleLogin(false);
}
};
checkGoogleLoginStatus();
}, [searchParams]);
const handleGoogleSignIn = async () => {
@ -262,21 +280,26 @@ export default function Login() {
>
{isSubmitting ? "Logging in..." : "Login"}
</button>
{/* 谷歌登录按钮已暂时注释 */}
<div className="my-4 relative flex items-center">
<div className="flex-grow border-t border-gray-500/30"></div>
<span className="flex-shrink mx-4 text-gray-400">or</span>
<div className="flex-grow border-t border-gray-500/30"></div>
</div>
{/* Google登录按钮 - 根据服务端配置显示/隐藏 */}
{showGoogleLogin && (
<>
<div className="my-4 relative flex items-center">
<div className="flex-grow border-t border-gray-500/30"></div>
<span className="flex-shrink mx-4 text-gray-400">or</span>
<div className="flex-grow border-t border-gray-500/30"></div>
</div>
<GoogleLoginButton
onClick={handleGoogleSignIn}
loading={googleLoading}
disabled={isSubmitting}
variant="outline"
size="md"
className="w-full"
/>
<GoogleLoginButton
onClick={handleGoogleSignIn}
loading={googleLoading}
disabled={isSubmitting}
variant="outline"
size="md"
className="w-full"
/>
</>
)}
<div className="text-center mt-4">
<p style={{ color: "rgba(255, 255, 255, 0.6)" }}>

88
lib/server-config.ts Normal file
View File

@ -0,0 +1,88 @@
/**
*
*/
import { post } from '@/api/request';
/**
* SSO配置接口
*/
export interface SSOConfig {
show: boolean;
provider: string;
displayName: string;
description: string;
}
/**
* SSO配置
* @returns Promise<SSOConfig | null>
*/
export const getSSOConfig = async (): Promise<SSOConfig | null> => {
try {
console.log('🔍 开始获取SSO配置...');
const res = await post<any>(`/api/server-setting/find_by_code`, { code: 'sso_config' });
console.log('📋 SSO API响应:', res);
if (!res || res.code !== 0 || !res.successful || !res.data) {
console.warn('❌ Failed to fetch SSO config:', res);
return null;
}
// 新的数据格式data直接包含id, code, value等字段
const { value } = res.data;
console.log('📝 SSO配置原始value:', value);
console.log('📝 value类型:', typeof value, 'value长度:', value?.length);
if (typeof value !== 'string' || value.length === 0) {
console.warn('❌ Invalid SSO config format:', value);
return null;
}
try {
const config: SSOConfig = JSON.parse(value);
console.log('✅ SSO配置解析成功:', config);
return config;
} catch (parseError) {
console.error('❌ Failed to parse SSO config:', parseError);
console.error('❌ 原始value:', JSON.stringify(value));
return null;
}
} catch (error) {
console.error('❌ Error fetching SSO config:', error);
return null;
}
};
/**
* Google登录
* @returns Promise<boolean>
*/
export const isGoogleLoginEnabled = async (): Promise<boolean> => {
try {
console.log('🔍 检查Google登录是否启用...');
const config = await getSSOConfig();
console.log('📋 获得的配置:', config);
if (!config) {
console.log('❌ 没有获得配置返回false');
return false;
}
const isEnabled = config?.show === true;
console.log('🔍 配置检查:', {
show: config?.show,
provider: config?.provider,
isEnabled,
finalResult: isEnabled
});
// 简化逻辑只检查show字段因为sso_config专门用于Google登录
return isEnabled;
} catch (error) {
console.error('❌ Error checking Google login status:', error);
return false; // 出错时默认不显示
}
};