forked from CarrotSkin/carrotskin
Compare commits
12 Commits
914ea7524b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 268344c357 | |||
|
|
fdd1d0c17b | ||
|
|
42c2fb4ce3 | ||
|
|
2e85be4657 | ||
|
|
dad28881ed | ||
|
|
0c6c0ae1ac | ||
|
|
2124790c8d | ||
| f5455afaf2 | |||
| eed6920d4a | |||
| 00984b6d67 | |||
| 344cae80af | |||
| 321b32e312 |
41
.dockerignore
Normal file
41
.dockerignore
Normal file
@@ -0,0 +1,41 @@
|
||||
# 依赖
|
||||
node_modules
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Next.js 构建产物
|
||||
.next
|
||||
out
|
||||
|
||||
# 测试
|
||||
coverage
|
||||
.nyc_output
|
||||
|
||||
# IDE
|
||||
.vscode
|
||||
.idea
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# 操作系统
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
|
||||
# 文档
|
||||
docs
|
||||
*.md
|
||||
|
||||
# 其他
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
85
.gitea/workflows/docker-build.yml
Normal file
85
.gitea/workflows/docker-build.yml
Normal file
@@ -0,0 +1,85 @@
|
||||
name: Build and Push Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
- develop
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: code.littlelan.cn
|
||||
IMAGE_NAME: carrotskin/carrotskin
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Log in to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Extract metadata for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
# main/master 分支标记为 latest
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
# 所有分支的标签
|
||||
type=ref,event=branch
|
||||
# Git tag 时创建版本标签(如 1.0.0, 1.0)
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
# 每次构建的 SHA 标签
|
||||
type=sha
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64
|
||||
provenance: false
|
||||
# 禁用 buildcache 以避免 413 错误
|
||||
# cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
|
||||
# cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max
|
||||
|
||||
- name: Show image tags
|
||||
run: |
|
||||
echo "Built and pushed image with tags:"
|
||||
echo "${{ steps.meta.outputs.tags }}"
|
||||
echo ""
|
||||
echo "Image digest: ${{ steps.meta.outputs.digest }}"
|
||||
|
||||
- name: Summary
|
||||
if: always()
|
||||
run: |
|
||||
echo "## Docker Image Build Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Image:** ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Tags:**" >> $GITHUB_STEP_SUMMARY
|
||||
echo "${{ steps.meta.outputs.tags }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Digest:** ${{ steps.meta.outputs.digest }}" >> $GITHUB_STEP_SUMMARY
|
||||
49
Dockerfile
Normal file
49
Dockerfile
Normal file
@@ -0,0 +1,49 @@
|
||||
# 构建阶段
|
||||
FROM node:alpine AS builder
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 复制 package 文件
|
||||
COPY package*.json ./
|
||||
|
||||
# 安装所有依赖(包括 devDependencies)
|
||||
RUN npm ci
|
||||
|
||||
# 复制源代码
|
||||
COPY . .
|
||||
|
||||
# 构建应用
|
||||
RUN npm run build
|
||||
|
||||
# 生产阶段
|
||||
FROM node:alpine AS runner
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 创建非 root 用户
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
|
||||
# 复制构建产物(standalone 模式)
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
COPY --from=builder /app/.next/static ./.next/static
|
||||
|
||||
# 设置正确的权限
|
||||
RUN chown -R nextjs:nodejs /app
|
||||
|
||||
# 切换到非 root 用户
|
||||
USER nextjs
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 3000
|
||||
|
||||
# 设置环境变量
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
# 启动应用
|
||||
CMD ["node", "server.js"]
|
||||
@@ -1,7 +1,15 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
output: 'standalone',
|
||||
rewrites: async () => {
|
||||
return [
|
||||
{
|
||||
source: '/api/v1/:path*',
|
||||
destination: 'http://localhost:8080/api/v1/:path*',
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
@@ -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);
|
||||
@@ -31,9 +39,27 @@ export default function AuthPage() {
|
||||
const [showCaptcha, setShowCaptcha] = useState(false);
|
||||
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,26 +156,15 @@ 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 sendVerificationCode(formData.email, 'register');
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.code === 200) {
|
||||
setCodeTimer(60);
|
||||
errorManager.showSuccess('验证码已发送到您的邮箱');
|
||||
@@ -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';
|
||||
@@ -282,23 +281,15 @@ export default function Home() {
|
||||
<p className="text-xl text-white/90 mb-8 max-w-2xl mx-auto font-light">
|
||||
加入CarrotSkin,体验新一代Minecraft皮肤管理平台,让你的创意无限绽放
|
||||
</p>
|
||||
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center">
|
||||
<Link
|
||||
href="/register"
|
||||
<Link
|
||||
href="/register"
|
||||
className="group bg-white text-orange-600 hover:bg-gray-100 font-bold py-4 px-8 rounded-2xl transition-all duration-300 inline-flex items-center space-x-2 shadow-2xl"
|
||||
>
|
||||
<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>
|
||||
|
||||
@@ -22,22 +22,24 @@ import {
|
||||
ArrowDownTrayIcon,
|
||||
ArrowLeftOnRectangleIcon
|
||||
} from '@heroicons/react/24/outline';
|
||||
import {
|
||||
getMyTextures,
|
||||
getFavoriteTextures,
|
||||
toggleFavorite,
|
||||
import {
|
||||
getMyTextures,
|
||||
getFavoriteTextures,
|
||||
toggleFavorite,
|
||||
getProfiles,
|
||||
createProfile,
|
||||
updateProfile,
|
||||
deleteProfile,
|
||||
setActiveProfile,
|
||||
getUserProfile,
|
||||
updateUserProfile,
|
||||
uploadTexture,
|
||||
getTexture,
|
||||
generateAvatarUploadUrl,
|
||||
updateAvatarUrl,
|
||||
uploadAvatar,
|
||||
resetYggdrasilPassword,
|
||||
deleteTexture,
|
||||
updateTexture,
|
||||
sendVerificationCode,
|
||||
changeEmail,
|
||||
type Texture,
|
||||
type Profile
|
||||
} from '@/lib/api';
|
||||
@@ -96,8 +98,15 @@ export default function ProfilePage() {
|
||||
const [yggdrasilPassword, setYggdrasilPassword] = useState<string>('');
|
||||
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(() => {
|
||||
@@ -178,23 +187,54 @@ export default function ProfilePage() {
|
||||
};
|
||||
|
||||
const handleToggleSkinVisibility = async (skinId: number) => {
|
||||
const skin = mySkins.find(s => s.id === skinId);
|
||||
if (!skin) return;
|
||||
|
||||
const newIsPublic = !skin.is_public;
|
||||
// 先乐观更新本地态,失败再回滚
|
||||
setMySkins(prev => prev.map(s =>
|
||||
s.id === skinId ? { ...s, is_public: newIsPublic } : s
|
||||
));
|
||||
|
||||
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 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 });
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteSkin = async (skinId: number) => {
|
||||
if (!confirm('确定要删除这个皮肤吗?')) return;
|
||||
|
||||
setMySkins(prev => prev.filter(skin => skin.id !== skinId));
|
||||
try {
|
||||
const response = await deleteTexture(skinId);
|
||||
if (response.code === 200) {
|
||||
setMySkins(prev => prev.filter(skin => skin.id !== skinId));
|
||||
messageManager.success('皮肤删除成功', { duration: 3000 });
|
||||
} else {
|
||||
messageManager.error(response.message || '删除皮肤失败', { duration: 3000 });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除皮肤失败:', error);
|
||||
messageManager.error('删除皮肤失败', { duration: 3000 });
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleFavorite = async (skinId: number) => {
|
||||
@@ -296,52 +336,31 @@ export default function ProfilePage() {
|
||||
|
||||
const handleUploadAvatar = async () => {
|
||||
if (!avatarFile) return;
|
||||
|
||||
|
||||
setIsUploadingAvatar(true);
|
||||
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) {
|
||||
console.error('头像上传失败:', error);
|
||||
messageManager.error(error instanceof Error ? error.message : '头像上传失败,请稍后重试', { duration: 3000 });
|
||||
@@ -373,12 +392,14 @@ export default function ProfilePage() {
|
||||
|
||||
const handleResetYggdrasilPassword = async () => {
|
||||
if (!confirm('确定要重置Yggdrasil密码吗?这将生成一个新的密码。')) return;
|
||||
|
||||
|
||||
setIsResettingYggdrasilPassword(true);
|
||||
|
||||
|
||||
try {
|
||||
const response = await resetYggdrasilPassword();
|
||||
if (response.code === 200) {
|
||||
setYggdrasilPassword(response.data.password);
|
||||
setShowYggdrasilPassword(true);
|
||||
messageManager.success('Yggdrasil密码重置成功!请妥善保管新密码。', { duration: 5000 });
|
||||
} else {
|
||||
throw new Error(response.message || '重置Yggdrasil密码失败');
|
||||
@@ -391,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 });
|
||||
@@ -434,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 });
|
||||
@@ -590,7 +672,6 @@ export default function ProfilePage() {
|
||||
onSave={handleEditCharacter}
|
||||
onCancel={onCancelEdit}
|
||||
onDelete={handleDeleteCharacter}
|
||||
onSetActive={handleSetActiveCharacter}
|
||||
onSelectSkin={setShowSkinSelector}
|
||||
onEditNameChange={setEditProfileName}
|
||||
/>
|
||||
@@ -833,10 +914,15 @@ export default function ProfilePage() {
|
||||
<span>账户操作</span>
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
<motion.button
|
||||
<motion.button
|
||||
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" />
|
||||
@@ -913,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 });
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: undefined } : p
|
||||
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 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
|
||||
));
|
||||
setProfileSkins(prev => {
|
||||
const newSkins = { ...prev };
|
||||
delete newSkins[currentProfile.uuid];
|
||||
return newSkins;
|
||||
});
|
||||
setShowSkinSelector(null);
|
||||
messageManager.error('移除皮肤失败,请稍后重试', { duration: 3000 });
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -934,35 +1036,50 @@ export default function ProfilePage() {
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">移除皮肤</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
|
||||
{availableSkins.map((skin) => (
|
||||
<motion.div
|
||||
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 });
|
||||
setProfiles(prev => prev.map(p =>
|
||||
p.uuid === currentProfile.uuid ? { ...p, skin_id: skin.id } : p
|
||||
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
|
||||
));
|
||||
setProfileSkins(prev => ({
|
||||
...prev,
|
||||
[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
|
||||
));
|
||||
setProfileSkins(prev => ({
|
||||
...prev,
|
||||
[currentProfile.uuid]: { url: skin.url, isSlim: skin.is_slim }
|
||||
}));
|
||||
setShowSkinSelector(null);
|
||||
messageManager.error('设置皮肤失败,请稍后重试', { duration: 3000 });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SkinViewer
|
||||
skinUrl={skin.url}
|
||||
isSlim={skin.is_slim}
|
||||
width={200}
|
||||
height={200}
|
||||
className="w-full h-full"
|
||||
autoRotate={false}
|
||||
/>
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<SkinViewer
|
||||
skinUrl={skin.url}
|
||||
isSlim={skin.is_slim}
|
||||
width={180}
|
||||
height={180}
|
||||
autoRotate={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-black/50 text-white text-xs p-2 text-center">
|
||||
{skin.name}
|
||||
</div>
|
||||
@@ -1128,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');
|
||||
}
|
||||
@@ -2,14 +2,15 @@
|
||||
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { usePathname, useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { useEffect, useState, useRef, Suspense } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
interface PageTransitionProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function PageTransition({ children }: PageTransitionProps) {
|
||||
// 内部组件:使用 useSearchParams 的部分
|
||||
function PageTransitionContent({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
@@ -96,13 +97,13 @@ export default function PageTransition({ children }: PageTransitionProps) {
|
||||
};
|
||||
|
||||
const getLoadingVariants = () => ({
|
||||
initial: {
|
||||
initial: {
|
||||
opacity: 0,
|
||||
scale: 0.8,
|
||||
y: 20
|
||||
},
|
||||
animate: {
|
||||
opacity: 1,
|
||||
animate: {
|
||||
opacity: 1,
|
||||
scale: 1,
|
||||
y: 0,
|
||||
transition: {
|
||||
@@ -133,17 +134,17 @@ export default function PageTransition({ children }: PageTransitionProps) {
|
||||
>
|
||||
<div className="text-center">
|
||||
<motion.div
|
||||
animate={{
|
||||
animate={{
|
||||
rotate: 360,
|
||||
scale: [1, 1.1, 1]
|
||||
}}
|
||||
transition={{
|
||||
transition={{
|
||||
rotate: { duration: 1, repeat: Infinity },
|
||||
scale: { duration: 1.5, repeat: Infinity }
|
||||
}}
|
||||
className="w-12 h-12 border-4 border-orange-500 border-t-transparent rounded-full mx-auto mb-4"
|
||||
/>
|
||||
<motion.p
|
||||
<motion.p
|
||||
className="text-lg font-medium text-gray-700 dark:text-gray-300"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
@@ -171,3 +172,20 @@ export default function PageTransition({ children }: PageTransitionProps) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// 加载状态组件
|
||||
function PageTransitionFallback() {
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
{null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PageTransition({ children }: PageTransitionProps) {
|
||||
return (
|
||||
<Suspense fallback={<PageTransitionFallback />}>
|
||||
<PageTransitionContent>{children}</PageTransitionContent>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -171,15 +171,15 @@ export default function SkinCard({
|
||||
</AnimatePresence>
|
||||
|
||||
{texture.type === 'SKIN' ? (
|
||||
<div className="relative w-full h-full bg-white dark:bg-gray-800">
|
||||
<div className="relative w-full h-full flex items-center justify-center bg-white dark:bg-gray-800">
|
||||
<SkinViewer
|
||||
skinUrl={texture.url}
|
||||
isSlim={texture.is_slim}
|
||||
width={300}
|
||||
height={300}
|
||||
className={`w-full h-full transition-all duration-500 ${
|
||||
imageLoaded ? 'opacity-100 scale-100' : 'opacity-0 scale-95'
|
||||
} ${isHovered ? 'scale-110' : ''}`}
|
||||
width={280}
|
||||
height={280}
|
||||
className={`transition-opacity duration-500 ${
|
||||
imageLoaded ? 'opacity-100' : 'opacity-0'
|
||||
}`}
|
||||
autoRotate={isHovered}
|
||||
walking={false}
|
||||
onImageLoaded={() => setImageLoaded(true)}
|
||||
|
||||
@@ -296,7 +296,7 @@ export default function SkinDetailModal({ isOpen, onClose, texture, isExternalPr
|
||||
isSlim={texture.is_slim}
|
||||
width={600}
|
||||
height={600}
|
||||
className="w-full h-full rounded-2xl shadow-2xl border-2 border-white/60 dark:border-gray-600/60 relative z-10"
|
||||
className="rounded-2xl shadow-2xl border-2 border-white/60 dark:border-gray-600/60 relative z-10"
|
||||
autoRotate={autoRotate}
|
||||
walking={currentAnimation === 'walking'}
|
||||
running={currentAnimation === 'running'}
|
||||
|
||||
@@ -83,28 +83,24 @@ export default function SkinViewer({
|
||||
try {
|
||||
console.log('初始化3D皮肤查看器:', { skinUrl, isSlim, width, height });
|
||||
|
||||
// 使用canvas的实际尺寸,参考blessingskin
|
||||
// 使用传入的宽高参数初始化
|
||||
const canvas = canvasRef.current;
|
||||
const viewer = new SkinViewer3D({
|
||||
canvas: canvas,
|
||||
width: canvas.clientWidth || width,
|
||||
height: canvas.clientHeight || height,
|
||||
width: width,
|
||||
height: height,
|
||||
skin: skinUrl,
|
||||
cape: capeUrl,
|
||||
model: isSlim ? 'slim' : 'default',
|
||||
zoom: 1.0, // 使用blessingskin的zoom方式
|
||||
zoom: 1.0,
|
||||
});
|
||||
|
||||
viewerRef.current = viewer;
|
||||
|
||||
// 设置背景和控制选项 - 参考blessingskin
|
||||
// 设置背景和控制选项
|
||||
viewer.background = null; // 透明背景
|
||||
viewer.autoRotate = false; // 完全禁用自动旋转
|
||||
|
||||
// 调整光照设置,避免皮肤发黑
|
||||
viewer.globalLight.intensity = 0.8; // 增加环境光强度
|
||||
viewer.cameraLight.intensity = 0.4; // 降低相机光源强度,避免过强的阴影
|
||||
|
||||
// 外部预览时禁用所有动画和旋转
|
||||
if (isExternalPreview) {
|
||||
viewer.autoRotate = false;
|
||||
@@ -268,11 +264,8 @@ export default function SkinViewer({
|
||||
ref={canvasRef}
|
||||
className={className}
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
height: '100%'
|
||||
width: width,
|
||||
height: height
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -76,18 +76,19 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
const response = await axios.get(`${API_BASE_URL}/captcha/generate`, {
|
||||
withCredentials: true // 关键:允许跨域携带凭证
|
||||
});
|
||||
const { code, msg: resMsg, captcha_id, mBase64, tBase64, y } = response.data;
|
||||
const { code, msg: resMsg, data } = response.data;
|
||||
const { masterImage, tileImage, captchaId, y } = data;
|
||||
|
||||
// 后端返回成功状态(code=200)
|
||||
if (code === 200) {
|
||||
// 设置背景图
|
||||
setBackgroundImage(mBase64);
|
||||
setBackgroundImage(masterImage);
|
||||
// 设置拼图图片
|
||||
setPuzzleImage(tBase64);
|
||||
setPuzzleImage(tileImage);
|
||||
// 设置拼图y坐标(从后端获取,以背景图左上角为原点)
|
||||
setPuzzleY(y);
|
||||
// 设置进程ID(用于后续验证)
|
||||
setProcessId(captcha_id);
|
||||
setProcessId(captchaId);
|
||||
// 随机生成拼图x坐标(确保拼图在背景图内)
|
||||
// setPuzzlePosition(Math.random() * (CANVAS_WIDTH - 50 - 50) + 50);
|
||||
// 保存后端返回的提示信息
|
||||
@@ -163,47 +164,59 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
|
||||
try {
|
||||
// 向后端发送验证请求,参数为滑块位置(x坐标)和进程ID
|
||||
// 使用sliderPosition作为dx值,这是拼图块左上角的位置
|
||||
const response = await axios.post(`${API_BASE_URL}/captcha/verify`, {
|
||||
dx: sliderPosition, // 滑块位置(拼图左上角x坐标,以背景图左上角为原点)
|
||||
captcha_id: processId // 验证码进程ID
|
||||
captchaId: processId // 验证码进程ID
|
||||
},{ withCredentials: true });
|
||||
|
||||
const { code, msg: resMsg, data } = response.data;
|
||||
// 保存后端返回的提示信息
|
||||
setMsg(resMsg);
|
||||
|
||||
// 后端返回成功 (code=200)
|
||||
// 根据后端返回的code判断验证结果
|
||||
// 验证成功:code=200
|
||||
if (code === 200) {
|
||||
// 验证成功(data=true)
|
||||
if (data === true) {
|
||||
setIsVerified(true);
|
||||
setVerifyResult(true);
|
||||
// 延迟1.2秒后调用验证成功回调
|
||||
setTimeout(() => onVerify(true), 1200);
|
||||
}
|
||||
// 验证失败(data=false)
|
||||
else {
|
||||
setVerifyResult(false);
|
||||
setShowError(true);
|
||||
// 增加尝试次数
|
||||
setAttempts(prev => prev + 1);
|
||||
// 1.5秒后重置滑块位置并隐藏错误提示
|
||||
setTimeout(() => {
|
||||
setSliderPosition(0);
|
||||
setShowError(false);
|
||||
}, 1500);
|
||||
}
|
||||
}
|
||||
// 后端返回参数错误(400)或系统错误(500)
|
||||
else if (code === 400 || code === 500) {
|
||||
setVerifyResult('error');
|
||||
setShowError(true);
|
||||
// 增加尝试次数
|
||||
setAttempts(prev => prev + 1);
|
||||
// 1.5秒后重置滑块位置并隐藏错误提示
|
||||
// 重置所有状态,确保验证成功状态的纯净性
|
||||
setShowError(false);
|
||||
setVerifyResult(false);
|
||||
// 直接设置验证成功状态,不使用异步更新
|
||||
setIsVerified(true);
|
||||
// 延迟1.2秒后调用验证成功回调,透传后端返回的 captchaId 供注册接口使用
|
||||
setTimeout(() => onVerify(true, processId), 1200);
|
||||
}
|
||||
// 验证失败:code=400
|
||||
else if (code === 400) {
|
||||
// 确保错误状态的正确性:验证失败显示红色
|
||||
setVerifyResult(false);
|
||||
setShowError(true);
|
||||
setIsVerified(false);
|
||||
// 增加尝试次数
|
||||
setAttempts(prev => prev + 1);
|
||||
// 1.5秒后重置滑块位置、隐藏错误提示并重置验证结果
|
||||
setTimeout(() => {
|
||||
setSliderPosition(0);
|
||||
setShowError(false);
|
||||
setVerifyResult(false);
|
||||
setIsVerified(false);
|
||||
}, 1500);
|
||||
}
|
||||
// 后端返回系统错误(500)
|
||||
else if (code === 500) {
|
||||
// 系统错误显示橙色
|
||||
setVerifyResult('error');
|
||||
setShowError(true);
|
||||
setIsVerified(false);
|
||||
// 增加尝试次数
|
||||
setAttempts(prev => prev + 1);
|
||||
// 1.5秒后重置滑块位置、隐藏错误提示并重置验证结果
|
||||
setTimeout(() => {
|
||||
setSliderPosition(0);
|
||||
setShowError(false);
|
||||
setVerifyResult(false);
|
||||
setIsVerified(false);
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
@@ -318,12 +331,12 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
// 加载中显示旋转动画
|
||||
return <div className="w-5 h-5 border-2 border-blue-300 border-t-blue-600 rounded-full animate-spin" />;
|
||||
}
|
||||
// 验证成功时,无论其他状态如何,都显示对勾图标
|
||||
if (isVerified) {
|
||||
// 验证成功显示对勾图标
|
||||
return <Check className="w-5 h-5 text-green-600" />;
|
||||
}
|
||||
if (showError) {
|
||||
// 验证失败显示叉号图标
|
||||
// 验证失败或错误时显示叉号图标
|
||||
if (showError || verifyResult === 'error') {
|
||||
return <X className="w-5 h-5 text-red-600" />;
|
||||
}
|
||||
// 默认显示蓝色圆点
|
||||
@@ -332,8 +345,12 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
|
||||
|
||||
const getStatusText = () => {
|
||||
if (verifyResult === 'error' || showError || isVerified) {
|
||||
// 错误、验证失败或成功时显示后端返回的消息
|
||||
if (isVerified) {
|
||||
// 验证成功时优先显示成功消息
|
||||
return msg;
|
||||
}
|
||||
if (verifyResult === 'error' || showError) {
|
||||
// 错误或验证失败时显示后端返回的消息
|
||||
return msg;
|
||||
}
|
||||
// 默认显示拖拽提示
|
||||
@@ -342,17 +359,21 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
|
||||
|
||||
const getStatusColor = () => {
|
||||
if (verifyResult === 'error') return 'text-orange-700';
|
||||
if (isVerified) return 'text-green-700';
|
||||
if (verifyResult === 'error') return 'text-orange-700';
|
||||
if (showError) return 'text-red-700';
|
||||
return 'text-gray-600';
|
||||
};
|
||||
|
||||
|
||||
const getProgressColor = () => {
|
||||
if (verifyResult === 'error') return 'bg-gradient-to-r from-orange-400 to-orange-500';
|
||||
// 验证成功时,无论其他状态如何,都显示绿色渐变
|
||||
if (isVerified) return 'bg-gradient-to-r from-green-400 to-green-500';
|
||||
if (showError) return 'bg-gradient-to-r from-red-400 to-red-500';
|
||||
// 系统错误(后端返回400/500)显示橙色渐变
|
||||
if (verifyResult === 'error') return 'bg-gradient-to-r from-orange-400 to-orange-500';
|
||||
// 验证失败(后端返回200但data=false)显示红色渐变
|
||||
if (showError && verifyResult !== 'error') return 'bg-gradient-to-r from-red-400 to-red-500';
|
||||
// 默认显示蓝色渐变
|
||||
return 'bg-gradient-to-r from-blue-400 to-blue-500';
|
||||
};
|
||||
|
||||
@@ -386,9 +407,9 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
/>
|
||||
)}
|
||||
{/* 可移动拼图块 */}
|
||||
{puzzleImage && !isVerified && (
|
||||
{puzzleImage && (
|
||||
<div
|
||||
className="absolute transition-all duration-300"
|
||||
className={`absolute ${isDragging ? '' : 'transition-all duration-300'}`}
|
||||
style={{
|
||||
left: `${sliderPosition}px`, // 滑块x位置(拼图左上角x坐标)
|
||||
top: `${puzzleY}px`, // 拼图y位置(从后端获取,拼图左上角y坐标)
|
||||
@@ -400,7 +421,6 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
alt="拼图块"
|
||||
className={`${isVerified ? 'opacity-100' : 'opacity-90'}`}
|
||||
style={{
|
||||
|
||||
filter: isVerified ? 'drop-shadow(0 0 10px rgba(34, 197, 94, 0.5))' : 'drop-shadow(0 2px 4px rgba(0,0,0,0.3))'
|
||||
}}
|
||||
/>
|
||||
@@ -415,7 +435,7 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
<div className="relative bg-gray-100 rounded-full h-12 overflow-hidden select-none" ref={trackRef} style={{ width: `${TRACK_WIDTH}px`, margin: '0 auto' }}>
|
||||
{/* 进度条 */}
|
||||
<div
|
||||
className={`absolute left-0 top-0 h-full transition-all duration-200 ease-out ${getProgressColor()}`}
|
||||
className={`absolute left-0 top-0 h-full ${isDragging ? '' : 'transition-all duration-200 ease-out'} ${getProgressColor()}`}
|
||||
style={{
|
||||
width: `${sliderPosition + SLIDER_WIDTH}px`,
|
||||
transform: isDragging ? 'scaleY(1.05)' : 'scaleY(1)',
|
||||
@@ -424,14 +444,13 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
/>
|
||||
{/* 滑块按钮 */}
|
||||
<div
|
||||
className={`absolute top-1 w-10 h-10 bg-white rounded-full shadow-lg cursor-pointer flex items-center justify-center transition-all duration-200 ease-out select-none ${
|
||||
className={`absolute top-1 w-10 h-10 bg-white rounded-full shadow-lg cursor-pointer flex items-center justify-center ${isDragging ? '' : 'transition-all duration-200 ease-out'} select-none ${
|
||||
isDragging ? 'scale-110 shadow-xl' : 'scale-100'
|
||||
} ${isVerified || verifyResult === 'error' ? 'cursor-default' : 'cursor-grab active:cursor-grabbing'}`}
|
||||
style={{ left: `${sliderPosition + 2}px`, zIndex: 10 }}
|
||||
onMouseDown={handleMouseDown}
|
||||
onTouchStart={handleTouchStart}
|
||||
onMouseDown={verifyResult === 'error' ? undefined : handleMouseDown}
|
||||
onTouchStart={verifyResult === 'error' ? undefined : handleTouchStart}
|
||||
ref={sliderRef}
|
||||
disabled={verifyResult === 'error'}
|
||||
>
|
||||
{getSliderIcon()}
|
||||
</div>
|
||||
@@ -450,7 +469,7 @@ export const SliderCaptcha: React.FC<SliderCaptchaProps> = ({ onVerify, onClose
|
||||
{/* 底部信息区域 */}
|
||||
<div className="px-6 pb-6">
|
||||
<div className="flex items-center justify-between text-xs text-gray-500">
|
||||
<span>尝试次数: {attempts + 1}/5</span>
|
||||
<span>尝试次数: {attempts}</span>
|
||||
<span className="flex items-center space-x-1">
|
||||
<Shield className="w-3 h-3" />
|
||||
<span>安全验证</span>
|
||||
|
||||
@@ -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) {
|
||||
@@ -42,25 +40,32 @@ export default function CharacterCard({
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => onEditNameChange(e.target.value)}
|
||||
className="text-lg font-semibold bg-transparent border-b border-orange-500 focus:outline-none text-gray-900 dark:text-white flex-1 mr-2"
|
||||
onBlur={() => onSave(profile.uuid)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && onSave(profile.uuid)}
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white truncate flex-1">{profile.name}</h3>
|
||||
)}
|
||||
{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 className="flex items-center gap-2 flex-1">
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => onEditNameChange(e.target.value)}
|
||||
className="text-lg font-semibold bg-transparent border-b border-orange-500 focus:outline-none text-gray-900 dark:text-white flex-1"
|
||||
onBlur={() => onSave(profile.uuid)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && onSave(profile.uuid)}
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white truncate">{profile.name}</h3>
|
||||
<motion.button
|
||||
onClick={() => onEdit(profile.uuid, profile.name)}
|
||||
className="text-gray-500 hover:text-orange-500 transition-colors"
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
title="改名"
|
||||
>
|
||||
<PencilIcon className="w-4 h-4" />
|
||||
</motion.button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</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">
|
||||
@@ -68,9 +73,8 @@ export default function CharacterCard({
|
||||
<SkinViewer
|
||||
skinUrl={skinUrl}
|
||||
isSlim={isSlim}
|
||||
width={200}
|
||||
height={200}
|
||||
className="w-full h-full"
|
||||
width={180}
|
||||
height={180}
|
||||
autoRotate={false}
|
||||
/>
|
||||
) : (
|
||||
@@ -82,32 +86,10 @@ export default function CharacterCard({
|
||||
<UserIcon className="w-10 h-10 text-white" />
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 皮肤选择按钮 */}
|
||||
<motion.button
|
||||
onClick={() => onSelectSkin(profile.uuid)}
|
||||
className="absolute bottom-2 right-2 bg-gradient-to-r from-orange-500 to-amber-500 text-white p-2 rounded-full shadow-lg"
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
title="选择皮肤"
|
||||
>
|
||||
<PencilIcon className="w-4 h-4" />
|
||||
</motion.button>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="flex gap-2">
|
||||
{!profile.is_active && (
|
||||
<motion.button
|
||||
onClick={() => onSetActive(profile.uuid)}
|
||||
className="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white text-sm py-2 px-3 rounded-lg transition-all duration-200"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
使用
|
||||
</motion.button>
|
||||
)}
|
||||
|
||||
{isEditing ? (
|
||||
<>
|
||||
<motion.button
|
||||
@@ -130,13 +112,12 @@ export default function CharacterCard({
|
||||
) : (
|
||||
<>
|
||||
<motion.button
|
||||
onClick={() => onEdit(profile.uuid, profile.name)}
|
||||
className="flex-1 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm py-2 px-3 rounded-lg transition-all duration-200"
|
||||
onClick={() => onSelectSkin(profile.uuid)}
|
||||
className="flex-1 bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white text-sm py-2 px-3 rounded-lg transition-all duration-200"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<PencilIcon className="w-4 h-4 inline mr-1" />
|
||||
编辑
|
||||
修改皮肤
|
||||
</motion.button>
|
||||
<motion.button
|
||||
onClick={() => onDelete(profile.uuid)}
|
||||
|
||||
@@ -68,7 +68,6 @@ export default function MySkinsTab({
|
||||
key={skin.id}
|
||||
texture={skin}
|
||||
onViewDetails={handleViewDetails}
|
||||
onToggleVisibility={onToggleVisibility}
|
||||
customActions={
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
|
||||
@@ -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;
|
||||
@@ -22,14 +23,12 @@ interface AuthContextType {
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
register: (username: string, email: string, password: string, verificationCode: string) => Promise<void>;
|
||||
register: (username: string, email: string, password: string, verificationCode: string, captchaId?: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
updateUser: (userData: Partial<User>) => void;
|
||||
refreshUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
const API_BASE_URL = 'http://localhost:8080/api/v1';
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
@@ -106,7 +105,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (username: string, email: string, password: string, verificationCode: string) => {
|
||||
const register = async (username: string, email: string, password: string, verificationCode: string, captchaId?: string) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/register`, {
|
||||
@@ -119,6 +118,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
email,
|
||||
password,
|
||||
verification_code: verificationCode,
|
||||
...(captchaId && { captcha_id: captchaId }),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
173
src/lib/api.ts
173
src/lib/api.ts
@@ -1,4 +1,4 @@
|
||||
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080/api/v1';
|
||||
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || '/api/v1';
|
||||
|
||||
export interface Texture {
|
||||
id: number;
|
||||
@@ -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;
|
||||
@@ -313,3 +358,79 @@ export async function resetYggdrasilPassword(): Promise<ApiResponse<{
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 删除材质
|
||||
export async function deleteTexture(id: number): Promise<ApiResponse<null>> {
|
||||
const response = await fetch(`${API_BASE_URL}/texture/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
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