Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(desktop):add cloudflare turnstile #4595

Merged
merged 1 commit into from Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 4 additions & 4 deletions frontend/desktop/package.json
Expand Up @@ -28,13 +28,14 @@
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@kubernetes/client-node": "^0.18.1",
"@marsidev/react-turnstile": "^0.5.3",
"@prisma/client": "^5.10.2",
"@sealos/driver": "workspace:^",
"@sealos/ui": "workspace:^",
"@tanstack/react-query": "^4.35.3",
"axios": "^1.5.1",
"clsx": "^1.2.1",
"cors": "^2.8.5",
"cors": "^2.8.5",
"dayjs": "^1.11.10",
"eslint": "8.38.0",
"eslint-config-next": "13.3.0",
Expand All @@ -53,6 +54,7 @@
"next-i18next": "^13.3.0",
"next-pwa": "^5.6.0",
"nprogress": "^0.2.0",
"prisma": "^5.10.2",
"qrcode.react": "^3.1.0",
"randexp": "^0.5.3",
"react": "18.2.0",
Expand All @@ -65,8 +67,7 @@
"sharp": "^0.32.6",
"uuid": "^9.0.1",
"xml2js": "^0.6.2",
"zustand": "^4.4.1",
"prisma": "^5.10.2"
"zustand": "^4.4.1"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.1.3",
Expand All @@ -86,7 +87,6 @@
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"prettier": "^2.8.8"

},
"pnpm": {
"supportedArchitectures": {
Expand Down
14 changes: 12 additions & 2 deletions frontend/desktop/src/components/signin/auth/useSms.tsx
Expand Up @@ -85,7 +85,13 @@ export default function useSms({
)();
};

const SmsModal = () => {
const SmsModal = ({
onAfterGetCode,
getCfToken
}: {
getCfToken?: () => string | undefined;
onAfterGetCode?: () => void;
}) => {
const [remainTime, setRemainTime] = useState(_remainTime.current);

useEffect(() => {
Expand All @@ -107,8 +113,10 @@ export default function useSms({
_remainTime.current = 60;

try {
const cfToken = getCfToken?.();
const res = await request.post<any, ApiResp<any>>('/api/auth/phone/sms', {
phoneNumbers: getValues('phoneNumber')
phoneNumbers: getValues('phoneNumber'),
cfToken
});
if (res.code !== 200 || res.message !== 'successfully') {
throw new Error('Get code failed');
Expand All @@ -117,6 +125,8 @@ export default function useSms({
showError(t('Get code failed') || 'Get code failed');
setRemainTime(0);
_remainTime.current = 0;
} finally {
onAfterGetCode?.();
}
};

Expand Down
38 changes: 33 additions & 5 deletions frontend/desktop/src/components/signin/index.tsx
Expand Up @@ -24,8 +24,9 @@ import { debounce } from 'lodash';
import { useTranslation } from 'next-i18next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import useWechat from './auth/useWechat';
import { Turnstile, TurnstileInstance } from '@marsidev/react-turnstile';

export default function SigninComponent() {
const { data: platformEnv } = useQuery(['getPlatformEnv'], getSystemEnv);
Expand All @@ -37,7 +38,8 @@ export default function SigninComponent() {
private_protocol_en = '',
needPassword = false,
needSms = false,
openWechatEnabled = false
openWechatEnabled = false,
cf_sitekey
} = platformEnv?.data || {};
const needTabs = needPassword && needSms;
const disclosure = useDisclosure();
Expand Down Expand Up @@ -80,12 +82,21 @@ export default function SigninComponent() {
setToken('');
}
}, []);

const turnstileRef = useRef<TurnstileInstance>(null);
const loginConfig = useMemo(() => {
return {
[LoginType.SMS]: {
login: smsSubmit,
component: <SmsModal />
component: (
<SmsModal
onAfterGetCode={() => {
turnstileRef.current?.reset();
}}
getCfToken={() => {
return turnstileRef.current?.getResponse();
}}
/>
)
},
[LoginType.PASSWORD]: {
login: passwordSubmit,
Expand All @@ -97,7 +108,15 @@ export default function SigninComponent() {
},
[LoginType.NONE]: null
};
}, [PasswordComponent, SmsModal, WechatComponent, passwordSubmit, smsSubmit, wechatSubmit]);
}, [
PasswordComponent,
SmsModal,
WechatComponent,
passwordSubmit,
smsSubmit,
wechatSubmit,
turnstileRef.current
]);

useEffect(() => {
setTabIndex(needSms ? LoginType.SMS : needPassword ? LoginType.PASSWORD : LoginType.NONE);
Expand Down Expand Up @@ -206,6 +225,15 @@ export default function SigninComponent() {
{tabIndex !== LoginType.WeChat && (
<>
<Protocol />
{!!cf_sitekey && (
<Turnstile
options={{
size: 'invisible'
}}
ref={turnstileRef}
siteKey={cf_sitekey}
/>
)}
<Button
variant={'unstyled'}
background="linear-gradient(90deg, #000000 0%, rgba(36, 40, 44, 0.9) 98.29%)"
Expand Down
27 changes: 25 additions & 2 deletions frontend/desktop/src/pages/api/auth/phone/sms.ts
Expand Up @@ -10,17 +10,40 @@ import { jsonRes } from '@/services/backend/response';
import { addOrUpdateCode, checkSendable } from '@/services/backend/db/verifyCode';
import { enableSms } from '@/services/enable';
import { retrySerially } from '@/utils/tools';

const accessKeyId = process.env.ALI_ACCESS_KEY_ID;
const accessKeySecret = process.env.ALI_ACCESS_KEY_SECRET;
const templateCode = process.env.ALI_TEMPLATE_CODE;
const signName = process.env.ALI_SIGN_NAME;

const verifyEndpoint = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
const secret = process.env.CF_SECRET_KEY;
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
if (!enableSms()) {
throw new Error('SMS is not enabled');
}
const { phoneNumbers } = req.body as { phoneNumbers?: string };
const { phoneNumbers, cfToken } = req.body as { phoneNumbers?: string; cfToken?: string };

if (secret) {
if (!cfToken)
return jsonRes(res, {
message: 'cfToken is invalid',
code: 400
});
const verifyRes = await fetch(verifyEndpoint, {
method: 'POST',
body: `secret=${encodeURIComponent(secret)}&response=${encodeURIComponent(cfToken)}`,
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
});
const data = await verifyRes.json();
if (!data.success)
return jsonRes(res, {
message: 'cfToken is invalid',
code: 400
});
}
if (!phoneNumbers)
return jsonRes(res, {
message: 'phoneNumbers is invalid',
Expand Down
5 changes: 3 additions & 2 deletions frontend/desktop/src/pages/api/platform/getEnv.ts
Expand Up @@ -23,6 +23,7 @@ export default async function handler(_: NextApiRequest, res: NextApiResponse) {
const private_protocol_en = process.env.PRIVATE_PROTOCOL_EN || '';
const oauth_proxy = process.env.OAUTH_PROXY || '';
const callback_url = process.env.CALLBACK_URL || '';
const cf_sitekey = process.env.CF_SITE_KEY || '';
const needGithub = enableGithub();
const needWechat = enableWechat();
const needPassword = enablePassword();
Expand All @@ -33,7 +34,6 @@ export default async function handler(_: NextApiRequest, res: NextApiResponse) {
const rechargeEnabled = enableRecharge();
const guideEnabled = process.env.GUIDE_ENABLED === 'true';
const openWechatEnabled = enableOpenWechat();

return jsonRes<SystemEnv>(res, {
data: {
SEALOS_CLOUD_DOMAIN: process.env.SEALOS_CLOUD_DOMAIN || 'cloud.sealos.io',
Expand All @@ -55,7 +55,8 @@ export default async function handler(_: NextApiRequest, res: NextApiResponse) {
rechargeEnabled,
licenseEnabled,
guideEnabled,
openWechatEnabled
openWechatEnabled,
cf_sitekey
}
});
}
1 change: 1 addition & 0 deletions frontend/desktop/src/stores/global.ts
Expand Up @@ -11,6 +11,7 @@ export const useGlobalStore = create<GlobalState>()(
persist(
immer((set) => ({
callback_url: '',
cf_sitekey: '',
service_protocol_en: '',
service_protocol_zh: '',
private_protocol_en: '',
Expand Down
1 change: 1 addition & 0 deletions frontend/desktop/src/types/system.ts
Expand Up @@ -19,6 +19,7 @@ export type LoginProps = {
github_client_id: string;
google_client_id: string;
callback_url: string;
cf_sitekey: string;
service_protocol_zh: string;
private_protocol_zh: string;
service_protocol_en: string;
Expand Down
54 changes: 53 additions & 1 deletion frontend/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.