mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-08 08:36:37 +08:00
邮箱注册要求
This commit is contained in:
@@ -10,10 +10,12 @@ import Link from "next/link"
|
|||||||
import {useAuth} from "@/components/providers/auth-provider"
|
import {useAuth} from "@/components/providers/auth-provider"
|
||||||
import {Button} from "@/components/ui/button"
|
import {Button} from "@/components/ui/button"
|
||||||
import {Input} from "@/components/ui/input"
|
import {Input} from "@/components/ui/input"
|
||||||
|
import {Label} from "@/components/ui/label"
|
||||||
import {Separator} from "@/components/ui/separator"
|
import {Separator} from "@/components/ui/separator"
|
||||||
import {Spinner} from "@/components/ui/spinner"
|
import {Spinner} from "@/components/ui/spinner"
|
||||||
import {Card, CardContent} from "@/components/ui/card"
|
import {Card, CardContent} from "@/components/ui/card"
|
||||||
import {CapWidget} from "@/components/auth/cap-widget"
|
import {CapWidget} from "@/components/auth/cap-widget"
|
||||||
|
import {OTPForm} from "./otp-form"
|
||||||
import services from "@/lib/services"
|
import services from "@/lib/services"
|
||||||
import type {LoginRequest} from "@/lib/services/auth/types"
|
import type {LoginRequest} from "@/lib/services/auth/types"
|
||||||
|
|
||||||
@@ -49,9 +51,9 @@ export function LoginForm() {
|
|||||||
const [password, setPassword] = useState("")
|
const [password, setPassword] = useState("")
|
||||||
const [code, setCode] = useState("")
|
const [code, setCode] = useState("")
|
||||||
const [showLoginCodeInput, setShowLoginCodeInput] = useState(false)
|
const [showLoginCodeInput, setShowLoginCodeInput] = useState(false)
|
||||||
const [maskedEmail, setMaskedEmail] = useState("")
|
|
||||||
const [loginCooldown, setLoginCooldown] = useState(0)
|
const [loginCooldown, setLoginCooldown] = useState(0)
|
||||||
const [errorMessage, setErrorMessage] = useState("")
|
const [errorMessage, setErrorMessage] = useState("")
|
||||||
|
const [loginCodeTip, setLoginCodeTip] = useState<React.ReactNode>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loginCooldown > 0) {
|
if (loginCooldown > 0) {
|
||||||
@@ -105,7 +107,11 @@ export function LoginForm() {
|
|||||||
const errorMsg = error.message || ""
|
const errorMsg = error.message || ""
|
||||||
if (errorMsg.startsWith("need_email_code:")) {
|
if (errorMsg.startsWith("need_email_code:")) {
|
||||||
const emailMasked = errorMsg.substring("need_email_code:".length)
|
const emailMasked = errorMsg.substring("need_email_code:".length)
|
||||||
setMaskedEmail(emailMasked)
|
setLoginCodeTip(
|
||||||
|
<>
|
||||||
|
已向您的安全邮箱 <span className="font-medium text-foreground">{emailMasked}</span> 发送了登录验证码。
|
||||||
|
</>
|
||||||
|
)
|
||||||
setShowLoginCodeInput(true)
|
setShowLoginCodeInput(true)
|
||||||
setLoginCooldown(60)
|
setLoginCooldown(60)
|
||||||
toast.success("登录验证码已发送至您的邮箱,请注意查收")
|
toast.success("登录验证码已发送至您的邮箱,请注意查收")
|
||||||
@@ -117,6 +123,22 @@ export function LoginForm() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (errorMsg.startsWith("smtp_invalid:")) {
|
||||||
|
const tip = errorMsg.substring("smtp_invalid:".length)
|
||||||
|
setLoginCodeTip(
|
||||||
|
<span className="text-amber-500 font-medium">{tip}</span>
|
||||||
|
)
|
||||||
|
setShowLoginCodeInput(true)
|
||||||
|
setLoginCooldown(0)
|
||||||
|
toast.warning(tip)
|
||||||
|
if (capEnabled) {
|
||||||
|
capTokenRef.current = null
|
||||||
|
setCapReady(false)
|
||||||
|
setCapResetKey((key) => key + 1)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
setErrorMessage(errorMsg || "登录失败,请重试")
|
setErrorMessage(errorMsg || "登录失败,请重试")
|
||||||
if (capEnabled) {
|
if (capEnabled) {
|
||||||
capTokenRef.current = null
|
capTokenRef.current = null
|
||||||
@@ -130,8 +152,8 @@ export function LoginForm() {
|
|||||||
setErrorMessage("")
|
setErrorMessage("")
|
||||||
const trimmedUsername = username.trim()
|
const trimmedUsername = username.trim()
|
||||||
if (!trimmedUsername || !password) {
|
if (!trimmedUsername || !password) {
|
||||||
toast.error("账号或密码未填写完整", {
|
toast.error("邮箱/用户名或密码未填写完整", {
|
||||||
description: "请先输入账号 and 密码后再登录",
|
description: "请先输入邮箱/用户名和密码后再登录",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -203,6 +225,20 @@ export function LoginForm() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (showLoginCodeInput) {
|
||||||
|
return (
|
||||||
|
<OTPForm
|
||||||
|
code={code}
|
||||||
|
setCode={setCode}
|
||||||
|
loginCodeTip={loginCodeTip}
|
||||||
|
loginCooldown={loginCooldown}
|
||||||
|
isPending={loginMutation.isPending}
|
||||||
|
onResend={handleResendLoginCode}
|
||||||
|
onSubmit={handlePasswordLogin}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full border-border/60 bg-background/80 shadow-2xl backdrop-blur">
|
<Card className="w-full border-border/60 bg-background/80 shadow-2xl backdrop-blur">
|
||||||
<CardContent className="space-y-5 p-5 sm:p-6">
|
<CardContent className="space-y-5 p-5 sm:p-6">
|
||||||
@@ -214,49 +250,31 @@ export function LoginForm() {
|
|||||||
|
|
||||||
<div className="space-y-4 pt-2">
|
<div className="space-y-4 pt-2">
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="space-y-2">
|
<div className="space-y-3">
|
||||||
<Input
|
<div className="space-y-1.5">
|
||||||
value={username}
|
<Label htmlFor="username">邮箱/用户名</Label>
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
<Input
|
||||||
placeholder="用户名"
|
id="username"
|
||||||
autoComplete="username"
|
value={username}
|
||||||
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
/>
|
placeholder="请输入邮箱或用户名"
|
||||||
<Input
|
autoComplete="username"
|
||||||
value={password}
|
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
/>
|
||||||
type="password"
|
</div>
|
||||||
placeholder="密码"
|
<div className="space-y-1.5">
|
||||||
autoComplete="current-password"
|
<Label htmlFor="password">密码</Label>
|
||||||
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
<Input
|
||||||
/>
|
id="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
type="password"
|
||||||
|
placeholder="请输入密码"
|
||||||
|
autoComplete="current-password"
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{showLoginCodeInput && (
|
|
||||||
<div className="space-y-1.5 pt-1">
|
|
||||||
<p className="text-[11px] text-muted-foreground leading-normal">
|
|
||||||
已向您的安全邮箱 <span className="font-medium text-foreground">{maskedEmail}</span> 发送了登录验证码。
|
|
||||||
</p>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Input
|
|
||||||
value={code}
|
|
||||||
onChange={(e) => setCode(e.target.value)}
|
|
||||||
placeholder="6 位邮箱验证码"
|
|
||||||
maxLength={6}
|
|
||||||
className="flex-1"
|
|
||||||
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={handleResendLoginCode}
|
|
||||||
disabled={loginCooldown > 0 || loginMutation.isPending}
|
|
||||||
className="w-[120px] text-xs"
|
|
||||||
>
|
|
||||||
{loginCooldown > 0 ? `${loginCooldown}秒后重发` : "重新发送"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Cap 人机验证 */}
|
{/* Cap 人机验证 */}
|
||||||
@@ -320,7 +338,7 @@ export function LoginForm() {
|
|||||||
|
|
||||||
{registrationEnabled && (
|
{registrationEnabled && (
|
||||||
<div className="text-center text-xs text-muted-foreground mt-4">
|
<div className="text-center text-xs text-muted-foreground mt-4">
|
||||||
Don't have an account?{" "}
|
{"Don't have an account?"}{" "}
|
||||||
<Link href="/register" className="font-semibold text-indigo-500 hover:text-indigo-600 transition-colors">
|
<Link href="/register" className="font-semibold text-indigo-500 hover:text-indigo-600 transition-colors">
|
||||||
Sign up
|
Sign up
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import {RefreshCwIcon} from "lucide-react"
|
||||||
|
|
||||||
|
import {Button} from "@/components/ui/button"
|
||||||
|
import {Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle,} from "@/components/ui/card"
|
||||||
|
import {Field, FieldLabel} from "@/components/ui/field"
|
||||||
|
import {InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot,} from "@/components/ui/input-otp"
|
||||||
|
import {cn} from "@/lib/utils"
|
||||||
|
|
||||||
|
interface OTPFormProps {
|
||||||
|
code: string
|
||||||
|
setCode: (val: string) => void
|
||||||
|
loginCodeTip: React.ReactNode
|
||||||
|
loginCooldown: number
|
||||||
|
isPending: boolean
|
||||||
|
onResend: () => void
|
||||||
|
onSubmit: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function OTPForm({
|
||||||
|
code,
|
||||||
|
setCode,
|
||||||
|
loginCodeTip,
|
||||||
|
loginCooldown,
|
||||||
|
isPending,
|
||||||
|
onResend,
|
||||||
|
onSubmit,
|
||||||
|
}: OTPFormProps) {
|
||||||
|
return (
|
||||||
|
<Card className="w-full border-border/60 bg-background/80 shadow-2xl backdrop-blur">
|
||||||
|
<CardHeader className="space-y-1.5 p-5 sm:p-6 pb-2 text-center">
|
||||||
|
<CardTitle className="text-xl font-semibold tracking-tight text-foreground">
|
||||||
|
验证登录
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-sm text-muted-foreground leading-normal">
|
||||||
|
{loginCodeTip}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-5 p-5 sm:p-6 pt-2">
|
||||||
|
<Field className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<FieldLabel htmlFor="otp-verification" className="text-sm font-medium">
|
||||||
|
验证码
|
||||||
|
</FieldLabel>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
type="button"
|
||||||
|
onClick={onResend}
|
||||||
|
disabled={loginCooldown > 0 || isPending}
|
||||||
|
className="gap-1 text-xs px-2 py-1 h-7"
|
||||||
|
>
|
||||||
|
<RefreshCwIcon className={cn("size-3", isPending && "animate-spin")} />
|
||||||
|
{loginCooldown > 0 ? `${loginCooldown}秒后重发` : "重新发送"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<InputOTP
|
||||||
|
maxLength={6}
|
||||||
|
id="otp-verification"
|
||||||
|
required
|
||||||
|
value={code}
|
||||||
|
onChange={setCode}
|
||||||
|
onComplete={onSubmit}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
<InputOTPGroup className="*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl">
|
||||||
|
<InputOTPSlot index={0} />
|
||||||
|
<InputOTPSlot index={1} />
|
||||||
|
<InputOTPSlot index={2} />
|
||||||
|
</InputOTPGroup>
|
||||||
|
<InputOTPSeparator className="mx-2" />
|
||||||
|
<InputOTPGroup className="*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl">
|
||||||
|
<InputOTPSlot index={3} />
|
||||||
|
<InputOTPSlot index={4} />
|
||||||
|
<InputOTPSlot index={5} />
|
||||||
|
</InputOTPGroup>
|
||||||
|
</InputOTP>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
</CardContent>
|
||||||
|
<CardFooter className="flex-col gap-4 p-5 sm:p-6 pt-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="w-full"
|
||||||
|
onClick={onSubmit}
|
||||||
|
disabled={isPending || code.length < 6}
|
||||||
|
>
|
||||||
|
{isPending ? "验证中..." : "验证"}
|
||||||
|
</Button>
|
||||||
|
<div className="text-xs text-muted-foreground text-center">
|
||||||
|
遇到登录问题?{" "}
|
||||||
|
<a
|
||||||
|
href="#"
|
||||||
|
className="underline underline-offset-4 transition-colors hover:text-primary"
|
||||||
|
>
|
||||||
|
联系客服
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import Link from "next/link"
|
|||||||
import {useAuth} from "@/components/providers/auth-provider"
|
import {useAuth} from "@/components/providers/auth-provider"
|
||||||
import {Button} from "@/components/ui/button"
|
import {Button} from "@/components/ui/button"
|
||||||
import {Input} from "@/components/ui/input"
|
import {Input} from "@/components/ui/input"
|
||||||
|
import {Label} from "@/components/ui/label"
|
||||||
import {Spinner} from "@/components/ui/spinner"
|
import {Spinner} from "@/components/ui/spinner"
|
||||||
import {Card, CardContent} from "@/components/ui/card"
|
import {Card, CardContent} from "@/components/ui/card"
|
||||||
import services from "@/lib/services"
|
import services from "@/lib/services"
|
||||||
@@ -116,17 +117,25 @@ export function RegisterForm() {
|
|||||||
toast.error("密码长度不能少于 8 位")
|
toast.error("密码长度不能少于 8 位")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (emailRegisterEnabled) {
|
const trimmedEmail = email.trim()
|
||||||
if (!email.trim() || !code.trim()) {
|
if (!trimmedEmail) {
|
||||||
toast.error("邮箱和验证码不能为空")
|
toast.error("邮箱不能为空")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
if (!emailRegex.test(trimmedEmail)) {
|
||||||
|
toast.error("请输入有效的邮箱地址")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (emailRegisterEnabled && !code.trim()) {
|
||||||
|
toast.error("验证码不能为空")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
registerMutation.mutate({
|
registerMutation.mutate({
|
||||||
username: username.trim(),
|
username: username.trim(),
|
||||||
password,
|
password,
|
||||||
nickname: nickname.trim() || undefined,
|
nickname: nickname.trim() || undefined,
|
||||||
email: email.trim() || undefined,
|
email: trimmedEmail,
|
||||||
code: code.trim() || undefined,
|
code: code.trim() || undefined,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -155,55 +164,78 @@ export function RegisterForm() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3 pt-2">
|
<div className="space-y-3 pt-2">
|
||||||
<div className="space-y-2">
|
<div className="space-y-3">
|
||||||
<Input
|
<div className="space-y-1.5">
|
||||||
value={username}
|
<Label htmlFor="username">用户名</Label>
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
<Input
|
||||||
placeholder="用户名"
|
id="username"
|
||||||
autoComplete="username"
|
value={username}
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
/>
|
placeholder="请输入用户名"
|
||||||
<Input
|
autoComplete="username"
|
||||||
value={nickname}
|
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||||
onChange={(e) => setNickname(e.target.value)}
|
/>
|
||||||
placeholder="昵称(可选)"
|
</div>
|
||||||
autoComplete="nickname"
|
<div className="space-y-1.5">
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
<Label htmlFor="nickname">
|
||||||
/>
|
昵称
|
||||||
<Input
|
<span className="text-muted-foreground font-normal text-xs ml-1">(可选)</span>
|
||||||
value={password}
|
</Label>
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
<Input
|
||||||
type="password"
|
id="nickname"
|
||||||
placeholder="密码(至少 8 位)"
|
value={nickname}
|
||||||
autoComplete="new-password"
|
onChange={(e) => setNickname(e.target.value)}
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
placeholder="请输入昵称"
|
||||||
/>
|
autoComplete="nickname"
|
||||||
<Input
|
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||||
value={email}
|
/>
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
</div>
|
||||||
placeholder={emailRegisterEnabled ? "电子邮箱" : "电子邮箱(可选)"}
|
<div className="space-y-1.5">
|
||||||
autoComplete="email"
|
<Label htmlFor="password">密码</Label>
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
<Input
|
||||||
/>
|
id="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
type="password"
|
||||||
|
placeholder="请输入密码(至少 8 位)"
|
||||||
|
autoComplete="new-password"
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="email">电子邮箱</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="请输入电子邮箱"
|
||||||
|
autoComplete="email"
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
{emailRegisterEnabled && (
|
{emailRegisterEnabled && (
|
||||||
<div className="flex gap-2">
|
<div className="space-y-1.5">
|
||||||
<Input
|
<Label htmlFor="code">邮箱验证码</Label>
|
||||||
value={code}
|
<div className="flex gap-2">
|
||||||
onChange={(e) => setCode(e.target.value)}
|
<Input
|
||||||
placeholder="6 位邮箱验证码"
|
id="code"
|
||||||
maxLength={6}
|
value={code}
|
||||||
className="flex-1"
|
onChange={(e) => setCode(e.target.value)}
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
placeholder="请输入 6 位邮箱验证码"
|
||||||
/>
|
maxLength={6}
|
||||||
<Button
|
className="flex-1"
|
||||||
type="button"
|
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||||
variant="outline"
|
/>
|
||||||
onClick={handleSendRegisterCode}
|
<Button
|
||||||
disabled={registerCooldown > 0 || sendRegisterCodeMutation.isPending}
|
type="button"
|
||||||
className="w-[120px] text-xs"
|
variant="outline"
|
||||||
>
|
onClick={handleSendRegisterCode}
|
||||||
{registerCooldown > 0 ? `${registerCooldown}秒后重发` : "获取验证码"}
|
disabled={registerCooldown > 0 || sendRegisterCodeMutation.isPending}
|
||||||
</Button>
|
className="w-[120px] text-xs"
|
||||||
|
>
|
||||||
|
{registerCooldown > 0 ? `${registerCooldown}秒后重发` : "获取验证码"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Rain-kl/Wavelet/internal/common"
|
"github.com/Rain-kl/Wavelet/internal/common"
|
||||||
|
"github.com/Rain-kl/Wavelet/internal/config"
|
||||||
"github.com/Rain-kl/Wavelet/internal/db"
|
"github.com/Rain-kl/Wavelet/internal/db"
|
||||||
"github.com/Rain-kl/Wavelet/internal/model"
|
"github.com/Rain-kl/Wavelet/internal/model"
|
||||||
"github.com/Rain-kl/Wavelet/internal/util"
|
"github.com/Rain-kl/Wavelet/internal/util"
|
||||||
@@ -171,19 +172,32 @@ func setLoginSession(ctx context.Context, c *gin.Context, user *model.User) erro
|
|||||||
session.Set(UserNameKey, user.Username)
|
session.Set(UserNameKey, user.Username)
|
||||||
|
|
||||||
// 根据系统配置动态设置 Session 过期时间
|
// 根据系统配置动态设置 Session 过期时间
|
||||||
maxAge := 0
|
maxAge := config.Config.App.SessionAge
|
||||||
|
isSessionCookie := false
|
||||||
|
|
||||||
ttlHours, err := model.GetIntByKey(ctx, model.ConfigKeyLoginSessionTTLHours)
|
ttlHours, err := model.GetIntByKey(ctx, model.ConfigKeyLoginSessionTTLHours)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if ttlHours == -1 {
|
switch {
|
||||||
|
case ttlHours == -1:
|
||||||
// 永不过期,设置为 10 年
|
// 永不过期,设置为 10 年
|
||||||
maxAge = 10 * 365 * 24 * 3600
|
maxAge = 10 * 365 * 24 * 3600
|
||||||
} else if ttlHours > 0 {
|
case ttlHours > 0:
|
||||||
maxAge = ttlHours * 3600
|
maxAge = ttlHours * 3600
|
||||||
|
case ttlHours == 0:
|
||||||
|
isSessionCookie = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
session.Options(util.GetSessionOptions(maxAge))
|
session.Options(util.GetSessionOptions(maxAge))
|
||||||
|
|
||||||
return session.Save()
|
if err := session.Save(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if isSessionCookie {
|
||||||
|
util.StripCookieMaxAgeAndExpires(c.Writer.Header(), config.Config.App.SessionCookieName)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func uniqueUsername(ctx context.Context, base string) (string, error) {
|
func uniqueUsername(ctx context.Context, base string) (string, error) {
|
||||||
|
|||||||
+39
-38
@@ -5,42 +5,43 @@
|
|||||||
package user
|
package user
|
||||||
|
|
||||||
const (
|
const (
|
||||||
errBindParamsFailed = "参数绑定失败"
|
errBindParamsFailed = "参数绑定失败"
|
||||||
errInvalidParams = "无效的参数"
|
errInvalidParams = "无效的参数"
|
||||||
errPasswordLoginDisabled = "管理员关闭了密码登录" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errPasswordLoginDisabled = "管理员关闭了密码登录" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errUsernameOrPasswordWrong = "用户名或密码错误" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errUsernameOrPasswordWrong = "用户名或密码错误" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errLoginEmailMissing = "该账号未绑定邮箱,请联系管理员绑定邮箱后再登录"
|
errLoginEmailMissing = "该账号未绑定邮箱,请联系管理员绑定邮箱后再登录"
|
||||||
errNeedEmailCodePrefix = "need_email_code:"
|
errNeedEmailCodePrefix = "need_email_code:"
|
||||||
errEmailCodeInvalidOrExpired = "验证码错误或已过期"
|
errSMTPInvalidUseTempCodePrefix = "smtp_invalid:"
|
||||||
errPasswordUpgradeFailed = "升级密码安全算法失败,请重试" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errSMTPInvalidUseTempCode = "smtp 配置无效,使用临时码登录"
|
||||||
errSaveSessionFailed = "无法保存会话信息,请重试"
|
errEmailCodeInvalidOrExpired = "验证码错误或已过期"
|
||||||
errRegistrationDisabled = "管理员关闭了注册"
|
errSaveSessionFailed = "无法保存会话信息,请重试"
|
||||||
errPasswordTooShort = "密码长度不能少于 8 位" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errRegistrationDisabled = "管理员关闭了注册"
|
||||||
errEmailOrCodeRequired = "邮箱或验证码未填写"
|
errPasswordTooShort = "密码长度不能少于 8 位" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errNewPasswordTooShort = "新密码长度不能少于 8 位" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errEmailOrCodeRequired = "邮箱或验证码未填写"
|
||||||
errLoginRequired = "请先登录"
|
errNewPasswordTooShort = "新密码长度不能少于 8 位" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errUserNotFound = "未找到该用户"
|
errLoginRequired = "请先登录"
|
||||||
errOldPasswordIncorrect = "原密码不正确" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errUserNotFound = "未找到该用户"
|
||||||
errPasswordEncryptFailed = "密码加密失败,请重试" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errOldPasswordIncorrect = "原密码不正确" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errEmailRequired = "邮箱地址不能为空"
|
errPasswordEncryptFailed = "密码加密失败,请重试" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errUnsupportedEmailScene = "不支持的验证场景"
|
errEmailRequired = "邮箱地址不能为空"
|
||||||
errEmailAlreadyRegistered = "该邮箱已被注册"
|
errUnsupportedEmailScene = "不支持的验证场景"
|
||||||
errEmailCodeCooldown = "验证码发送频繁,请稍后再试"
|
errEmailAlreadyRegistered = "该邮箱已被注册"
|
||||||
errEmailFormatInvalid = "邮箱格式不正确"
|
errEmailCodeCooldown = "验证码发送频繁,请稍后再试"
|
||||||
errEmailAlreadyBound = "该邮箱已被其他账号绑定"
|
errEmailFormatInvalid = "邮箱格式不正确"
|
||||||
errRenderEmailTemplateFailed = "渲染验证邮件模板失败:%w"
|
errEmailAlreadyBound = "该邮箱已被其他账号绑定"
|
||||||
errGenerateEmailCodeFailed = "生成验证码失败,请重试"
|
errRenderEmailTemplateFailed = "渲染验证邮件模板失败:%w"
|
||||||
errDispatchEmailTaskFailed = "投递验证邮件发送任务失败,请重试"
|
errGenerateEmailCodeFailed = "生成验证码失败,请重试"
|
||||||
errTokenNameRequired = "令牌名称不能为空" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errDispatchEmailTaskFailed = "投递验证邮件发送任务失败,请重试"
|
||||||
errAccessTokenLimitReached = "已达到访问令牌最大创建数量限制" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errTokenNameRequired = "令牌名称不能为空" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errGenerateTokenFailed = "生成令牌失败" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errAccessTokenLimitReached = "已达到访问令牌最大创建数量限制" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errInvalidTokenID = "无效的令牌ID" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errGenerateTokenFailed = "生成令牌失败" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errTokenNotFoundOrForbidden = "令牌不存在或无权操作" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errInvalidTokenID = "无效的令牌ID" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errAdminTokenRequiresAdmin = "只有管理员才能创建具有管理员权限的令牌" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
errTokenNotFoundOrForbidden = "令牌不存在或无权操作" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errTaskPayloadRequired = "任务参数不能为空"
|
errAdminTokenRequiresAdmin = "只有管理员才能创建具有管理员权限的令牌" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||||
errInvalidJSONFormat = "无效的 JSON 格式: %w"
|
errTaskPayloadRequired = "任务参数不能为空"
|
||||||
errEmailTaskFieldsRequired = "to、subject、body 不能为空"
|
errInvalidJSONFormat = "无效的 JSON 格式: %w"
|
||||||
errParseEmailPayloadFailed = "解析邮件发送参数失败: %w"
|
errEmailTaskFieldsRequired = "to、subject、body 不能为空"
|
||||||
errSMTPConfigIncomplete = "系统 SMTP 邮件服务配置不完整"
|
errParseEmailPayloadFailed = "解析邮件发送参数失败: %w"
|
||||||
errSendMailFailed = "发送邮件失败: %w"
|
errSMTPConfigIncomplete = "系统 SMTP 邮件服务配置不完整"
|
||||||
|
errSendMailFailed = "发送邮件失败: %w"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -45,17 +45,19 @@ func isEmailRegisterVerificationEnabled(ctx context.Context) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func isSMTPConfigured(ctx context.Context) bool {
|
func isSMTPConfigured(ctx context.Context) bool {
|
||||||
var sc model.SystemConfig
|
|
||||||
var host, port, username string
|
var host, port, username string
|
||||||
|
|
||||||
if err := sc.GetByKey(ctx, model.ConfigKeySMTPHost); err == nil {
|
var scHost model.SystemConfig
|
||||||
host = sc.Value
|
if err := scHost.GetByKey(ctx, model.ConfigKeySMTPHost); err == nil {
|
||||||
|
host = scHost.Value
|
||||||
}
|
}
|
||||||
if err := sc.GetByKey(ctx, model.ConfigKeySMTPPort); err == nil {
|
var scPort model.SystemConfig
|
||||||
port = sc.Value
|
if err := scPort.GetByKey(ctx, model.ConfigKeySMTPPort); err == nil {
|
||||||
|
port = scPort.Value
|
||||||
}
|
}
|
||||||
if err := sc.GetByKey(ctx, model.ConfigKeySMTPUsername); err == nil {
|
var scUser model.SystemConfig
|
||||||
username = sc.Value
|
if err := scUser.GetByKey(ctx, model.ConfigKeySMTPUsername); err == nil {
|
||||||
|
username = scUser.Value
|
||||||
}
|
}
|
||||||
|
|
||||||
return host != "" && port != "" && username != ""
|
return host != "" && port != "" && username != ""
|
||||||
@@ -130,32 +132,44 @@ func verifyEmailCode(ctx context.Context, email, scene, code string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func handleLoginEmailVerification(ctx context.Context, c *gin.Context, req *loginRequest, user *model.User) error {
|
func handleLoginEmailVerification(ctx context.Context, c *gin.Context, req *loginRequest, user *model.User) error {
|
||||||
if user.Email == "" {
|
if req.Code != "" {
|
||||||
c.JSON(http.StatusOK, util.Err(errLoginEmailMissing))
|
if !verifyEmailCode(ctx, user.Email, "login", req.Code) {
|
||||||
return errors.New("handled")
|
c.JSON(http.StatusOK, util.Err(errEmailCodeInvalidOrExpired))
|
||||||
}
|
return errors.New("handled")
|
||||||
|
|
||||||
if req.Code == "" {
|
|
||||||
cooldownKey := getEmailCooldownKey("login", user.Email)
|
|
||||||
var temp string
|
|
||||||
err := db.GetJSON(ctx, cooldownKey, &temp)
|
|
||||||
if err != nil {
|
|
||||||
if err := sendEmailVerificationCode(ctx, user.Email, "login", "login_email"); err != nil {
|
|
||||||
c.JSON(http.StatusOK, util.Err(err.Error()))
|
|
||||||
return errors.New("handled")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
maskedEmail := util.MaskEmail(user.Email)
|
// 如果 SMTP 未配置,或者用户没有绑定邮箱(无法发送验证码),则使用临时码 888888
|
||||||
c.JSON(http.StatusOK, util.Err(errNeedEmailCodePrefix+maskedEmail))
|
if !isSMTPConfigured(ctx) || user.Email == "" {
|
||||||
|
codeKey := getEmailCodeKey("login", user.Email)
|
||||||
|
if err := db.SetJSON(ctx, codeKey, "888888", emailCodeExpiry); err != nil {
|
||||||
|
c.JSON(http.StatusOK, util.Err(errGenerateEmailCodeFailed))
|
||||||
|
return errors.New("handled")
|
||||||
|
}
|
||||||
|
var msg string
|
||||||
|
if !isSMTPConfigured(ctx) {
|
||||||
|
msg = errSMTPInvalidUseTempCodePrefix + errSMTPInvalidUseTempCode
|
||||||
|
} else {
|
||||||
|
msg = errSMTPInvalidUseTempCodePrefix + "该账号未绑定邮箱,使用临时码登录"
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, util.Err(msg))
|
||||||
return errors.New("handled")
|
return errors.New("handled")
|
||||||
}
|
}
|
||||||
|
|
||||||
if !verifyEmailCode(ctx, user.Email, "login", req.Code) {
|
cooldownKey := getEmailCooldownKey("login", user.Email)
|
||||||
c.JSON(http.StatusOK, util.Err(errEmailCodeInvalidOrExpired))
|
var temp string
|
||||||
return errors.New("handled")
|
err := db.GetJSON(ctx, cooldownKey, &temp)
|
||||||
|
if err != nil {
|
||||||
|
if err := sendEmailVerificationCode(ctx, user.Email, "login", "login_email"); err != nil {
|
||||||
|
c.JSON(http.StatusOK, util.Err(err.Error()))
|
||||||
|
return errors.New("handled")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
|
maskedEmail := util.MaskEmail(user.Email)
|
||||||
|
c.JSON(http.StatusOK, util.Err(errNeedEmailCodePrefix+maskedEmail))
|
||||||
|
return errors.New("handled")
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendEmailCode 发送邮箱验证码
|
// SendEmailCode 发送邮箱验证码
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Rain-kl/Wavelet/internal/apps/oauth"
|
"github.com/Rain-kl/Wavelet/internal/apps/oauth"
|
||||||
"github.com/Rain-kl/Wavelet/internal/common"
|
"github.com/Rain-kl/Wavelet/internal/common"
|
||||||
|
"github.com/Rain-kl/Wavelet/internal/config"
|
||||||
"github.com/Rain-kl/Wavelet/internal/db"
|
"github.com/Rain-kl/Wavelet/internal/db"
|
||||||
"github.com/Rain-kl/Wavelet/internal/db/idgen"
|
"github.com/Rain-kl/Wavelet/internal/db/idgen"
|
||||||
"github.com/Rain-kl/Wavelet/internal/model"
|
"github.com/Rain-kl/Wavelet/internal/model"
|
||||||
@@ -64,14 +65,19 @@ func setLoginSession(ctx context.Context, c *gin.Context, user *model.User) erro
|
|||||||
session.Set(oauth.UserNameKey, user.Username)
|
session.Set(oauth.UserNameKey, user.Username)
|
||||||
|
|
||||||
// 根据系统配置动态设置 Session 过期时间
|
// 根据系统配置动态设置 Session 过期时间
|
||||||
maxAge := 0
|
maxAge := config.Config.App.SessionAge
|
||||||
|
isSessionCookie := false
|
||||||
|
|
||||||
ttlHours, err := model.GetIntByKey(ctx, model.ConfigKeyLoginSessionTTLHours)
|
ttlHours, err := model.GetIntByKey(ctx, model.ConfigKeyLoginSessionTTLHours)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if ttlHours == -1 {
|
switch {
|
||||||
|
case ttlHours == -1:
|
||||||
// 永不过期,设置为 10 年
|
// 永不过期,设置为 10 年
|
||||||
maxAge = 10 * 365 * 24 * 3600
|
maxAge = 10 * 365 * 24 * 3600
|
||||||
} else if ttlHours > 0 {
|
case ttlHours > 0:
|
||||||
maxAge = ttlHours * 3600
|
maxAge = ttlHours * 3600
|
||||||
|
case ttlHours == 0:
|
||||||
|
isSessionCookie = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
session.Options(util.GetSessionOptions(maxAge))
|
session.Options(util.GetSessionOptions(maxAge))
|
||||||
@@ -79,6 +85,11 @@ func setLoginSession(ctx context.Context, c *gin.Context, user *model.User) erro
|
|||||||
if err := session.Save(); err != nil {
|
if err := session.Save(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if isSessionCookie {
|
||||||
|
util.StripCookieMaxAgeAndExpires(c.Writer.Header(), config.Config.App.SessionCookieName)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +122,7 @@ func Login(c *gin.Context) {
|
|||||||
|
|
||||||
var user model.User
|
var user model.User
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
if err := db.DB(ctx).Where("username = ?", req.Username).First(&user).Error; err != nil {
|
if err := db.DB(ctx).Where("username = ? OR email = ?", req.Username, req.Username).First(&user).Error; err != nil {
|
||||||
c.JSON(http.StatusOK, util.Err(errUsernameOrPasswordWrong))
|
c.JSON(http.StatusOK, util.Err(errUsernameOrPasswordWrong))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -193,6 +204,10 @@ func Register(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, util.Err(errInvalidParams))
|
c.JSON(http.StatusOK, util.Err(errInvalidParams))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if req.Email == "" {
|
||||||
|
c.JSON(http.StatusOK, util.Err(errEmailRequired))
|
||||||
|
return
|
||||||
|
}
|
||||||
if len(req.Password) < minPasswordLength {
|
if len(req.Password) < minPasswordLength {
|
||||||
c.JSON(http.StatusOK, util.Err(errPasswordTooShort))
|
c.JSON(http.StatusOK, util.Err(errPasswordTooShort))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package user
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -13,6 +14,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Rain-kl/Wavelet/internal/apps/oauth"
|
"github.com/Rain-kl/Wavelet/internal/apps/oauth"
|
||||||
"github.com/Rain-kl/Wavelet/internal/config"
|
"github.com/Rain-kl/Wavelet/internal/config"
|
||||||
|
"github.com/Rain-kl/Wavelet/internal/db"
|
||||||
"github.com/Rain-kl/Wavelet/internal/model"
|
"github.com/Rain-kl/Wavelet/internal/model"
|
||||||
"github.com/Rain-kl/Wavelet/internal/testhelper"
|
"github.com/Rain-kl/Wavelet/internal/testhelper"
|
||||||
"github.com/Rain-kl/Wavelet/internal/util"
|
"github.com/Rain-kl/Wavelet/internal/util"
|
||||||
@@ -141,6 +143,7 @@ func TestRegisterCreatesAuthenticatedEncryptedUser(t *testing.T) {
|
|||||||
Username: "newuser",
|
Username: "newuser",
|
||||||
Password: "newpassword123",
|
Password: "newpassword123",
|
||||||
Nickname: "New User",
|
Nickname: "New User",
|
||||||
|
Email: "newuser@example.com",
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(payload)
|
body, _ := json.Marshal(payload)
|
||||||
|
|
||||||
@@ -240,3 +243,203 @@ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|||||||
t.Errorf("UserInfo() after Login(%q) need_change_password = false, want true", adminUsername)
|
t.Errorf("UserInfo() after Login(%q) need_change_password = false, want true", adminUsername)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoginEmailVerificationFallbackWhenSMTPUnconfigured(t *testing.T) {
|
||||||
|
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
const (
|
||||||
|
userID = uint64(222)
|
||||||
|
username = "smtpuser"
|
||||||
|
password = "newpassword123"
|
||||||
|
email = "smtpuser@example.com"
|
||||||
|
)
|
||||||
|
now := time.Now()
|
||||||
|
user := model.User{
|
||||||
|
ID: userID,
|
||||||
|
Username: username,
|
||||||
|
Nickname: "SMTP User",
|
||||||
|
Email: email,
|
||||||
|
IsActive: true,
|
||||||
|
IsAdmin: false,
|
||||||
|
LastLoginAt: now,
|
||||||
|
}
|
||||||
|
if err := user.SetEncryptedPassword(password); err != nil {
|
||||||
|
t.Fatalf("set encrypted password failed: %v", err)
|
||||||
|
}
|
||||||
|
if err := dbConn.Create(&user).Error; err != nil {
|
||||||
|
t.Fatalf("create test user failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Enable email login verification
|
||||||
|
if err := dbConn.Model(&model.SystemConfig{}).Where("key = ?", model.ConfigKeyEmailLoginVerificationEnabled).Update("value", "true").Error; err != nil {
|
||||||
|
t.Fatalf("enable email login verification failed: %v", err)
|
||||||
|
}
|
||||||
|
// 2. Clear SMTP host to simulate unconfigured SMTP
|
||||||
|
if err := dbConn.Model(&model.SystemConfig{}).Where("key = ?", model.ConfigKeySMTPHost).Update("value", "").Error; err != nil {
|
||||||
|
t.Fatalf("clear SMTP host failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.5 Invalidate the system config cache in Redis
|
||||||
|
if err := db.Redis.Del(context.Background(), db.PrefixedKey(model.SystemConfigRedisHashKey)).Err(); err != nil {
|
||||||
|
t.Fatalf("invalidate system config cache failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
router := setupUserTestRouter(t)
|
||||||
|
|
||||||
|
// 3. Perform login request without verification code
|
||||||
|
payload := loginRequest{
|
||||||
|
Username: username,
|
||||||
|
Password: password,
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(payload)
|
||||||
|
|
||||||
|
w := performUserRequest(router, http.MethodPost, "/api/v1/user/login", body, nil)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("Login(%q) status = %d, want %d. Body: %s", username, w.Code, http.StatusOK, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check response error msg
|
||||||
|
var resp struct {
|
||||||
|
ErrorMsg string `json:"error_msg"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("unmarshal response failed: %v", err)
|
||||||
|
}
|
||||||
|
expectedError := errSMTPInvalidUseTempCodePrefix + errSMTPInvalidUseTempCode
|
||||||
|
if resp.ErrorMsg != expectedError {
|
||||||
|
t.Errorf("expected error %q, got %q", expectedError, resp.ErrorMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Check that verification code stored in Redis is "888888"
|
||||||
|
ctx := context.Background()
|
||||||
|
codeKey := getEmailCodeKey("login", email)
|
||||||
|
var storedCode string
|
||||||
|
if err := db.GetJSON(ctx, codeKey, &storedCode); err != nil {
|
||||||
|
t.Fatalf("get stored verification code failed: %v", err)
|
||||||
|
}
|
||||||
|
if storedCode != "888888" {
|
||||||
|
t.Errorf("expected verification code '888888', got %q", storedCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Retry login with code "888888"
|
||||||
|
payload.Code = "888888"
|
||||||
|
bodyWithCode, _ := json.Marshal(payload)
|
||||||
|
w = performUserRequest(router, http.MethodPost, "/api/v1/user/login", bodyWithCode, nil)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("Login with code status = %d, want %d. Body: %s", w.Code, http.StatusOK, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var successResp struct {
|
||||||
|
ErrorMsg string `json:"error_msg"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &successResp); err != nil {
|
||||||
|
t.Fatalf("unmarshal success response failed: %v", err)
|
||||||
|
}
|
||||||
|
if successResp.ErrorMsg != "" {
|
||||||
|
t.Errorf("expected login success, got error %q", successResp.ErrorMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginEmailVerificationFallbackForEmptyEmail(t *testing.T) {
|
||||||
|
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
const (
|
||||||
|
userID = uint64(223)
|
||||||
|
username = "emptyemailuser"
|
||||||
|
password = "newpassword123"
|
||||||
|
email = ""
|
||||||
|
)
|
||||||
|
now := time.Now()
|
||||||
|
user := model.User{
|
||||||
|
ID: userID,
|
||||||
|
Username: username,
|
||||||
|
Nickname: "Empty Email User",
|
||||||
|
Email: email,
|
||||||
|
IsActive: true,
|
||||||
|
IsAdmin: true,
|
||||||
|
LastLoginAt: now,
|
||||||
|
}
|
||||||
|
if err := user.SetEncryptedPassword(password); err != nil {
|
||||||
|
t.Fatalf("set encrypted password failed: %v", err)
|
||||||
|
}
|
||||||
|
if err := dbConn.Create(&user).Error; err != nil {
|
||||||
|
t.Fatalf("create test user failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Enable email login verification
|
||||||
|
if err := dbConn.Model(&model.SystemConfig{}).Where("key = ?", model.ConfigKeyEmailLoginVerificationEnabled).Update("value", "true").Error; err != nil {
|
||||||
|
t.Fatalf("enable email login verification failed: %v", err)
|
||||||
|
}
|
||||||
|
// 2. Make sure SMTP is configured so we only trigger empty email check
|
||||||
|
if err := dbConn.Model(&model.SystemConfig{}).Where("key = ?", model.ConfigKeySMTPHost).Update("value", "smtp.example.com").Error; err != nil {
|
||||||
|
t.Fatalf("set SMTP host failed: %v", err)
|
||||||
|
}
|
||||||
|
if err := dbConn.Model(&model.SystemConfig{}).Where("key = ?", model.ConfigKeySMTPPort).Update("value", "587").Error; err != nil {
|
||||||
|
t.Fatalf("set SMTP port failed: %v", err)
|
||||||
|
}
|
||||||
|
if err := dbConn.Model(&model.SystemConfig{}).Where("key = ?", model.ConfigKeySMTPUsername).Update("value", "smtpuser").Error; err != nil {
|
||||||
|
t.Fatalf("set SMTP username failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalidate the system config cache in Redis
|
||||||
|
if err := db.Redis.Del(context.Background(), db.PrefixedKey(model.SystemConfigRedisHashKey)).Err(); err != nil {
|
||||||
|
t.Fatalf("invalidate system config cache failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
router := setupUserTestRouter(t)
|
||||||
|
|
||||||
|
// 3. Perform login request without verification code
|
||||||
|
payload := loginRequest{
|
||||||
|
Username: username,
|
||||||
|
Password: password,
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(payload)
|
||||||
|
|
||||||
|
w := performUserRequest(router, http.MethodPost, "/api/v1/user/login", body, nil)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("Login(%q) status = %d, want %d. Body: %s", username, w.Code, http.StatusOK, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check response error msg
|
||||||
|
var resp struct {
|
||||||
|
ErrorMsg string `json:"error_msg"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("unmarshal response failed: %v", err)
|
||||||
|
}
|
||||||
|
expectedError := errSMTPInvalidUseTempCodePrefix + "该账号未绑定邮箱,使用临时码登录"
|
||||||
|
if resp.ErrorMsg != expectedError {
|
||||||
|
t.Errorf("expected error %q, got %q", expectedError, resp.ErrorMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Check that verification code stored in Redis is "888888"
|
||||||
|
ctx := context.Background()
|
||||||
|
codeKey := getEmailCodeKey("login", email)
|
||||||
|
var storedCode string
|
||||||
|
if err := db.GetJSON(ctx, codeKey, &storedCode); err != nil {
|
||||||
|
t.Fatalf("get stored verification code failed: %v", err)
|
||||||
|
}
|
||||||
|
if storedCode != "888888" {
|
||||||
|
t.Errorf("expected verification code '888888', got %q", storedCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Retry login with code "888888"
|
||||||
|
payload.Code = "888888"
|
||||||
|
bodyWithCode, _ := json.Marshal(payload)
|
||||||
|
w = performUserRequest(router, http.MethodPost, "/api/v1/user/login", bodyWithCode, nil)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("Login with code status = %d, want %d. Body: %s", w.Code, http.StatusOK, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var successResp struct {
|
||||||
|
ErrorMsg string `json:"error_msg"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &successResp); err != nil {
|
||||||
|
t.Fatalf("unmarshal success response failed: %v", err)
|
||||||
|
}
|
||||||
|
if successResp.ErrorMsg != "" {
|
||||||
|
t.Errorf("expected login success, got error %q", successResp.ErrorMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,6 +5,9 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Rain-kl/Wavelet/internal/config"
|
"github.com/Rain-kl/Wavelet/internal/config"
|
||||||
"github.com/gin-contrib/sessions"
|
"github.com/gin-contrib/sessions"
|
||||||
)
|
)
|
||||||
@@ -19,3 +22,31 @@ func GetSessionOptions(maxAge int) sessions.Options {
|
|||||||
Secure: config.Config.App.SessionSecure,
|
Secure: config.Config.App.SessionSecure,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StripCookieMaxAgeAndExpires 从 Set-Cookie 响应头中移除 Max-Age 和 Expires,从而使其成为浏览器会话 Cookie
|
||||||
|
func StripCookieMaxAgeAndExpires(header http.Header, cookieName string) {
|
||||||
|
headers := header["Set-Cookie"]
|
||||||
|
if len(headers) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
newHeaders := make([]string, 0, len(headers))
|
||||||
|
for _, h := range headers {
|
||||||
|
if strings.HasPrefix(h, cookieName+"=") {
|
||||||
|
parts := strings.Split(h, ";")
|
||||||
|
newParts := make([]string, 0, len(parts))
|
||||||
|
for _, p := range parts {
|
||||||
|
trimmed := strings.TrimSpace(p)
|
||||||
|
lower := strings.ToLower(trimmed)
|
||||||
|
if strings.HasPrefix(lower, "max-age=") || strings.HasPrefix(lower, "expires=") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newParts = append(newParts, p)
|
||||||
|
}
|
||||||
|
newHeaders = append(newHeaders, strings.Join(newParts, ";"))
|
||||||
|
} else {
|
||||||
|
newHeaders = append(newHeaders, h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
header["Set-Cookie"] = newHeaders
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user