chore: update Captcha component

This commit is contained in:
javayhu 2025-07-18 20:37:59 +08:00
parent cb7743fe07
commit 2c4db1e744
2 changed files with 20 additions and 10 deletions

View File

@ -54,7 +54,9 @@ export const RegisterForm = ({
// turnstile captcha schema
const turnstileEnabled = websiteConfig.features.enableTurnstileCaptcha;
const captchaSchema = turnstileEnabled
const captchaSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;
const captchaConfigured = turnstileEnabled && !!captchaSiteKey;
const captchaSchema = captchaConfigured
? z.string().min(1, 'Please complete the captcha')
: z.string().optional();
@ -87,8 +89,8 @@ export const RegisterForm = ({
});
const onSubmit = async (values: z.infer<typeof RegisterSchema>) => {
// Validate captcha token if turnstile is enabled
if (turnstileEnabled && values.captchaToken) {
// Validate captcha token if turnstile is enabled and site key is available
if (captchaConfigured && values.captchaToken) {
const captchaResult = await validateCaptchaAction({
captchaToken: values.captchaToken,
});
@ -229,14 +231,14 @@ export const RegisterForm = ({
</div>
<FormError message={error} />
<FormSuccess message={success} />
{turnstileEnabled && (
{captchaConfigured && (
<Captcha
onSuccess={(token) => form.setValue('captchaToken', token)}
validationError={form.formState.errors.captchaToken?.message}
/>
)}
<Button
disabled={isPending || (turnstileEnabled && !captchaToken)}
disabled={isPending || (captchaConfigured && !captchaToken)}
size="lg"
type="submit"
className="cursor-pointer w-full flex items-center justify-center gap-2"

View File

@ -23,15 +23,23 @@ type Props = Omit<ComponentProps<typeof Turnstile>, 'siteKey'> & {
*/
export const Captcha = ({ validationError, ...props }: Props) => {
const turnstileEnabled = websiteConfig.features.enableTurnstileCaptcha;
if (!turnstileEnabled || !process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY) {
console.error('Captcha, NEXT_PUBLIC_TURNSTILE_SITE_KEY is not set');
const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;
// If turnstile is disabled in config, don't render anything
if (!turnstileEnabled) {
return null;
}
// If turnstile is enabled but site key is missing, show error message
if (!siteKey) {
console.error('Captcha: NEXT_PUBLIC_TURNSTILE_SITE_KEY is not set');
return null;
}
const theme = useTheme();
const locale = useLocale();
return turnstileEnabled ? (
return (
<>
<Turnstile
options={{
@ -40,7 +48,7 @@ export const Captcha = ({ validationError, ...props }: Props) => {
theme: theme.theme === 'dark' ? 'dark' : 'light',
}}
{...props}
siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || ''}
siteKey={siteKey}
/>
{validationError && (
@ -49,5 +57,5 @@ export const Captcha = ({ validationError, ...props }: Props) => {
</FormMessage>
)}
</>
) : null;
);
};