一些问题的修复

This commit is contained in:
xiaowang
2026-03-19 14:10:59 +08:00
parent 580a89c64d
commit 3527e248d1
50 changed files with 847 additions and 165 deletions
+3
View File
@@ -368,3 +368,6 @@ buildNumber.properties
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Local Maven repository used for sandbox compile verification
m2repo/
+18
View File
@@ -1,5 +1,9 @@
import api from './index'
export interface SendVerificationCodeRequest {
phone: string
}
export interface LoginRequest {
account: string
password: string
@@ -48,7 +52,17 @@ export interface RefreshTokenResponse {
refreshToken: string
}
export interface ResetPasswordRequest {
phone: string
verificationCode: string
newPassword: string
}
export const authApi = {
sendVerificationCode: (data: SendVerificationCodeRequest) => {
return api.post('/user/send-verification-code', data)
},
login: (data: LoginRequest) => {
return api.post<LoginResponse>('/user/login', data)
},
@@ -75,5 +89,9 @@ export const authApi = {
getUserInfo: () => {
return api.get<UserInfo>('/user/info')
},
resetPasswordByPhone: (data: ResetPasswordRequest) => {
return api.post('/user/reset-password-by-phone', data)
}
}
+5
View File
@@ -16,6 +16,11 @@ export const cartApi = {
return api.delete(`/cart/remove/${productId}`)
},
// 批量从购物车移除作品
batchRemoveFromCart: (cartItemIds: number[]) => {
return api.post('/cart/batch-remove', cartItemIds)
},
// 更新购物车作品数量
updateCartQuantity: (item: CartItem) => {
return api.put('/cart/update', item)
+12 -1
View File
@@ -1,8 +1,14 @@
import api from './index'
interface OrderItem {
productId: number
quantity: number
artistId?: number
}
interface CreateOrderRequest {
couponId?: number
artistId?: number
items: OrderItem[]
}
export const orderApi = {
@@ -36,5 +42,10 @@ export const orderApi = {
return api.put(`/order/admin/process/${orderId}`, {}, {
params: { status }
})
},
// 美甲师查看自己的订单
getArtistOrders: () => {
return api.get('/order/artist/list')
}
}
+6
View File
@@ -57,6 +57,12 @@ const router = createRouter({
component: () => import('../views/OrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/artist-orders',
name: 'artist-orders',
component: () => import('../views/ArtistOrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:artist:view' }
},
{
path: '/settings',
name: 'settings',
@@ -340,6 +340,12 @@ const handleSendVerificationCode = async () => {
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(bindPhoneForm.phone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: bindPhoneForm.phone })
message.success('验证码发送成功')
@@ -357,6 +363,12 @@ const handleSendChangePhoneVerificationCode = async () => {
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(changePhoneForm.newPhone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: changePhoneForm.newPhone })
message.success('验证码发送成功')
@@ -374,6 +386,12 @@ const handleSendChangePasswordVerificationCode = async () => {
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(userInfo.value.phone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: userInfo.value.phone })
message.success('验证码发送成功')
+169 -5
View File
@@ -303,6 +303,85 @@
</div>
</a-form>
</div>
<!-- 忘记密码弹窗 -->
<a-modal
v-model:visible="forgotPasswordVisible"
title="忘记密码"
:footer="null"
width="90%"
:destroyOnClose="true"
>
<a-form
:model="forgotPasswordForm"
:rules="forgotPasswordRules"
@finish="handleResetPassword"
layout="vertical"
>
<a-form-item name="phone" label="手机号">
<a-input
v-model:value="forgotPasswordForm.phone"
placeholder="请输入绑定的手机号"
size="large"
>
<template #prefix>
<UserOutlined style="color: #999" />
</template>
</a-input>
</a-form-item>
<a-form-item name="verificationCode" label="验证码">
<a-input
v-model:value="forgotPasswordForm.verificationCode"
placeholder="请输入验证码"
size="large"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
<template #suffix>
<a-button
type="link"
:disabled="forgotCountdown > 0 || !forgotPasswordForm.phone"
@click="handleSendForgotCode"
>
{{ forgotCountdown > 0 ? `${forgotCountdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item name="newPassword" label="新密码">
<a-input-password
v-model:value="forgotPasswordForm.newPassword"
placeholder="请输入新密码"
size="large"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
</a-input-password>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
block
:loading="resettingPassword"
>
重置密码
</a-button>
</a-form-item>
<a-form-item>
<a-button size="large" block @click="forgotPasswordVisible = false">
取消
</a-button>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
@@ -327,6 +406,16 @@ const accountStatus = ref<any>(null)
const phoneUserStatus = ref<any>(null)
const countdown = ref(0)
const forgotPasswordVisible = ref(false)
const forgotCountdown = ref(0)
const resettingPassword = ref(false)
const forgotPasswordForm = reactive({
phone: '',
verificationCode: '',
newPassword: ''
})
const formData = reactive({
account: '',
password: '',
@@ -342,6 +431,14 @@ const validatePassword = async (_rule: any, value: string) => {
if (value.length < 6) {
return Promise.reject('密码长度不能少于6位')
}
let count = 0
if (/\d/.test(value)) count++
if (/[a-z]/.test(value)) count++
if (/[A-Z]/.test(value)) count++
if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) count++
if (count < 3) {
return Promise.reject('密码必须包含数字、小写字母、大写字母和符号中的至少3种')
}
return Promise.resolve()
}
@@ -357,9 +454,7 @@ const validateConfirmPassword = async (_rule: any, value: string) => {
const rules: Record<string, Rule[]> = {
account: [
{ required: true, message: '请输入账号', trigger: 'blur' },
{ min: 3, max: 50, message: '账号长度在3到50个字符', trigger: 'blur' },
{ pattern: /^[a-zA-Z0-9_\-@.]+$/, message: '账号只能包含数字、字母、下划线、连字符、@和点号', trigger: 'blur' }
{ required: true, message: '请输入账号', trigger: 'blur' }
],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
@@ -379,13 +474,28 @@ const rules: Record<string, Rule[]> = {
],
nickname: [
{ required: true, message: '请输入昵称', trigger: 'blur' },
{ min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur' }
{ min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur' },
{ pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/, message: '昵称不能包含特殊符号', trigger: 'blur' }
],
shopId: [
{ required: true, message: '请选择店铺', trigger: 'change' }
]
}
const forgotPasswordRules: Record<string, Rule[]> = {
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
],
verificationCode: [
{ required: true, message: '请输入验证码', trigger: 'blur' },
{ pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
],
newPassword: [
{ required: true, message: '请输入新密码', trigger: 'blur' }
]
}
const fetchShops = async () => {
loadingShops.value = true
try {
@@ -474,7 +584,55 @@ const handleSubmit = async () => {
}
const handleForgotPassword = () => {
message.info('忘记密码功能开发中')
forgotPasswordVisible.value = true
}
const handleSendForgotCode = async () => {
if (!forgotPasswordForm.phone) {
message.error('请输入手机号')
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(forgotPasswordForm.phone)) {
message.error('手机号格式不正确')
return
}
try {
await authApi.sendVerificationCode({ phone: forgotPasswordForm.phone })
message.success('验证码已发送')
forgotCountdown.value = 60
const timer = setInterval(() => {
forgotCountdown.value--
if (forgotCountdown.value <= 0) {
clearInterval(timer)
}
}, 1000)
} catch (error: any) {
message.error(error.response?.data?.message || '发送验证码失败')
}
}
const handleResetPassword = async () => {
resettingPassword.value = true
try {
await authApi.resetPasswordByPhone({
phone: forgotPasswordForm.phone,
verificationCode: forgotPasswordForm.verificationCode,
newPassword: forgotPasswordForm.newPassword
})
message.success('密码重置成功,请使用新密码登录')
forgotPasswordVisible.value = false
forgotPasswordForm.phone = ''
forgotPasswordForm.verificationCode = ''
forgotPasswordForm.newPassword = ''
} catch (error: any) {
message.error(error.response?.data?.message || '重置密码失败')
} finally {
resettingPassword.value = false
}
}
const handleWeChatLogin = () => {
@@ -542,6 +700,12 @@ const handleSendVerificationCode = async () => {
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(formData.phone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: formData.phone })
message.success('验证码已发送')
+144 -58
View File
@@ -42,6 +42,18 @@
<h3 class="item-name" @click="handleProductClick(item)" style="cursor: pointer;">{{ item.productTitle }}</h3>
<p class="item-price">¥{{ item.price.toFixed(2) }}</p>
<!-- 美甲师选择 -->
<div class="artist-selector" @click="showArtistSelection(item)">
<span v-if="item.artist" class="selected-artist">
<img v-if="item.artist.avatar" :src="item.artist.avatar" class="artist-avatar-small" />
<span class="artist-name">{{ item.artist.name }}</span>
</span>
<span v-else class="select-artist">
选择美甲师
</span>
<RightOutlined class="arrow-icon" />
</div>
<!-- 数量控制和删除按钮 -->
<div class="item-actions">
<div class="quantity-control">
@@ -83,7 +95,7 @@
<div class="coupon-header" @click="showCouponModal = true">
<span class="coupon-title">优惠券</span>
<div class="coupon-value">
{{ selectedCoupon ? '已选择: ' + selectedCoupon.couponName : '请选择' }}
{{ selectedCoupon ? selectedCoupon.couponName : '使用优惠券' }}
<RightOutlined :style="{ marginLeft: '4px' }" />
</div>
</div>
@@ -122,14 +134,14 @@
block
@click="handleCheckout"
>
结算 ({{ selectedCount }}) - ¥{{ totalAmount.toFixed(2) }}
确认 {{ selectedCount }} 笔订单- 预计金额 ¥{{ totalAmount.toFixed(2) }}
</a-button>
</div>
<!-- 优惠券选择弹窗 -->
<a-modal
v-model:visible="showCouponModal"
title="选择优惠券"
title="使用优惠券"
width="90%"
@ok="confirmCouponSelection"
@cancel="cancelCouponSelection"
@@ -192,11 +204,10 @@
<!-- 美甲师选择弹窗 -->
<a-modal
v-model:visible="showArtistModal"
title="选择美甲师"
:title='currentEditingItem ? `为"${currentEditingItem.productTitle}"选择美甲师` : "选择美甲师"'
width="90%"
@ok="selectArtistAndCheckout"
@ok="confirmArtistSelection"
@cancel="closeArtistModal"
>
<div class="artist-modal-content">
<a-empty v-if="availableArtists.length === 0" description="暂无可用美甲师" />
@@ -206,8 +217,8 @@
v-for="artist in availableArtists"
:key="artist.id"
class="artist-item"
:class="{ 'selected': selectedArtist && selectedArtist.id === artist.id }"
@click="toggleArtistSelection(artist)"
:class="{ 'selected': currentEditingItem && currentEditingItem.artistId === artist.id }"
@click="selectArtist(artist)"
>
<div class="artist-card">
<div class="artist-avatar">
@@ -238,7 +249,7 @@
<span class="skill-tag" v-for="skill in getArtistSkills(artist)" :key="skill">{{ skill }}</span>
</div>
</div>
<div class="artist-selection-indicator" v-if="selectedArtist && selectedArtist.id === artist.id">
<div class="artist-selection-indicator" v-if="currentEditingItem && currentEditingItem.artistId === artist.id">
<CheckCircleOutlined style="color: #1890ff; font-size: 20px;" />
</div>
</div>
@@ -283,6 +294,18 @@ interface CartItem {
totalPrice: number
tags: string
selected: boolean
artistId?: number
artist?: {
id: number
name: string
avatar?: string
signature?: string
shopName?: string
status?: number
experience?: number
skills?: string
rating?: number
}
}
const router = useRouter()
@@ -516,7 +539,7 @@ const cancelCouponSelection = () => {
// 美甲师选择相关状态
const showArtistModal = ref(false)
const selectedArtist = ref<{id: number, name: string, avatar?: string, signature?: string, shopName?: string, status?: number, experience?: number, skills?: string, rating?: number} | null>(null)
const currentEditingItem = ref<CartItem | null>(null)
const availableArtists = ref<{id: number, name: string, avatar?: string, signature?: string, shopName?: string, status?: number, experience?: number, skills?: string, rating?: number}[]>([])
// 标签列表
const tagList = ref<TagVO[]>([])
@@ -592,28 +615,30 @@ const handleCheckout = async () => {
return
}
// 加载可用美甲师
await loadAvailableArtists()
// 显示美甲师选择弹窗
showArtistModal.value = true
}
// 选择美甲师并创建订单
const selectArtistAndCheckout = async () => {
if (!selectedArtist.value) {
message.warning('请选择美甲师')
// 检查所有选中的作品是否都选择了美甲师
const itemsWithoutArtist = selectedItems.filter(item => !item.artistId)
if (itemsWithoutArtist.length > 0) {
message.warning(`请为"${itemsWithoutArtist.map(item => item.productTitle).join('、')}"选择美甲师`)
return
}
// 创建订单
try {
await orderApi.createOrder({
couponId: selectedCoupon.value ? selectedCoupon.value.id : undefined,
artistId: selectedArtist.value.id
items: selectedItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId
}))
})
message.success('订单创建成功')
showArtistModal.value = false
// 更新购物车数量(因为订单创建后购物车会被清空)
// 从购物车中移除已购买的商品
const selectedIds = selectedItems.map(item => item.id)
await cartApi.batchRemoveFromCart(selectedIds)
// 更新购物车数据
await loadCartItems()
// 更新购物车数量
await updateCartCount()
router.push('/profile')
} catch (error) {
@@ -621,10 +646,31 @@ const selectArtistAndCheckout = async () => {
}
}
// 显示美甲师选择弹窗
const showArtistSelection = (item: CartItem) => {
currentEditingItem.value = item
loadAvailableArtists()
showArtistModal.value = true
}
// 选择美甲师
const selectArtist = (artist: any) => {
if (currentEditingItem.value) {
currentEditingItem.value.artistId = artist.id
currentEditingItem.value.artist = artist
}
}
// 确认选择
const confirmArtistSelection = () => {
showArtistModal.value = false
currentEditingItem.value = null
}
// 关闭美甲师选择弹窗
const closeArtistModal = () => {
showArtistModal.value = false
selectedArtist.value = null
currentEditingItem.value = null
}
// 获取美甲师头像
@@ -670,17 +716,6 @@ const getArtistSkills = (artist: any) => {
})
}
// 切换美甲师选择状态
const toggleArtistSelection = (artist: any) => {
if (selectedArtist.value && selectedArtist.value.id === artist.id) {
// 取消选择
selectedArtist.value = null
} else {
// 选择新的美甲师
selectedArtist.value = artist
}
}
// 监听选中作品变化,重新加载可用优惠券
watch(
() => cartItems.value.map(item => ({ id: item.id, selected: item.selected, quantity: item.quantity })),
@@ -807,6 +842,55 @@ onMounted(() => {
font-size: 16px;
}
.artist-selector {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background: #f8f9ff;
border-radius: 8px;
margin-bottom: 10px;
cursor: pointer;
transition: all 0.3s ease;
}
.artist-selector:hover {
background: #e6f7ff;
}
.selected-artist {
display: flex;
align-items: center;
gap: 8px;
color: #1890ff;
font-weight: 500;
}
.artist-avatar-small {
width: 24px;
height: 24px;
border-radius: 50%;
object-fit: cover;
}
.select-artist {
color: #999;
font-size: 13px;
display: flex;
align-items: center;
gap: 4px;
}
.arrow-icon {
color: #999;
font-size: 12px;
transition: transform 0.3s ease;
}
.artist-selector:hover .arrow-icon {
transform: translateX(4px);
}
.item-duration {
color: #666;
font-size: 13px;
@@ -907,7 +991,7 @@ onMounted(() => {
display: flex;
justify-content: space-between;
align-items: center;
padding: 18px 20px;
padding: 12px 16px;
cursor: pointer;
background: linear-gradient(135deg, #f6f9ff 0%, #ffffff 100%);
border-bottom: 1px solid #e6f7ff;
@@ -918,29 +1002,29 @@ onMounted(() => {
}
.coupon-title {
font-size: 16px;
font-size: 14px;
font-weight: 600;
color: #333;
display: flex;
align-items: center;
gap: 8px;
gap: 6px;
}
.coupon-title::before {
content: "🎁";
font-size: 18px;
font-size: 14px;
}
.coupon-value {
font-size: 13px;
font-size: 12px;
font-weight: 500;
color: #1890ff;
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
gap: 4px;
padding: 4px 10px;
background: rgba(24, 144, 255, 0.1);
border-radius: 20px;
border-radius: 16px;
transition: all 0.3s ease;
box-shadow: 0 1px 3px rgba(24, 144, 255, 0.2);
}
@@ -952,7 +1036,7 @@ onMounted(() => {
}
.coupon-discount {
padding: 14px 20px;
padding: 10px 16px;
background-color: #f0f9ff;
border-top: 1px solid #e6f7ff;
display: flex;
@@ -961,20 +1045,20 @@ onMounted(() => {
}
.discount-label {
font-size: 14px;
font-size: 12px;
color: #666;
display: flex;
align-items: center;
gap: 6px;
gap: 4px;
}
.discount-label::before {
content: "💰";
font-size: 14px;
font-size: 12px;
}
.discount-amount {
font-size: 18px;
font-size: 16px;
font-weight: 700;
color: #1890ff;
text-shadow: 0 1px 2px rgba(24, 144, 255, 0.3);
@@ -1014,15 +1098,17 @@ onMounted(() => {
.coupon-content {
display: flex;
align-items: center;
padding: 16px;
gap: 16px;
padding: 10px;
gap: 10px;
}
.coupon-value {
font-size: 24px;
font-size: 18px;
font-weight: 600;
color: #ff4d4f;
flex-shrink: 0;
min-width: 50px;
text-align: center;
}
.coupon-info {
@@ -1031,29 +1117,29 @@ onMounted(() => {
}
.coupon-name {
font-size: 15px;
font-size: 13px;
font-weight: 600;
color: #333;
margin-bottom: 4px;
margin-bottom: 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.coupon-condition {
font-size: 13px;
font-size: 11px;
color: #666;
margin-bottom: 4px;
margin-bottom: 2px;
}
.coupon-time {
font-size: 12px;
font-size: 10px;
color: #999;
}
.coupon-select {
color: #1890ff;
font-size: 20px;
font-size: 16px;
flex-shrink: 0;
}
+19
View File
@@ -33,6 +33,10 @@
<div class="item-info">
<div class="item-title">{{ item.productTitle }}</div>
<div class="item-price">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
<div v-if="item.artistName" class="item-artist">
<img v-if="item.artistAvatar" :src="item.artistAvatar" class="artist-avatar-small" />
<span>美甲师: {{ item.artistName }}</span>
</div>
</div>
</div>
</div>
@@ -299,6 +303,21 @@ onMounted(() => {
color: #666;
}
.item-artist {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: #1890ff;
}
.artist-avatar-small {
width: 20px;
height: 20px;
border-radius: 50%;
object-fit: cover;
}
.order-footer {
display: flex;
justify-content: space-between;
+3 -3
View File
@@ -8,7 +8,7 @@
</div>
<h1>{{ product.name || '作品详情' }}</h1>
<div class="actions">
<el-icon @click="handleFavoriteClick" :style="{ fontSize: '20px' }" :class="{ active: isFavorite }"><Star /></el-icon>
<el-icon @click="handleFavoriteClick" :style="{ fontSize: '20px' }" :class="{ active: isFavorite }"><StarFilled /></el-icon>
</div>
</header>
@@ -115,7 +115,7 @@
<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import { ArrowLeft, Star, Clock, Collection, ShoppingCart, Right } from '@element-plus/icons-vue'
import { ArrowLeft, StarFilled, Clock, Collection, ShoppingCart, Right } from '@element-plus/icons-vue'
import { Icon } from '@iconify/vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
@@ -388,7 +388,7 @@ onMounted(() => {
}
.actions .el-icon.active {
color: #f56c6c;
color: #fadb14;
}
.product-image-container {
+2 -2
View File
@@ -36,7 +36,7 @@
<!-- Empty Wishlist Message -->
<div v-if="wishlistItems.length === 0" class="empty-wishlist">
<el-icon :size="60"><Star /></el-icon>
<el-icon :size="60" :style="{ color: '#fadb14' }"><StarFilled /></el-icon>
<p>收藏列表为空</p>
<el-button type="primary" @click="handleBrowseProducts">
浏览作品
@@ -47,7 +47,7 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ArrowLeft, Delete, Star } from '@element-plus/icons-vue'
import { ArrowLeft, Delete, StarFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { wishlistApi, type WishlistItem } from '@/api/wishlist'
+19 -2
View File
@@ -12,12 +12,12 @@
<groupId>com.xiaowang</groupId>
<artifactId>YumiNail-Core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>1.0.0</version>
<name>YumiNail-Core</name>
<description>YumiNail-Core - 核心业务微服务</description>
<properties>
<java.version>17</java.version>
<java.version>21</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
@@ -193,6 +193,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<optional>true</optional>
</dependency>
@@ -243,6 +244,22 @@
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>17</source>
<target>17</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
@@ -1,5 +1,7 @@
package com.xiaowang.yuminailcore.config;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@@ -13,6 +15,7 @@ import javax.servlet.http.HttpServletResponse;
public class AuthInterceptor implements HandlerInterceptor {
private final JwtUtil jwtUtil;
private final UserMapper userMapper;
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_PREFIX = "Bearer ";
@@ -40,17 +43,37 @@ public class AuthInterceptor implements HandlerInterceptor {
}
if (!jwtUtil.isAccessToken(token)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":401,\"message\":\"Token类型错误\"}");
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误");
return false;
}
Long userId = jwtUtil.getUserIdFromToken(token);
String account = jwtUtil.getAccountFromToken(token);
UserDO currentUser = userMapper.selectById(userId);
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
return false;
}
if (isAdminPath(path) && (currentUser.getType() == null || currentUser.getType() < 2)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
return false;
}
request.setAttribute("userId", userId);
request.setAttribute("account", account);
request.setAttribute("userType", currentUser.getType());
return true;
}
private boolean isAdminPath(String path) {
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
}
private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception {
response.setStatus(status);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}");
}
}
@@ -21,13 +21,11 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/user/refresh-token",
"/user/send-verification-code",
"/user/phone-login",
"/user/reset-password-by-phone",
"/user/get/account/**",
"/shop/list/simple",
"/product/**",
"/tag/**",
"/file/**",
"/admin/auth/login",
"/admin/object-storage-file/upload",
"/admin/auth/refresh",
"/error",
"/health/**"
);
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/balance-change-detail")
@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"})
@RequiredArgsConstructor
public class BalanceChangeDetailController {
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/balance")
@RequestMapping({"/balance", "/api/balance"})
@RequiredArgsConstructor
public class BalanceController {
@@ -31,6 +31,13 @@ public class CartController {
return Result.success();
}
@PostMapping("/batch-remove")
public Result<Void> batchRemoveFromCart(@RequestBody List<Long> cartItemIds, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
cartService.batchRemoveFromCart(userId, cartItemIds);
return Result.success();
}
@PutMapping("/update")
public Result<Void> updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/comment")
@RequestMapping({"/comment", "/api/comment"})
@RequiredArgsConstructor
public class CommentController {
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/effect-diagram")
@RequestMapping({"/effect-diagram", "/api/effect-diagram"})
@RequiredArgsConstructor
public class EffectDiagramController {
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/login-identity")
@RequestMapping({"/login-identity", "/api/login-identity"})
@RequiredArgsConstructor
public class LoginIdentityController {
@@ -59,4 +59,12 @@ public class OrderController {
orderService.processOrder(orderId, status);
return Result.success();
}
// 美甲师查看自己的订单
@GetMapping("/artist/list")
public Result<List<OrderVO>> getArtistOrders(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
List<OrderVO> orderList = orderService.getOrdersByArtistId(userId);
return Result.success(orderList);
}
}
@@ -19,7 +19,7 @@ import java.util.List;
* @date 2026-02-25
*/
@RestController
@RequestMapping("/api/permission")
@RequestMapping({"/permission", "/api/permission"})
@RequiredArgsConstructor
public class PermissionController {
@@ -1,15 +1,7 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.BindEmailRequestDTO;
import com.xiaowang.yuminailcore.dto.BindPhoneRequestDTO;
import com.xiaowang.yuminailcore.dto.LoginRequestDTO;
import com.xiaowang.yuminailcore.dto.PhoneLoginRequestDTO;
import com.xiaowang.yuminailcore.dto.RefreshTokenRequestDTO;
import com.xiaowang.yuminailcore.dto.RegisterRequestDTO;
import com.xiaowang.yuminailcore.dto.SendVerificationCodeRequestDTO;
import com.xiaowang.yuminailcore.dto.UpdatePhoneRequestDTO;
import com.xiaowang.yuminailcore.dto.UserDTO;
import com.xiaowang.yuminailcore.dto.*;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
@@ -190,6 +182,18 @@ public class UserController {
return Result.success(true);
}
/**
* 通过手机号验证码重置密码
*
* @param resetPasswordRequestDTO 重置密码请求DTO
* @return 是否重置成功
*/
@PostMapping("/reset-password-by-phone")
public Result<Boolean> resetPasswordByPhone(@RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) {
boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO);
return Result.success(success);
}
/**
* 刷新Token
*
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/vip-benefit")
@RequestMapping({"/vip-benefit", "/api/vip-benefit"})
@RequiredArgsConstructor
public class VipBenefitController {
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/vip-info")
@RequestMapping({"/vip-info", "/api/vip-info"})
@RequiredArgsConstructor
public class VipInfoController {
@@ -2,9 +2,23 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
/**
* 绑定邮箱请求 DTO
* 用于用户绑定邮箱账号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class BindEmailRequestDTO {
/**
* 邮箱地址
*/
private String email;
/**
* 验证码
*/
private String code;
}
@@ -2,9 +2,23 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
/**
* 绑定手机号请求 DTO
* 用于用户绑定手机号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class BindPhoneRequestDTO {
/**
* 手机号
*/
private String phone;
/**
* 验证码
*/
private String code;
}
@@ -2,8 +2,23 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
/**
* 购物车 DTO
* 用于购物车商品信息的传输
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class CartDTO {
/**
* 商品ID
*/
private Long productId;
/**
* 商品数量
*/
private Integer quantity;
}
@@ -1,21 +1,36 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
/**
* 登录请求 DTO
* 用于用户账号密码登录
*
* @author xiaowang
* @date 2026-02-14
*/
@Data
@Getter
@Setter
public class LoginRequestDTO {
/**
* 账号
*/
private String account;
/**
* 密码
*/
private String password;
/**
* 记住我标志
*/
private Boolean rememberMe;
/**
* 店铺ID
*/
private Long shopId;
}
@@ -2,7 +2,25 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import java.util.List;
/**
* 订单 DTO
* 用于订单创建请求
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class OrderDTO {
/**
* 优惠券ID
*/
private Long couponId;
}
/**
* 订单商品列表
*/
private List<OrderItemDTO> items;
}
@@ -0,0 +1,29 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
/**
* 订单商品项 DTO
* 用于订单中的单个商品信息
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class OrderItemDTO {
/**
* 商品ID
*/
private Long productId;
/**
* 商品数量
*/
private Integer quantity;
/**
* 美甲师ID
*/
private Long artistId;
}
@@ -4,12 +4,16 @@ import lombok.Data;
/**
* 刷新Token请求 DTO
* 用于刷新访问令牌
*
* @author xiaowang
* @date 2026-02-14
*/
@Data
public class RefreshTokenRequestDTO {
/**
* 刷新令牌
*/
private String refreshToken;
}
@@ -2,9 +2,28 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
/**
* 更换手机号请求 DTO
* 用于用户更换绑定的手机号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class UpdatePhoneRequestDTO {
/**
* 原手机号
*/
private String oldPhone;
/**
* 新手机号
*/
private String newPhone;
/**
* 验证码
*/
private String verificationCode;
}
@@ -3,10 +3,33 @@ package com.xiaowang.yuminailcore.dto;
import com.xiaowang.yuminailcore.vo.ProductVO;
import lombok.Data;
/**
* 收藏夹 DTO
* 用于收藏夹商品信息的传输
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class WishlistDTO {
/**
* 收藏记录ID
*/
private Long id;
/**
* 用户ID
*/
private Long userId;
/**
* 商品ID
*/
private Long productId;
/**
* 商品详细信息
*/
private ProductVO product;
}
@@ -11,6 +11,7 @@ import java.time.LocalDateTime;
public class OrderDO extends BaseEntity {
private String orderNo;
private Long userId;
private Long shopId;
private BigDecimal totalAmount;
private BigDecimal actualAmount;
private Long couponId;
@@ -13,6 +13,7 @@ public class OrderItemDO extends BaseEntity {
private Long productId;
private Integer quantity;
private BigDecimal price;
private Long artistId;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private Integer isDelete;
@@ -5,7 +5,8 @@ import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.EqualsAndHashCode;
/**
@@ -15,8 +16,9 @@ import lombok.EqualsAndHashCode;
* @author xiaowang
* @date 2026-02-13
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@TableName("t_user")
public class UserDO extends BaseEntity {
@@ -15,4 +15,10 @@ public interface OrderMapper extends BaseMapper<OrderDO> {
@Select("SELECT * FROM t_order WHERE order_no = #{orderNo}")
OrderDO selectByOrderNo(@Param("orderNo") String orderNo);
@Select("SELECT DISTINCT o.* FROM t_order o " +
"INNER JOIN t_order_item oi ON o.id = oi.order_id " +
"WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " +
"ORDER BY o.create_time DESC")
List<OrderDO> selectByArtistId(@Param("artistId") Long artistId);
}
@@ -8,6 +8,7 @@ import java.util.List;
public interface CartService {
void addToCart(Long userId, CartDTO cartDTO);
void removeFromCart(Long userId, Long productId);
void batchRemoveFromCart(Long userId, List<Long> cartItemIds);
void updateCartQuantity(Long userId, CartDTO cartDTO);
List<CartVO> getCartList(Long userId);
void clearCart(Long userId);
@@ -12,4 +12,5 @@ public interface OrderService {
void cancelOrder(Long orderId, Long userId);
void processOrder(Long orderId, Integer status);
List<OrderVO> getAllOrders();
List<OrderVO> getOrdersByArtistId(Long artistId);
}
@@ -6,6 +6,7 @@ import com.xiaowang.yuminailcore.dto.BindPhoneRequestDTO;
import com.xiaowang.yuminailcore.dto.LoginRequestDTO;
import com.xiaowang.yuminailcore.dto.PhoneLoginRequestDTO;
import com.xiaowang.yuminailcore.dto.RegisterRequestDTO;
import com.xiaowang.yuminailcore.dto.ResetPasswordRequestDTO;
import com.xiaowang.yuminailcore.dto.UpdatePhoneRequestDTO;
import com.xiaowang.yuminailcore.dto.UserDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
@@ -52,6 +53,8 @@ public interface UserService extends IService<UserDO> {
boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO);
boolean resetPassword(Long targetUserId, Long currentUserId);
boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO);
PageResultVO<UserVO> pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type);
@@ -61,6 +61,19 @@ public class CartServiceImpl implements CartService {
cartMapper.delete(wrapper);
}
@Override
@Transactional
public void batchRemoveFromCart(Long userId, List<Long> cartItemIds) {
if (cartItemIds == null || cartItemIds.isEmpty()) {
return;
}
QueryWrapper<CartDO> wrapper = new QueryWrapper<>();
wrapper.eq("user_id", userId)
.in("id", cartItemIds)
.eq("is_delete", 0);
cartMapper.delete(wrapper);
}
@Override
@Transactional
public void updateCartQuantity(Long userId, CartDTO cartDTO) {
@@ -2,6 +2,7 @@ package com.xiaowang.yuminailcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaowang.yuminailcore.dto.OrderDTO;
import com.xiaowang.yuminailcore.dto.OrderItemDTO;
import com.xiaowang.yuminailcore.entity.*;
import com.xiaowang.yuminailcore.mapper.*;
import com.xiaowang.yuminailcore.service.OrderService;
@@ -38,38 +39,79 @@ public class OrderServiceImpl implements OrderService {
@Resource
private UserCouponMapper userCouponMapper;
@Resource
private UserMapper userMapper;
@Override
@Transactional
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
// 获取购物车商品
List<CartDO> cartList = cartMapper.selectByUserId(userId);
if (cartList.isEmpty()) {
throw new RuntimeException("购物车为空");
// 获取订单项列表
List<OrderItemDTO> orderItemDTOs = orderDTO.getItems();
if (orderItemDTOs == null || orderItemDTOs.isEmpty()) {
throw new RuntimeException("订单项不能为空");
}
// 计算总金额
BigDecimal totalAmount = BigDecimal.ZERO;
List<OrderItemDO> orderItems = new ArrayList<>();
Long shopId = null;
for (CartDO cart : cartList) {
if (cart.getIsDelete() == 0) {
ProductDO product = productMapper.selectById(cart.getProductId());
if (product != null && product.getIsDelete() == 0) {
BigDecimal itemTotal = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
totalAmount = totalAmount.add(itemTotal);
// 创建订单商品
OrderItemDO orderItem = new OrderItemDO();
orderItem.setProductId(product.getId());
orderItem.setQuantity(cart.getQuantity());
orderItem.setPrice(product.getPrice());
orderItems.add(orderItem);
}
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
ProductDO product = productMapper.selectById(orderItemDTO.getProductId());
if (product == null || product.getIsDelete() == 1) {
throw new RuntimeException("商品不存在或已下架");
}
// 验证美甲师
if (orderItemDTO.getArtistId() != null) {
UserDO artist = userMapper.selectById(orderItemDTO.getArtistId());
if (artist == null || artist.getIsDelete() == 1) {
throw new RuntimeException("美甲师不存在或已删除");
}
if (artist.getType() != 3) {
throw new RuntimeException("指定的用户不是美甲师");
}
if (artist.getStatus() == 0) {
throw new RuntimeException("美甲师已被禁用");
}
// 验证商品是否可以被该美甲师预约
if (product.getBookableArtists() != null && !product.getBookableArtists().isEmpty()) {
String[] artistIds = product.getBookableArtists().split(",");
boolean isBookable = false;
for (String artistId : artistIds) {
if (artistId.trim().equals(orderItemDTO.getArtistId().toString())) {
isBookable = true;
break;
}
}
if (!isBookable) {
throw new RuntimeException("该美甲师无法预约此商品");
}
}
} else {
throw new RuntimeException("请为每个商品选择美甲师");
}
// 设置店铺ID(从第一个商品获取)
if (shopId == null) {
shopId = product.getShopId();
}
BigDecimal itemTotal = product.getPrice().multiply(new BigDecimal(orderItemDTO.getQuantity()));
totalAmount = totalAmount.add(itemTotal);
// 创建订单商品
OrderItemDO orderItem = new OrderItemDO();
orderItem.setProductId(product.getId());
orderItem.setQuantity(orderItemDTO.getQuantity());
orderItem.setPrice(product.getPrice());
orderItem.setArtistId(orderItemDTO.getArtistId());
orderItems.add(orderItem);
}
if (totalAmount.compareTo(BigDecimal.ZERO) == 0) {
throw new RuntimeException("购物车商品无效");
throw new RuntimeException("订单金额无效");
}
// 处理优惠券
@@ -117,6 +159,7 @@ public class OrderServiceImpl implements OrderService {
OrderDO order = new OrderDO();
order.setOrderNo(orderNo);
order.setUserId(userId);
order.setShopId(shopId);
order.setTotalAmount(totalAmount);
order.setActualAmount(actualAmount);
order.setCouponId(couponId);
@@ -131,9 +174,6 @@ public class OrderServiceImpl implements OrderService {
orderItemMapper.insert(item);
}
// 清空购物车
cartMapper.delete(new QueryWrapper<CartDO>().eq("user_id", userId).eq("is_delete", 0));
// 构建返回对象
return buildOrderVO(order);
}
@@ -258,10 +298,24 @@ public class OrderServiceImpl implements OrderService {
return orderVOList;
}
@Override
public List<OrderVO> getOrdersByArtistId(Long artistId) {
List<OrderDO> orderList = orderMapper.selectByArtistId(artistId);
List<OrderVO> orderVOList = new ArrayList<>();
for (OrderDO order : orderList) {
orderVOList.add(buildOrderVO(order));
}
return orderVOList;
}
private OrderVO buildOrderVO(OrderDO order) {
OrderVO orderVO = new OrderVO();
orderVO.setId(order.getId());
orderVO.setOrderNo(order.getOrderNo());
orderVO.setUserId(order.getUserId());
orderVO.setShopId(order.getShopId());
orderVO.setTotalAmount(order.getTotalAmount());
orderVO.setActualAmount(order.getActualAmount());
orderVO.setCouponId(order.getCouponId());
@@ -311,6 +365,17 @@ public class OrderServiceImpl implements OrderService {
itemVO.setQuantity(item.getQuantity());
itemVO.setPrice(item.getPrice());
itemVO.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
// 设置美甲师信息
if (item.getArtistId() != null) {
itemVO.setArtistId(item.getArtistId());
UserDO artist = userMapper.selectById(item.getArtistId());
if (artist != null) {
itemVO.setArtistName(artist.getNickname());
itemVO.setArtistAvatar(artist.getAvatar());
}
}
orderItemVOs.add(itemVO);
}
}
@@ -794,4 +794,32 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
}
@Override
public boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO) {
String phone = resetPasswordRequestDTO.getPhone();
String verificationCode = resetPasswordRequestDTO.getVerificationCode();
String newPassword = resetPasswordRequestDTO.getNewPassword();
// 验证验证码
String redisKey = "verification_code:" + phone;
String storedCode = redisTemplate.opsForValue().get(redisKey);
if (storedCode == null || !storedCode.equals(verificationCode)) {
throw new RuntimeException("验证码错误");
}
// 根据手机号查找用户
LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class);
wrapper.eq(UserDO::getPhone, phone);
UserDO userDO = userMapper.selectOne(wrapper);
if (userDO == null) {
throw new RuntimeException("未绑定手机号,请联系店员");
}
// 更新密码
userDO.setPassword(passwordEncoder.encode(newPassword));
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
}
}
@@ -13,4 +13,7 @@ public class OrderItemVO {
private Integer quantity;
private BigDecimal price;
private BigDecimal totalPrice;
private Long artistId;
private String artistName;
private String artistAvatar;
}
@@ -10,6 +10,8 @@ import java.util.List;
public class OrderVO {
private Long id;
private String orderNo;
private Long userId;
private Long shopId;
private BigDecimal totalAmount;
private BigDecimal actualAmount;
private Long couponId;
@@ -655,4 +655,7 @@ CREATE TABLE t_product_like (
) COMMENT '商品点赞记录表';
CREATE INDEX idx_user_id_like ON t_product_like (user_id) COMMENT '按用户查询点赞的索引';
CREATE INDEX idx_product_id_like ON t_product_like (product_id) COMMENT '按商品查询点赞的索引';
CREATE INDEX idx_product_id_like ON t_product_like (product_id) COMMENT '按商品查询点赞的索引';
ALTER TABLE t_order_item ADD COLUMN artist_id BIGINT UNSIGNED DEFAULT NULL COMMENT '关联美甲师ID' AFTER price;
+2 -1
View File
@@ -17,7 +17,7 @@
<description>YumiNail-Gateway - 服务网关</description>
<properties>
<java.version>17</java.version>
<java.version>21</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
</properties>
@@ -105,6 +105,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<optional>true</optional>
</dependency>
@@ -17,6 +17,7 @@ import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* 全局认证过滤器
@@ -29,6 +30,23 @@ import java.nio.charset.StandardCharsets;
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
private static final List<String> DEFAULT_WHITELIST = List.of(
"/api/user/login",
"/api/user/register",
"/api/user/refresh-token",
"/api/user/send-verification-code",
"/api/user/phone-login",
"/api/user/reset-password-by-phone",
"/api/user/get/account/**",
"/api/shop/list/simple",
"/api/admin/auth/login",
"/api/admin/auth/refresh",
"/admin/api/auth/login",
"/admin/api/auth/refresh",
"/api/health/**",
"/api/error"
);
@Autowired
private GatewayConfig gatewayConfig;
@@ -39,34 +57,15 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
log.info("Gateway received request: {}", path);
// 打印白名单配置
if (gatewayConfig.getWhitelist() != null) {
log.info("Whitelist from config: {}", gatewayConfig.getWhitelist());
} else {
log.info("Whitelist from config is null");
}
// 1. Whitelist check (login and register interfaces don't need authentication)
log.info("Checking if path is in whitelist: {}", path);
boolean isWhitelist = isWhitelist(path);
log.info("Whitelist check result: {}", isWhitelist);
if (isWhitelist) {
log.info("Path is in whitelist, passing through directly");
if (isWhitelist(path)) {
return chain.filter(exchange);
}
log.info("Path is not in whitelist, need to check Token");
// 2. Token 校验
String token = request.getHeaders().getFirst("Authorization");
if (!StringUtils.hasText(token)) {
return unAuthorized(exchange, "未携带Token,拒绝访问");
}
// 3. 双 Token 校验模式
// accessToken 用于 API 访问,refreshToken 用于刷新 accessToken
// 这里只验证 accessToken 是否存在,具体验证由后端服务处理
if (!token.startsWith("Bearer ")) {
return unAuthorized(exchange, "Token格式错误");
}
@@ -78,7 +77,6 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
* 判断是否在白名单中
*/
private boolean isWhitelist(String path) {
// 首先检查配置文件中的白名单
if (gatewayConfig.getWhitelist() != null) {
for (String whitelistPath : gatewayConfig.getWhitelist()) {
if (pathMatcher.match(whitelistPath, path)) {
@@ -86,20 +84,8 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
}
}
}
// 硬编码白名单作为备用
return pathMatcher.match("/api/user/login", path) ||
pathMatcher.match("/api/user/register", path) ||
pathMatcher.match("/api/user/refresh-token", path) ||
pathMatcher.match("/api/user/send-verification-code", path) ||
pathMatcher.match("/api/user/phone-login", path) ||
pathMatcher.match("/api/user/get/account/**", path) ||
pathMatcher.match("/api/shop/list/simple", path) ||
pathMatcher.match("/api/admin/auth/login", path) ||
pathMatcher.match("/admin/api/auth/login", path) ||
pathMatcher.match("/api/health/**", path) ||
pathMatcher.match("/api/error", path) ||
pathMatcher.match("/api/admin/object-storage-file/upload", path);
return DEFAULT_WHITELIST.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
}
/**
@@ -89,6 +89,7 @@ spring:
- RewritePath=/api/(?<remaining>.*), /${remaining}
# 后台管理API路由(/api/admin/** 格式)
- id: admin-api-route
order: -10
uri: lb://yumi-nail-core
predicates:
- Path=/api/admin/**
@@ -96,8 +97,35 @@ spring:
- RewritePath=/api/admin/(?<remaining>.*), /admin/${remaining}
# 后台管理API路由(/admin/api/** 格式)
- id: admin-route
order: -9
uri: lb://yumi-nail-core
predicates:
- Path=/admin/api/**
filters:
- RewritePath=/admin/api/(?<remaining>.*), /admin/${remaining}
# 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404
- id: frontend-fallback-route
order: 100
uri: lb://yumi-nail-core
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
yuminail:
gateway:
whitelist:
- /api/user/login
- /api/user/register
- /api/user/refresh-token
- /api/user/send-verification-code
- /api/user/phone-login
- /api/user/reset-password-by-phone
- /api/user/get/account/**
- /api/shop/list/simple
- /api/health/**
- /api/error
- /api/admin/auth/login
- /api/admin/auth/refresh
- /admin/api/auth/login
- /admin/api/auth/refresh