chore: 给phone登陆改成sms登陆,并顺手实现sms登陆

This commit is contained in:
2025-12-17 23:23:14 +08:00
parent 0575f892ef
commit 4569d6e443
4 changed files with 110 additions and 72 deletions

View File

@@ -1,67 +0,0 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
import { useState, useCallback } from "react";
import { toast } from "sonner";
import LoginHeader from "./LoginHeader";
import { SendCodeFormData } from "./types";
import { Label } from "@/components/ui/label"
export default function PhoneLoginMode({ onSendCode }: { onSendCode: (data: SendCodeFormData) => Promise<boolean> }) {
const [phone, setPhone] = useState("");
const handleSendCode = useCallback(() => {
if (phone.trim().length !== 11) {
toast.error('请输入正确的手机号');
return;
}
onSendCode({
type: 'phone',
phone,
})
}, [phone, onSendCode]);
return (
<>
<LoginHeader />
<div className="grid gap-3">
<Label htmlFor="phone"></Label>
<Input
id="phone-login-mode-phone"
name="phone"
type="text"
placeholder="+86 手机号"
value={phone}
onChange={(e) => setPhone(e.target.value)}
required />
</div>
<div className="grid gap-3">
<div className="flex items-center h-4">
<Label htmlFor="code"></Label>
</div>
<div className="flex gap-5">
<InputOTP
id="phone-login-mode-code"
name="code"
maxLength={6}
pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
required
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
<Button type="button" variant="secondary" onClick={handleSendCode} disabled></Button>
</div>
</div>
<Button type="submit" className="w-full" disabled>
</Button>
</>
)
}

View File

@@ -0,0 +1,78 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
import { useState, useCallback } from "react";
import { toast } from "sonner";
import LoginHeader from "./LoginHeader";
import { Label } from "@/components/ui/label"
import { HumanVerification } from "@/components/human-verification";
import { AuthAPI, SmsAPI } from "@/lib/api/client";
import { handleAPIError } from "@/lib/api/common";
export default function SmsLoginMode() {
const [phone, setPhone] = useState("");
const handleSendCode = useCallback(async () => {
await SmsAPI.sendLoginSms(phone)
.then(() => toast.success('验证码已发送!'))
.catch(e => handleAPIError(e, ({ message }) => toast.error(`${message}`)))
}, [phone]);
return (
<>
<LoginHeader />
<div className="grid gap-3">
<Label htmlFor="phone"></Label>
<Input
id="phone-login-mode-phone"
name="phone"
type="text"
placeholder="+86 手机号"
value={phone}
onChange={(e) => setPhone(e.target.value)}
required />
</div>
<div className="grid gap-3">
<div className="flex items-center h-4">
<Label htmlFor="code"></Label>
</div>
<div className="flex gap-1 overflow-hidden items-center flex-row-reverse">
<HumanVerification onSuccess={handleSendCode} >
<Button type="button" variant="secondary">
</Button>
</HumanVerification>
<div className="flex-1 min-w-0">
<InputOTP
id="phone-login-mode-code"
name="code"
maxLength={6}
pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
required
>
<InputOTPGroup className="w-full flex justify-between">
{[...Array(6)].map((_, i) => (
<InputOTPSlot
key={i}
index={i}
className="flex-1 aspect-square"
/>
))}
</InputOTPGroup>
</InputOTP>
</div>
</div>
</div>
<Button type="submit" className="w-full" >
</Button>
</>
)
}
export async function handleSubmit(formData: FormData) {
const phone = formData.get('phone')?.toString() || '';
const code = formData.get('code')?.toString() || '';
return AuthAPI.loginBySms(phone, code)
}

View File

@@ -9,14 +9,14 @@ import { cn } from "@/lib/utils";
import { KeyRound, Phone, FileKey2 } from "lucide-react"; import { KeyRound, Phone, FileKey2 } from "lucide-react";
import EmailLoginMode from "./components/EmailLoginMode"; import EmailLoginMode from "./components/EmailLoginMode";
import PasswordLoginMode from "./components/PasswordLoginMode"; import PasswordLoginMode from "./components/PasswordLoginMode";
import PhoneLoginMode from "./components/PhoneLoginMode"; import PhoneLoginMode from "./components/SmsLoginMode";
import { useState } from "react"; import { useState } from "react";
import LoginBG from './components/login-bg.jpg'; import LoginBG from './components/login-bg.jpg';
import Image from "next/image"; import Image from "next/image";
import { handleAPIError } from "@/lib/api/common"; import { handleAPIError } from "@/lib/api/common";
import { useUserStore } from "@/store/useUserStore"; import { useUserStore } from "@/store/useUserStore";
export type SubmitMode = 'password' | 'phone' | 'passkey'; export type SubmitMode = 'password' | 'sms' | 'passkey';
export default function Login() { export default function Login() {
const router = useRouter(); const router = useRouter();
@@ -37,6 +37,8 @@ export default function Login() {
let handler = (await (async () => { let handler = (await (async () => {
if (loginMode === 'password') { if (loginMode === 'password') {
return import('./components/PasswordLoginMode'); return import('./components/PasswordLoginMode');
} else if (loginMode === 'sms') {
return import('./components/SmsLoginMode');
} }
})())?.handleSubmit; })())?.handleSubmit;
if (!handler) { if (!handler) {
@@ -54,7 +56,7 @@ export default function Login() {
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-6">
{loginMode === 'password' ? <PasswordLoginMode /> : null} {loginMode === 'password' ? <PasswordLoginMode /> : null}
{/* {loginMode === 'phone' ? <PhoneLoginMode onSendCode={handleSendCode} /> : null} */} {loginMode === 'sms' ? <PhoneLoginMode /> : null}
{/* {loginMode === 'email' ? <EmailLoginMode onSendCode={handleSendCode} /> : null} */} {/* {loginMode === 'email' ? <EmailLoginMode onSendCode={handleSendCode} /> : null} */}
<div className="after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t"> <div className="after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t">
@@ -64,7 +66,7 @@ export default function Login() {
</div> </div>
<div className="grid grid-cols-3 gap-4"> <div className="grid grid-cols-3 gap-4">
{ {
([['password', KeyRound], ['phone', Phone], ['passkey', FileKey2]] as const).map(([mode, Icon]) => ( ([['password', KeyRound], ['sms', Phone], ['passkey', FileKey2]] as const).map(([mode, Icon]) => (
<Button key={mode} variant={loginMode === mode ? 'default' : 'outline'} type="button" className="w-full" onClick={() => setLoginMode(mode)}> <Button key={mode} variant={loginMode === mode ? 'default' : 'outline'} type="button" className="w-full" onClick={() => setLoginMode(mode)}>
<Icon /> <Icon />
</Button> </Button>
@@ -74,7 +76,7 @@ export default function Login() {
<div className="text-center text-sm"> <div className="text-center text-sm">
{" "} {" "}
<a className="underline underline-offset-4 cursor-pointer" onClick={() => setLoginMode('phone')}> <a className="underline underline-offset-4 cursor-pointer" onClick={() => setLoginMode('sms')}>
</a> </a>
</div> </div>

View File

@@ -24,4 +24,29 @@ export async function loginByPassword(identifier: string, password: string) {
password, password,
}) })
}); });
}
export async function loginBySms(phone: string, code: string) {
phone = phone.trim();
code = code.trim();
if (phone.length === 0 || code.length === 0) {
throw new APIError('请输入手机号及短信验证码')
}
if (!/^1[3-9]\d{9}$/.test(phone)) {
throw new APIError('请输入合法的中国大陆手机号');
}
if (! /\d{6}/.test(code)) {
throw new APIError('密码长度只能为6~32位')
}
return clientFetch<{ user: User }>('/api/auth/login/sms', {
method: 'POST',
body: JSON.stringify({
phone,
code,
})
});
} }