fix: 修复前端多项问题并完善认证流程
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 15m39s
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 15m39s
- 修复 AuthContext 硬编码 localhost:8080,改用 api.ts 统一的 API_BASE_URL(走环境变量/代理,生产可部署) - 修复注册页发送验证码绕过 api.ts 直接 raw fetch 的问题,改用统一的 sendVerificationCode - 修复 SliderCaptcha 验证成功后 captchaId 未透传导致注册人机验证失效的断链 - 修复头像上传契约:预签名URL方式(/user/avatar/upload-url)改为直传(/user/avatar/upload) - 移除后端不支持的'设置活跃角色'功能(/profile/:uuid/activate)及相关死代码 - 修复分页字段不一致:新增 normalizePaginatedData 兼容后端 per_page 响应 - 强化邮箱正则校验(RFC 标准,禁止连续点/首尾点,TLD>=2字母) - 移除首页指向无效 /api 页面的'查看API文档'按钮 - 新增 /register /login /signup 重定向路由,统一指向 /auth?mode= - 同步 API文档.md
This commit is contained in:
@@ -2,12 +2,20 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { EyeIcon, EyeSlashIcon, CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/outline';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { errorManager } from '@/components/ErrorNotification';
|
||||
import SliderCaptcha from '@/components/SliderCaptcha';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { sendVerificationCode, resetPassword } from '@/lib/api';
|
||||
|
||||
// 邮箱格式校验:local@domain.tld
|
||||
// - local 段:字母/数字/._%+-,首尾不能是点,不能连续点
|
||||
// - domain 段:字母/数字/-,每段 1-63 字符,至少一个点
|
||||
// - TLD:至少 2 位字母
|
||||
const EMAIL_REGEX = /^(?!.*\.\.)[a-zA-Z0-9._%+-]+(?<!\.)@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
|
||||
|
||||
export default function AuthPage() {
|
||||
const [isLoginMode, setIsLoginMode] = useState(true);
|
||||
@@ -32,8 +40,26 @@ export default function AuthPage() {
|
||||
const [isCaptchaVerified, setIsCaptchaVerified] = useState(false);
|
||||
const [captchaId, setCaptchaId] = useState<string | undefined>();
|
||||
|
||||
// 忘记密码弹窗相关状态
|
||||
const [showForgotPassword, setShowForgotPassword] = useState(false);
|
||||
const [forgotForm, setForgotForm] = useState({ email: '', code: '', newPassword: '' });
|
||||
const [isSendingForgotCode, setIsSendingForgotCode] = useState(false);
|
||||
const [forgotCodeTimer, setForgotCodeTimer] = useState(0);
|
||||
const [isResettingPassword, setIsResettingPassword] = useState(false);
|
||||
|
||||
const { login, register } = useAuth();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// 支持 ?mode=register 直接进入注册模式(来自 /register、/signup 等重定向)
|
||||
useEffect(() => {
|
||||
const mode = searchParams.get('mode');
|
||||
if (mode === 'register') {
|
||||
setIsLoginMode(false);
|
||||
} else if (mode === 'login') {
|
||||
setIsLoginMode(true);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
let interval: NodeJS.Timeout;
|
||||
@@ -88,7 +114,7 @@ export default function AuthPage() {
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = '邮箱不能为空';
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
} else if (!EMAIL_REGEX.test(formData.email)) {
|
||||
newErrors.email = '请输入有效的邮箱地址';
|
||||
}
|
||||
|
||||
@@ -130,25 +156,14 @@ export default function AuthPage() {
|
||||
const passwordStrength = getPasswordStrength();
|
||||
|
||||
const handleSendCode = async () => {
|
||||
if (!formData.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
if (!formData.email || !EMAIL_REGEX.test(formData.email)) {
|
||||
setErrors(prev => ({ ...prev, email: '请输入有效的邮箱地址' }));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSendingCode(true);
|
||||
try {
|
||||
const response = await fetch('/api/v1/auth/send-code', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: formData.email,
|
||||
type: 'register'
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
const data = await sendVerificationCode(formData.email, 'register');
|
||||
|
||||
if (data.code === 200) {
|
||||
setCodeTimer(60);
|
||||
@@ -165,9 +180,10 @@ export default function AuthPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleCaptchaVerify = (success: boolean) => {
|
||||
const handleCaptchaVerify = (success: boolean, verifiedCaptchaId?: string) => {
|
||||
if (success) {
|
||||
setIsCaptchaVerified(true);
|
||||
setCaptchaId(verifiedCaptchaId);
|
||||
setShowCaptcha(false);
|
||||
// 验证码验证成功后,继续注册流程
|
||||
handleRegisterAfterCaptcha();
|
||||
@@ -255,6 +271,80 @@ export default function AuthPage() {
|
||||
});
|
||||
};
|
||||
|
||||
const openForgotPassword = () => {
|
||||
setForgotForm({ email: '', code: '', newPassword: '' });
|
||||
setForgotCodeTimer(0);
|
||||
setShowForgotPassword(true);
|
||||
};
|
||||
|
||||
const closeForgotPassword = () => {
|
||||
if (isResettingPassword) return;
|
||||
setShowForgotPassword(false);
|
||||
};
|
||||
|
||||
const handleSendForgotCode = async () => {
|
||||
const email = forgotForm.email.trim();
|
||||
if (!email || !EMAIL_REGEX.test(email)) {
|
||||
errorManager.showError('请输入有效的邮箱地址');
|
||||
return;
|
||||
}
|
||||
setIsSendingForgotCode(true);
|
||||
try {
|
||||
const resp = await sendVerificationCode(email, 'reset_password');
|
||||
if (resp.code === 200) {
|
||||
errorManager.showSuccess('验证码已发送到您的邮箱');
|
||||
setForgotCodeTimer(60);
|
||||
const timer = setInterval(() => {
|
||||
setForgotCodeTimer(prev => {
|
||||
if (prev <= 1) {
|
||||
clearInterval(timer);
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
} else {
|
||||
errorManager.showError(resp.message || '发送验证码失败');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('发送验证码失败:', err);
|
||||
errorManager.showError('发送验证码失败,请稍后重试');
|
||||
} finally {
|
||||
setIsSendingForgotCode(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
const { email, code, newPassword } = forgotForm;
|
||||
if (!email.trim() || !EMAIL_REGEX.test(email.trim())) {
|
||||
errorManager.showError('请输入有效的邮箱地址');
|
||||
return;
|
||||
}
|
||||
if (!/^\d{6}$/.test(code.trim())) {
|
||||
errorManager.showError('请输入6位数字验证码');
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 6 || newPassword.length > 128) {
|
||||
errorManager.showError('新密码长度需在6-128位之间');
|
||||
return;
|
||||
}
|
||||
setIsResettingPassword(true);
|
||||
try {
|
||||
const resp = await resetPassword(email.trim(), code.trim(), newPassword);
|
||||
if (resp.code === 200) {
|
||||
errorManager.showSuccess('密码重置成功,请使用新密码登录');
|
||||
setShowForgotPassword(false);
|
||||
} else {
|
||||
errorManager.showError(resp.message || '重置密码失败');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('重置密码失败:', err);
|
||||
errorManager.showError('重置密码失败,请稍后重试');
|
||||
} finally {
|
||||
setIsResettingPassword(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex">
|
||||
{/* Left Side - Orange Section */}
|
||||
@@ -619,9 +709,13 @@ export default function AuthPage() {
|
||||
记住我
|
||||
</span>
|
||||
</label>
|
||||
<Link href="/forgot-password" className="text-sm text-orange-500 hover:text-orange-600 transition-colors">
|
||||
<button
|
||||
type="button"
|
||||
onClick={openForgotPassword}
|
||||
className="text-sm text-orange-500 hover:text-orange-600 transition-colors"
|
||||
>
|
||||
忘记密码?
|
||||
</Link>
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
@@ -646,13 +740,21 @@ export default function AuthPage() {
|
||||
/>
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
我已阅读并同意
|
||||
<Link href="/terms" className="text-orange-500 hover:text-orange-600 underline ml-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.preventDefault(); errorManager.showError('服务条款页面建设中'); }}
|
||||
className="text-orange-500 hover:text-orange-600 underline ml-1"
|
||||
>
|
||||
服务条款
|
||||
</Link>
|
||||
</button>
|
||||
和
|
||||
<Link href="/privacy" className="text-orange-500 hover:text-orange-600 underline ml-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.preventDefault(); errorManager.showError('隐私政策页面建设中'); }}
|
||||
className="text-orange-500 hover:text-orange-600 underline ml-1"
|
||||
>
|
||||
隐私政策
|
||||
</Link>
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
{errors.agreeToTerms && (
|
||||
@@ -766,6 +868,94 @@ export default function AuthPage() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Forgot Password Modal */}
|
||||
{showForgotPassword && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999] p-4"
|
||||
onClick={closeForgotPassword}
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.9, y: 20 }}
|
||||
animate={{ scale: 1, y: 0 }}
|
||||
className="bg-white dark:bg-gray-800 rounded-2xl p-6 w-full max-w-md"
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-xl font-bold text-gray-900 dark:text-white">找回密码</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeForgotPassword}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 disabled:opacity-50"
|
||||
disabled={isResettingPassword}
|
||||
>
|
||||
<XMarkIcon className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
注册邮箱
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={forgotForm.email}
|
||||
onChange={e => setForgotForm(prev => ({ ...prev, email: e.target.value }))}
|
||||
placeholder="请输入注册时使用的邮箱"
|
||||
disabled={isResettingPassword}
|
||||
className="w-full px-4 py-3 bg-white/50 dark:bg-gray-700/50 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200 disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
验证码
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
maxLength={6}
|
||||
value={forgotForm.code}
|
||||
onChange={e => setForgotForm(prev => ({ ...prev, code: e.target.value.replace(/\D/g, '') }))}
|
||||
placeholder="6位数字验证码"
|
||||
disabled={isResettingPassword}
|
||||
className="flex-1 px-4 py-3 bg-white/50 dark:bg-gray-700/50 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200 disabled:opacity-50"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSendForgotCode}
|
||||
disabled={isSendingForgotCode || forgotCodeTimer > 0 || isResettingPassword}
|
||||
className="bg-gradient-to-r from-orange-500 to-amber-500 text-white px-4 py-2 rounded-xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
|
||||
>
|
||||
{forgotCodeTimer > 0 ? `${forgotCodeTimer}s` : isSendingForgotCode ? '发送中...' : '发送验证码'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
新密码
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={forgotForm.newPassword}
|
||||
onChange={e => setForgotForm(prev => ({ ...prev, newPassword: e.target.value }))}
|
||||
placeholder="6-128位新密码"
|
||||
disabled={isResettingPassword}
|
||||
className="w-full px-4 py-3 bg-white/50 dark:bg-gray-700/50 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200 disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleResetPassword}
|
||||
disabled={isResettingPassword}
|
||||
className="w-full bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white font-semibold py-3 rounded-xl shadow-lg transition-all duration-200 disabled:opacity-50"
|
||||
>
|
||||
{isResettingPassword ? '重置中...' : '重置密码'}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
6
src/app/login/page.tsx
Normal file
6
src/app/login/page.tsx
Normal file
@@ -0,0 +1,6 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
// /login 兼容入口:重定向到统一认证页并默认进入登录模式
|
||||
export default function LoginPage() {
|
||||
redirect('/auth?mode=login');
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
CloudArrowUpIcon,
|
||||
ShareIcon,
|
||||
CubeIcon,
|
||||
UserGroupIcon,
|
||||
SparklesIcon,
|
||||
RocketLaunchIcon
|
||||
} from '@heroicons/react/24/outline';
|
||||
@@ -291,14 +290,6 @@ export default function Home() {
|
||||
<span>免费注册</span>
|
||||
<ArrowRightIcon className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
href="/api"
|
||||
className="border-2 border-white/30 text-white hover:bg-white/10 font-bold py-4 px-8 rounded-2xl transition-all duration-300 inline-flex items-center space-x-2"
|
||||
>
|
||||
<span>查看API文档</span>
|
||||
<UserGroupIcon className="w-5 h-5" />
|
||||
</Link>
|
||||
</div>
|
||||
</motion.div>
|
||||
</section>
|
||||
|
||||
@@ -30,15 +30,16 @@ import {
|
||||
createProfile,
|
||||
updateProfile,
|
||||
deleteProfile,
|
||||
setActiveProfile,
|
||||
getUserProfile,
|
||||
updateUserProfile,
|
||||
uploadTexture,
|
||||
getTexture,
|
||||
generateAvatarUploadUrl,
|
||||
updateAvatarUrl,
|
||||
uploadAvatar,
|
||||
resetYggdrasilPassword,
|
||||
deleteTexture,
|
||||
updateTexture,
|
||||
sendVerificationCode,
|
||||
changeEmail,
|
||||
type Texture,
|
||||
type Profile
|
||||
} from '@/lib/api';
|
||||
@@ -98,7 +99,14 @@ export default function ProfilePage() {
|
||||
const [showYggdrasilPassword, setShowYggdrasilPassword] = useState<boolean>(false);
|
||||
const [isResettingYggdrasilPassword, setIsResettingYggdrasilPassword] = useState<boolean>(false);
|
||||
|
||||
const { user, isAuthenticated, logout } = useAuth();
|
||||
// 更换邮箱流程相关状态
|
||||
const [showChangeEmailModal, setShowChangeEmailModal] = useState(false);
|
||||
const [changeEmailForm, setChangeEmailForm] = useState({ newEmail: '', code: '' });
|
||||
const [isSendingEmailCode, setIsSendingEmailCode] = useState(false);
|
||||
const [emailCodeCountdown, setEmailCodeCountdown] = useState(0);
|
||||
const [isChangingEmail, setIsChangingEmail] = useState(false);
|
||||
|
||||
const { user, isAuthenticated, logout, updateUser } = useAuth();
|
||||
|
||||
// 加载用户数据
|
||||
useEffect(() => {
|
||||
@@ -179,16 +187,36 @@ export default function ProfilePage() {
|
||||
};
|
||||
|
||||
const handleToggleSkinVisibility = async (skinId: number) => {
|
||||
try {
|
||||
const skin = mySkins.find(s => s.id === skinId);
|
||||
if (!skin) return;
|
||||
|
||||
// TODO: 添加更新皮肤API调用
|
||||
setMySkins(prev => prev.map(skin =>
|
||||
skin.id === skinId ? { ...skin, is_public: !skin.is_public } : skin
|
||||
const newIsPublic = !skin.is_public;
|
||||
// 先乐观更新本地态,失败再回滚
|
||||
setMySkins(prev => prev.map(s =>
|
||||
s.id === skinId ? { ...s, is_public: newIsPublic } : s
|
||||
));
|
||||
|
||||
try {
|
||||
const response = await updateTexture(skinId, { is_public: newIsPublic });
|
||||
if (response.code === 200) {
|
||||
// 以后端返回为准
|
||||
setMySkins(prev => prev.map(s =>
|
||||
s.id === skinId ? { ...s, is_public: response.data.is_public } : s
|
||||
));
|
||||
messageManager.success(newIsPublic ? '已设为公开' : '已设为隐藏', { duration: 2000 });
|
||||
} else {
|
||||
// 回滚
|
||||
setMySkins(prev => prev.map(s =>
|
||||
s.id === skinId ? { ...s, is_public: skin.is_public } : s
|
||||
));
|
||||
messageManager.error(response.message || '切换可见性失败', { duration: 3000 });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('切换皮肤可见性失败:', error);
|
||||
setMySkins(prev => prev.map(s =>
|
||||
s.id === skinId ? { ...s, is_public: skin.is_public } : s
|
||||
));
|
||||
messageManager.error('切换可见性失败,请稍后重试', { duration: 3000 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -313,45 +341,24 @@ export default function ProfilePage() {
|
||||
setAvatarUploadProgress(0);
|
||||
|
||||
try {
|
||||
// 获取上传URL
|
||||
const uploadUrlResponse = await generateAvatarUploadUrl(avatarFile.name);
|
||||
if (uploadUrlResponse.code !== 200) {
|
||||
throw new Error(uploadUrlResponse.message || '获取上传URL失败');
|
||||
}
|
||||
|
||||
const { post_url, form_data, avatar_url } = uploadUrlResponse.data;
|
||||
|
||||
// 模拟上传进度
|
||||
const progressInterval = setInterval(() => {
|
||||
setAvatarUploadProgress(prev => Math.min(prev + 20, 80));
|
||||
}, 200);
|
||||
|
||||
// 上传文件到预签名URL
|
||||
const formData = new FormData();
|
||||
Object.entries(form_data).forEach(([key, value]) => {
|
||||
formData.append(key, value as string);
|
||||
});
|
||||
formData.append('file', avatarFile);
|
||||
|
||||
const uploadResponse = await fetch(post_url, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error('文件上传失败');
|
||||
}
|
||||
// 直接上传文件到后端,后端写入对象存储并更新用户头像
|
||||
const response = await uploadAvatar(avatarFile);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setAvatarUploadProgress(100);
|
||||
|
||||
// 更新用户头像URL
|
||||
const response = await updateAvatarUrl(avatar_url);
|
||||
if (response.code === 200) {
|
||||
setUserProfile(prev => prev ? { ...prev, avatar: avatar_url } : null);
|
||||
const avatarUrl = response.data.avatar_url;
|
||||
setUserProfile(prev => prev ? { ...prev, avatar: avatarUrl } : null);
|
||||
updateUser({ avatar: avatarUrl });
|
||||
messageManager.success('头像上传成功!', { duration: 3000 });
|
||||
} else {
|
||||
throw new Error(response.message || '更新头像URL失败');
|
||||
throw new Error(response.message || '头像上传失败');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -405,6 +412,86 @@ export default function ProfilePage() {
|
||||
}
|
||||
};
|
||||
|
||||
// 发送更换邮箱的验证码(type=change_email)
|
||||
const handleSendChangeEmailCode = async () => {
|
||||
const email = changeEmailForm.newEmail.trim();
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!email) {
|
||||
messageManager.warning('请输入新邮箱地址', { duration: 3000 });
|
||||
return;
|
||||
}
|
||||
if (!EMAIL_REGEX.test(email)) {
|
||||
messageManager.warning('请输入有效的邮箱地址', { duration: 3000 });
|
||||
return;
|
||||
}
|
||||
if (email === userProfile?.email) {
|
||||
messageManager.warning('新邮箱不能与当前邮箱相同', { duration: 3000 });
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSendingEmailCode(true);
|
||||
try {
|
||||
const resp = await sendVerificationCode(email, 'change_email');
|
||||
if (resp.code === 200) {
|
||||
messageManager.success('验证码已发送到新邮箱', { duration: 3000 });
|
||||
setEmailCodeCountdown(60);
|
||||
const timer = setInterval(() => {
|
||||
setEmailCodeCountdown(prev => {
|
||||
if (prev <= 1) {
|
||||
clearInterval(timer);
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
} else {
|
||||
messageManager.error(resp.message || '发送验证码失败', { duration: 3000 });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('发送验证码失败:', err);
|
||||
messageManager.error('发送验证码失败,请稍后重试', { duration: 3000 });
|
||||
} finally {
|
||||
setIsSendingEmailCode(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 提交更换邮箱
|
||||
const handleChangeEmail = async () => {
|
||||
const newEmail = changeEmailForm.newEmail.trim();
|
||||
const code = changeEmailForm.code.trim();
|
||||
if (!newEmail) {
|
||||
messageManager.warning('请输入新邮箱地址', { duration: 3000 });
|
||||
return;
|
||||
}
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
messageManager.warning('请输入6位数字验证码', { duration: 3000 });
|
||||
return;
|
||||
}
|
||||
|
||||
setIsChangingEmail(true);
|
||||
try {
|
||||
const resp = await changeEmail(newEmail, code);
|
||||
if (resp.code === 200) {
|
||||
messageManager.success('邮箱更换成功', { duration: 3000 });
|
||||
// 同步本地用户信息(email 已变化)
|
||||
setUserProfile(prev => prev ? { ...prev, email: resp.data.email } : prev);
|
||||
if (updateUser) {
|
||||
updateUser({ email: resp.data.email });
|
||||
}
|
||||
setShowChangeEmailModal(false);
|
||||
setChangeEmailForm({ newEmail: '', code: '' });
|
||||
setEmailCodeCountdown(0);
|
||||
} else {
|
||||
messageManager.error(resp.message || '更换邮箱失败', { duration: 3000 });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('更换邮箱失败:', err);
|
||||
messageManager.error('更换邮箱失败,请稍后重试', { duration: 3000 });
|
||||
} finally {
|
||||
setIsChangingEmail(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateCharacter = async () => {
|
||||
if (!newCharacterName.trim()) {
|
||||
messageManager.warning('请输入角色名称', { duration: 3000 });
|
||||
@@ -448,25 +535,6 @@ export default function ProfilePage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleSetActiveCharacter = async (uuid: string) => {
|
||||
try {
|
||||
const response = await setActiveProfile(uuid);
|
||||
if (response.code === 200) {
|
||||
setProfiles(prev => prev.map(profile => ({
|
||||
...profile,
|
||||
is_active: profile.uuid === uuid
|
||||
})));
|
||||
messageManager.success('角色切换成功!', { duration: 3000 });
|
||||
} else {
|
||||
throw new Error(response.message || '设置活跃角色失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('设置活跃角色失败:', error);
|
||||
messageManager.error(error instanceof Error ? error.message : '设置活跃角色失败,请稍后重试', { duration: 3000 });
|
||||
} finally {
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditCharacter = async () => {
|
||||
if (!editProfileName.trim()) {
|
||||
messageManager.warning('请输入角色名称', { duration: 3000 });
|
||||
@@ -604,7 +672,6 @@ export default function ProfilePage() {
|
||||
onSave={handleEditCharacter}
|
||||
onCancel={onCancelEdit}
|
||||
onDelete={handleDeleteCharacter}
|
||||
onSetActive={handleSetActiveCharacter}
|
||||
onSelectSkin={setShowSkinSelector}
|
||||
onEditNameChange={setEditProfileName}
|
||||
/>
|
||||
@@ -851,6 +918,11 @@ export default function ProfilePage() {
|
||||
className="w-full flex items-center justify-between p-3 border border-orange-500 text-orange-500 hover:bg-orange-500 hover:text-white rounded-xl transition-all duration-200"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
onClick={() => {
|
||||
setChangeEmailForm({ newEmail: '', code: '' });
|
||||
setEmailCodeCountdown(0);
|
||||
setShowChangeEmailModal(true);
|
||||
}}
|
||||
>
|
||||
<span>更换邮箱地址</span>
|
||||
<EnvelopeIcon className="w-5 h-5" />
|
||||
@@ -927,19 +999,35 @@ export default function ProfilePage() {
|
||||
<motion.div
|
||||
className="aspect-square bg-gray-100 dark:bg-gray-700 rounded-xl flex items-center justify-center cursor-pointer border-2 border-dashed border-gray-300 dark:border-gray-600"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
onClick={() => {
|
||||
// 移除皮肤
|
||||
if (currentProfile) {
|
||||
updateProfile(currentProfile.uuid, { skin_id: undefined });
|
||||
onClick={async () => {
|
||||
if (!currentProfile) return;
|
||||
const prevSkinId = currentProfile.skin_id;
|
||||
// 乐观更新本地态
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: undefined } : p
|
||||
));
|
||||
setProfileSkins(prev => {
|
||||
const newSkins = { ...prev };
|
||||
delete newSkins[currentProfile.uuid];
|
||||
return newSkins;
|
||||
const next = { ...prev };
|
||||
delete next[currentProfile.uuid];
|
||||
return next;
|
||||
});
|
||||
setShowSkinSelector(null);
|
||||
try {
|
||||
// 显式传 null(区别于 undefined 被 JSON.stringify 丢弃),后端据此清空皮肤关联
|
||||
const resp = await updateProfile(currentProfile.uuid, { skin_id: null });
|
||||
if (resp.code !== 200) {
|
||||
// 回滚
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: prevSkinId } : p
|
||||
));
|
||||
messageManager.error(resp.message || '移除皮肤失败', { duration: 3000 });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('移除皮肤失败:', err);
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: prevSkinId } : p
|
||||
));
|
||||
messageManager.error('移除皮肤失败,请稍后重试', { duration: 3000 });
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -954,10 +1042,10 @@ export default function ProfilePage() {
|
||||
key={skin.id}
|
||||
className="aspect-square bg-gradient-to-br from-orange-100 to-amber-100 dark:from-gray-700 dark:to-gray-600 rounded-xl overflow-hidden cursor-pointer relative group"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
onClick={() => {
|
||||
// 分配皮肤给角色
|
||||
if (currentProfile) {
|
||||
updateProfile(currentProfile.uuid, { skin_id: skin.id });
|
||||
onClick={async () => {
|
||||
if (!currentProfile) return;
|
||||
const prevSkinId = currentProfile.skin_id;
|
||||
// 乐观更新
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: skin.id } : p
|
||||
));
|
||||
@@ -966,6 +1054,20 @@ export default function ProfilePage() {
|
||||
[currentProfile.uuid]: { url: skin.url, isSlim: skin.is_slim }
|
||||
}));
|
||||
setShowSkinSelector(null);
|
||||
try {
|
||||
const resp = await updateProfile(currentProfile.uuid, { skin_id: skin.id });
|
||||
if (resp.code !== 200) {
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: prevSkinId } : p
|
||||
));
|
||||
messageManager.error(resp.message || '设置皮肤失败', { duration: 3000 });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('设置皮肤失败:', err);
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: prevSkinId } : p
|
||||
));
|
||||
messageManager.error('设置皮肤失败,请稍后重试', { duration: 3000 });
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -1143,6 +1245,116 @@ export default function ProfilePage() {
|
||||
|
||||
{/* Skin Selector Modal */}
|
||||
{renderSkinSelector()}
|
||||
|
||||
{/* Change Email Modal */}
|
||||
{showChangeEmailModal && (
|
||||
<AnimatePresence>
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]"
|
||||
onClick={() => !isChangingEmail && setShowChangeEmailModal(false)}
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.9, y: 20 }}
|
||||
animate={{ scale: 1, y: 0 }}
|
||||
exit={{ scale: 0.9, y: 20 }}
|
||||
className="bg-white dark:bg-gray-800 rounded-2xl p-6 w-full max-w-md mx-4"
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-xl font-bold text-gray-900 dark:text-white flex items-center space-x-2">
|
||||
<EnvelopeIcon className="w-5 h-5" />
|
||||
<span>更换邮箱地址</span>
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => !isChangingEmail && setShowChangeEmailModal(false)}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 disabled:opacity-50"
|
||||
disabled={isChangingEmail}
|
||||
>
|
||||
<XMarkIcon className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
当前邮箱
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={userProfile?.email || ''}
|
||||
readOnly
|
||||
className="w-full px-4 py-3 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-xl text-gray-500 dark:text-gray-400"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
新邮箱地址
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={changeEmailForm.newEmail}
|
||||
onChange={e => setChangeEmailForm(prev => ({ ...prev, newEmail: e.target.value }))}
|
||||
placeholder="请输入新邮箱"
|
||||
disabled={isChangingEmail}
|
||||
className="w-full px-4 py-3 bg-white/50 dark:bg-gray-700/50 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200 disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
验证码
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
maxLength={6}
|
||||
value={changeEmailForm.code}
|
||||
onChange={e => setChangeEmailForm(prev => ({ ...prev, code: e.target.value.replace(/\D/g, '') }))}
|
||||
placeholder="6位数字验证码"
|
||||
disabled={isChangingEmail}
|
||||
className="flex-1 px-4 py-3 bg-white/50 dark:bg-gray-700/50 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200 disabled:opacity-50"
|
||||
/>
|
||||
<motion.button
|
||||
onClick={handleSendChangeEmailCode}
|
||||
disabled={isSendingEmailCode || emailCodeCountdown > 0 || isChangingEmail}
|
||||
className="bg-gradient-to-r from-orange-500 to-amber-500 text-white px-4 py-2 rounded-xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
|
||||
whileHover={{ scale: 1.05 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
{emailCodeCountdown > 0 ? `${emailCodeCountdown}s` : isSendingEmailCode ? '发送中...' : '发送验证码'}
|
||||
</motion.button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
验证码将发送到新邮箱,请查收邮件
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex space-x-3 pt-2">
|
||||
<motion.button
|
||||
onClick={() => setShowChangeEmailModal(false)}
|
||||
disabled={isChangingEmail}
|
||||
className="flex-1 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 px-4 py-2 rounded-xl transition-all duration-200 disabled:opacity-50"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
取消
|
||||
</motion.button>
|
||||
<motion.button
|
||||
onClick={handleChangeEmail}
|
||||
disabled={isChangingEmail}
|
||||
className="flex-1 bg-gradient-to-r from-orange-500 to-amber-500 text-white px-4 py-2 rounded-xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
{isChangingEmail ? '更换中...' : '确认更换'}
|
||||
</motion.button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
6
src/app/register/page.tsx
Normal file
6
src/app/register/page.tsx
Normal file
@@ -0,0 +1,6 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
// /register 兼容入口:重定向到统一认证页并默认进入注册模式
|
||||
export default function RegisterPage() {
|
||||
redirect('/auth?mode=register');
|
||||
}
|
||||
6
src/app/signup/page.tsx
Normal file
6
src/app/signup/page.tsx
Normal file
@@ -0,0 +1,6 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
// /signup 兼容入口:重定向到统一认证页并默认进入注册模式
|
||||
export default function SignupPage() {
|
||||
redirect('/auth?mode=register');
|
||||
}
|
||||
@@ -6,11 +6,11 @@ import { API_BASE_URL } from '@/lib/api';
|
||||
/**
|
||||
* 滑块验证码组件属性接口定义
|
||||
* @interface SliderCaptchaProps
|
||||
* @property {function} onVerify - 验证结果回调函数,参数为验证是否成功
|
||||
* @property {function} onVerify - 验证结果回调函数,参数为验证是否成功及验证码ID(成功时)
|
||||
* @property {function} onClose - 关闭验证码组件的回调函数
|
||||
*/
|
||||
interface SliderCaptchaProps {
|
||||
onVerify: (success: boolean) => void;
|
||||
onVerify: (success: boolean, captchaId?: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -184,8 +184,8 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
setVerifyResult(false);
|
||||
// 直接设置验证成功状态,不使用异步更新
|
||||
setIsVerified(true);
|
||||
// 延迟1.2秒后调用验证成功回调
|
||||
setTimeout(() => onVerify(true), 1200);
|
||||
// 延迟1.2秒后调用验证成功回调,透传后端返回的 captchaId 供注册接口使用
|
||||
setTimeout(() => onVerify(true, processId), 1200);
|
||||
}
|
||||
// 验证失败:code=400
|
||||
else if (code === 400) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { motion } from 'framer-motion';
|
||||
import { UserIcon, PencilIcon, TrashIcon, CheckIcon } from '@heroicons/react/24/outline';
|
||||
import { UserIcon, PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import SkinViewer from '@/components/SkinViewer';
|
||||
import type { Profile } from '@/lib/api';
|
||||
|
||||
@@ -15,7 +15,6 @@ interface CharacterCardProps {
|
||||
onSave: (uuid: string) => void;
|
||||
onCancel: () => void;
|
||||
onDelete: (uuid: string) => void;
|
||||
onSetActive: (uuid: string) => void;
|
||||
onSelectSkin: (uuid: string) => void;
|
||||
onEditNameChange: (name: string) => void;
|
||||
}
|
||||
@@ -30,7 +29,6 @@ export default function CharacterCard({
|
||||
onSave,
|
||||
onCancel,
|
||||
onDelete,
|
||||
onSetActive,
|
||||
onSelectSkin,
|
||||
onEditNameChange
|
||||
}: CharacterCardProps) {
|
||||
@@ -68,12 +66,6 @@ export default function CharacterCard({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{profile.is_active && (
|
||||
<span className="px-2 py-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white text-xs rounded-full flex items-center space-x-1">
|
||||
<CheckIcon className="w-3 h-3" />
|
||||
<span>当前使用</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="aspect-square bg-gradient-to-br from-orange-100 to-amber-100 dark:from-gray-700 dark:to-gray-600 rounded-xl mb-4 flex items-center justify-center relative overflow-hidden">
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
import { API_BASE_URL } from '@/lib/api';
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
@@ -28,8 +29,6 @@ interface AuthContextType {
|
||||
refreshUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
const API_BASE_URL = 'http://localhost:8080/api/v1';
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
161
src/lib/api.ts
161
src/lib/api.ts
@@ -24,7 +24,7 @@ export interface Profile {
|
||||
name: string;
|
||||
skin_id?: number;
|
||||
cape_id?: number;
|
||||
is_active: boolean;
|
||||
is_active?: boolean;
|
||||
last_used_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
@@ -38,6 +38,32 @@ export interface PaginatedResponse<T> {
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
// 后端原始分页响应结构(统一返回 { list, total, page, per_page },不含 total_pages/page_size)
|
||||
type RawPaginatedData<T> = {
|
||||
list?: T[];
|
||||
total?: number;
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
page_size?: number;
|
||||
};
|
||||
|
||||
// 在前端补齐 page_size 与 total_pages(由 total / page_size 向上取整),以便 UI 分页使用
|
||||
function normalizePaginatedData<T>(raw: RawPaginatedData<T>): PaginatedResponse<T> {
|
||||
const list = raw.list ?? [];
|
||||
const total = raw.total ?? 0;
|
||||
const page = raw.page ?? 1;
|
||||
const page_size = raw.per_page ?? raw.page_size ?? 20;
|
||||
const total_pages = page_size > 0 ? Math.max(1, Math.ceil(total / page_size)) : 1;
|
||||
return { list, total, page, page_size, total_pages };
|
||||
}
|
||||
|
||||
// 后端错误响应的 data 可能不是分页结构(code !== 200),用此类型宽松接收
|
||||
type RawApiResponse<T> = {
|
||||
code: number;
|
||||
message: string;
|
||||
data: T;
|
||||
};
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
code: number;
|
||||
message: string;
|
||||
@@ -75,7 +101,11 @@ export async function searchTextures(params: {
|
||||
},
|
||||
});
|
||||
|
||||
return response.json();
|
||||
const result: RawApiResponse<RawPaginatedData<Texture>> = await response.json();
|
||||
if (result.code === 200 && result.data) {
|
||||
return { ...result, data: normalizePaginatedData(result.data) };
|
||||
}
|
||||
return result as ApiResponse<PaginatedResponse<Texture>>;
|
||||
}
|
||||
|
||||
// 获取材质详情
|
||||
@@ -114,7 +144,11 @@ export async function getMyTextures(params: {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
const result: RawApiResponse<RawPaginatedData<Texture>> = await response.json();
|
||||
if (result.code === 200 && result.data) {
|
||||
return { ...result, data: normalizePaginatedData(result.data) };
|
||||
}
|
||||
return result as ApiResponse<PaginatedResponse<Texture>>;
|
||||
}
|
||||
|
||||
// 获取用户收藏的材质列表
|
||||
@@ -131,7 +165,11 @@ export async function getFavoriteTextures(params: {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
const result: RawApiResponse<RawPaginatedData<Texture>> = await response.json();
|
||||
if (result.code === 200 && result.data) {
|
||||
return { ...result, data: normalizePaginatedData(result.data) };
|
||||
}
|
||||
return result as ApiResponse<PaginatedResponse<Texture>>;
|
||||
}
|
||||
|
||||
// 获取用户档案列表
|
||||
@@ -156,10 +194,11 @@ export async function createProfile(name: string): Promise<ApiResponse<Profile>>
|
||||
}
|
||||
|
||||
// 更新档案
|
||||
// skin_id / cape_id: 显式传 null 表示移除当前皮肤的关联;传 number 表示设置;不传表示不修改。
|
||||
export async function updateProfile(uuid: string, data: {
|
||||
name?: string;
|
||||
skin_id?: number;
|
||||
cape_id?: number;
|
||||
skin_id?: number | null;
|
||||
cape_id?: number | null;
|
||||
}): Promise<ApiResponse<Profile>> {
|
||||
const response = await fetch(`${API_BASE_URL}/profile/${uuid}`, {
|
||||
method: 'PUT',
|
||||
@@ -180,16 +219,6 @@ export async function deleteProfile(uuid: string): Promise<ApiResponse<null>> {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 设置活跃档案
|
||||
export async function setActiveProfile(uuid: string): Promise<ApiResponse<{ message: string }>> {
|
||||
const response = await fetch(`${API_BASE_URL}/profile/${uuid}/activate`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
export async function getUserProfile(): Promise<ApiResponse<{
|
||||
id: number;
|
||||
@@ -264,23 +293,39 @@ export async function uploadTexture(file: File, data: {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 生成头像上传URL
|
||||
export async function generateAvatarUploadUrl(fileName: string): Promise<ApiResponse<{
|
||||
post_url: string;
|
||||
form_data: Record<string, string>;
|
||||
// 直接上传头像文件到后端(multipart/form-data)
|
||||
// 后端接口 POST /user/avatar/upload,由后端负责写入对象存储并更新用户头像
|
||||
export async function uploadAvatar(file: File): Promise<ApiResponse<{
|
||||
avatar_url: string;
|
||||
expires_in: number;
|
||||
user: {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
avatar: string;
|
||||
points: number;
|
||||
role: string;
|
||||
status: number;
|
||||
last_login_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
}>> {
|
||||
const response = await fetch(`${API_BASE_URL}/user/avatar/upload-url`, {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const token = typeof window !== 'undefined' ? localStorage.getItem('authToken') : null;
|
||||
const response = await fetch(`${API_BASE_URL}/user/avatar/upload`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({ file_name: fileName }),
|
||||
headers: {
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 更新头像URL
|
||||
// 更新头像URL(用于外部URL场景,区别于文件直传)
|
||||
export async function updateAvatarUrl(avatarUrl: string): Promise<ApiResponse<{
|
||||
id: number;
|
||||
username: string;
|
||||
@@ -323,3 +368,69 @@ export async function deleteTexture(id: number): Promise<ApiResponse<null>> {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 更新材质信息(名称、描述、公开性)
|
||||
// 对应后端 PUT /texture/{id}:is_public 为布尔值时会更新该字段,会影响公开/隐藏状态
|
||||
export async function updateTexture(id: number, data: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
is_public?: boolean;
|
||||
}): Promise<ApiResponse<Texture>> {
|
||||
const response = await fetch(`${API_BASE_URL}/texture/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 发送邮箱验证码
|
||||
// type: register | reset_password | change_email
|
||||
export async function sendVerificationCode(email: string, type: 'register' | 'reset_password' | 'change_email'): Promise<ApiResponse<null>> {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/send-code`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, type }),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 更换邮箱
|
||||
export async function changeEmail(newEmail: string, verificationCode: string): Promise<ApiResponse<{
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
avatar: string;
|
||||
points: number;
|
||||
role: string;
|
||||
status: number;
|
||||
last_login_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>> {
|
||||
const response = await fetch(`${API_BASE_URL}/user/change-email`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({ new_email: newEmail, verification_code: verificationCode }),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 重置密码(通过邮箱验证码)
|
||||
// 对应后端 POST /auth/reset-password,无需 JWT
|
||||
export async function resetPassword(email: string, verificationCode: string, newPassword: string): Promise<ApiResponse<null>> {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/reset-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
verification_code: verificationCode,
|
||||
new_password: newPassword,
|
||||
}),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user