增加用户资料修改
This commit is contained in:
@@ -26,6 +26,16 @@ func (r *UserRepository) FindByID(id uint64) (*model.User, error) {
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) UpdateProfile(id uint64, nickname string, avatarURL string) (*model.User, error) {
|
||||
if err := r.db.Model(&model.User{}).Where("id = ?", id).Updates(map[string]any{
|
||||
"nickname": nickname,
|
||||
"avatar_url": avatarURL,
|
||||
}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.FindByID(id)
|
||||
}
|
||||
|
||||
func (r *UserRepository) FindOrCreateByPhone(phone string) (*model.User, error) {
|
||||
now := time.Now()
|
||||
user := model.User{
|
||||
|
||||
@@ -2,6 +2,7 @@ package user
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/modules/auth"
|
||||
@@ -15,6 +16,11 @@ type Handler struct {
|
||||
users *auth.UserRepository
|
||||
}
|
||||
|
||||
type UpdateProfileRequest struct {
|
||||
Nickname string `json:"nickname"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
}
|
||||
|
||||
func NewHandler(users *auth.UserRepository) *Handler {
|
||||
return &Handler{users: users}
|
||||
}
|
||||
@@ -40,3 +46,47 @@ func (h *Handler) Me(c *gin.Context) {
|
||||
}
|
||||
response.OK(c, user)
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateMe(c *gin.Context) {
|
||||
if h.users == nil {
|
||||
response.ServiceUnavailable(c, "数据库未连接")
|
||||
return
|
||||
}
|
||||
userID, ok := c.Get(middleware.ContextUserID)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
|
||||
var req UpdateProfileRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "资料格式不正确")
|
||||
return
|
||||
}
|
||||
|
||||
nickname := strings.TrimSpace(req.Nickname)
|
||||
avatarURL := strings.TrimSpace(req.AvatarURL)
|
||||
if nickname == "" {
|
||||
response.BadRequest(c, "昵称不能为空")
|
||||
return
|
||||
}
|
||||
if len([]rune(nickname)) > 24 {
|
||||
response.BadRequest(c, "昵称不能超过 24 个字符")
|
||||
return
|
||||
}
|
||||
if len(avatarURL) > 512 {
|
||||
response.BadRequest(c, "头像地址过长")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.users.UpdateProfile(userID.(uint64), nickname, avatarURL)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.Unauthorized(c, "用户不存在")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.ServiceUnavailable(c, "资料更新失败")
|
||||
return
|
||||
}
|
||||
response.OK(c, user)
|
||||
}
|
||||
|
||||
@@ -140,6 +140,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
}
|
||||
|
||||
api.GET("/me", requireAuth, userHandler.Me)
|
||||
api.PUT("/me", requireAuth, userHandler.UpdateMe)
|
||||
|
||||
listingRoutes := api.Group("/listings")
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ export interface AuthUser {
|
||||
id: number
|
||||
phone: string
|
||||
nickname: string
|
||||
avatar_url: string
|
||||
realname_status: string
|
||||
risk_status: string
|
||||
credit_score: number
|
||||
@@ -44,3 +45,8 @@ export async function fetchMe() {
|
||||
const { data } = await apiClient.get<ApiResponse<AuthUser>>('/me')
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function updateMe(payload: Pick<AuthUser, 'nickname' | 'avatar_url'>) {
|
||||
const { data } = await apiClient.put<ApiResponse<AuthUser>>('/me', payload)
|
||||
return data.data
|
||||
}
|
||||
|
||||
@@ -38,6 +38,9 @@ apiClient.interceptors.response.use(
|
||||
localStorage.removeItem('access_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('user_id')
|
||||
localStorage.removeItem('phone')
|
||||
localStorage.removeItem('nickname')
|
||||
localStorage.removeItem('avatar_url')
|
||||
localStorage.removeItem('realname_status')
|
||||
|
||||
if (!window.location.pathname.startsWith('/m/login') && !window.location.pathname.startsWith('/m/register')) {
|
||||
|
||||
@@ -218,8 +218,18 @@ router.beforeEach(async (to) => {
|
||||
return { path: toMobilePath(to.path), query: to.query, hash: to.hash };
|
||||
}
|
||||
|
||||
if (to.meta.requiresAuth && !localStorage.getItem("access_token")) {
|
||||
return { path: "/m/login", query: { redirect: to.fullPath } };
|
||||
if (to.meta.requiresAuth) {
|
||||
const session = useSessionStore();
|
||||
if (!session.token) {
|
||||
return { path: "/m/login", query: { redirect: to.fullPath } };
|
||||
}
|
||||
if (!session.phone) {
|
||||
try {
|
||||
await session.loadMe();
|
||||
} catch {
|
||||
return { path: "/m/login", query: { redirect: to.fullPath } };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (to.meta.requiresRealname) {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
import { fetchMe, loginWithSms, type AuthUser } from '@/api/auth'
|
||||
import { fetchMe, loginWithSms, updateMe, type AuthUser } from '@/api/auth'
|
||||
|
||||
export const useSessionStore = defineStore('session', {
|
||||
state: () => ({
|
||||
token: localStorage.getItem('access_token') || '',
|
||||
refreshToken: localStorage.getItem('refresh_token') || '',
|
||||
userId: Number(localStorage.getItem('user_id') || 0),
|
||||
phone: '',
|
||||
phone: localStorage.getItem('phone') || '',
|
||||
nickname: localStorage.getItem('nickname') || '',
|
||||
avatarUrl: localStorage.getItem('avatar_url') || '',
|
||||
realnameStatus: localStorage.getItem('realname_status') || 'unknown',
|
||||
}),
|
||||
actions: {
|
||||
@@ -21,6 +23,11 @@ export const useSessionStore = defineStore('session', {
|
||||
this.applyUser(user)
|
||||
return user
|
||||
},
|
||||
async updateProfile(payload: { nickname: string; avatar_url: string }) {
|
||||
const user = await updateMe(payload)
|
||||
this.applyUser(user)
|
||||
return user
|
||||
},
|
||||
logout() {
|
||||
this.token = ''
|
||||
this.refreshToken = ''
|
||||
@@ -30,6 +37,9 @@ export const useSessionStore = defineStore('session', {
|
||||
localStorage.removeItem('access_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('user_id')
|
||||
localStorage.removeItem('phone')
|
||||
localStorage.removeItem('nickname')
|
||||
localStorage.removeItem('avatar_url')
|
||||
localStorage.removeItem('realname_status')
|
||||
},
|
||||
applySession(user: AuthUser, accessToken: string, refreshToken: string) {
|
||||
@@ -45,6 +55,11 @@ export const useSessionStore = defineStore('session', {
|
||||
this.userId = user.id
|
||||
localStorage.setItem('user_id', String(user.id))
|
||||
this.phone = user.phone
|
||||
localStorage.setItem('phone', user.phone)
|
||||
this.nickname = user.nickname
|
||||
localStorage.setItem('nickname', user.nickname)
|
||||
this.avatarUrl = user.avatar_url
|
||||
localStorage.setItem('avatar_url', user.avatar_url)
|
||||
this.realnameStatus = user.realname_status
|
||||
localStorage.setItem('realname_status', user.realname_status)
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useRouter, useRoute } from "vue-router";
|
||||
import { useSessionStore } from "@/stores/session";
|
||||
import { showDialog, showToast } from "vant";
|
||||
@@ -10,6 +10,12 @@ const route = useRoute();
|
||||
|
||||
/** 设置面板 */
|
||||
const showSettings = ref(false);
|
||||
const showProfileEditor = ref(false);
|
||||
const savingProfile = ref(false);
|
||||
const profileForm = reactive({
|
||||
nickname: "",
|
||||
avatar_url: "",
|
||||
});
|
||||
|
||||
const settingsGroups = [
|
||||
{
|
||||
@@ -17,7 +23,6 @@ const settingsGroups = [
|
||||
items: [
|
||||
{ label: "资料更改", icon: "edit", action: "profile" },
|
||||
{ label: "实名认证", icon: "idcard", action: "realname" },
|
||||
{ label: "登录密码管理", icon: "lock", action: "password" },
|
||||
{ label: "注销账号", icon: "delete-o", action: "cancel-account" },
|
||||
],
|
||||
},
|
||||
@@ -34,14 +39,11 @@ function onSettingClick(action: string) {
|
||||
showSettings.value = false;
|
||||
switch (action) {
|
||||
case "profile":
|
||||
showToast({ message: "资料更改功能开发中", icon: "info-o" });
|
||||
openProfileEditor();
|
||||
break;
|
||||
case "realname":
|
||||
router.push("/m/realname");
|
||||
break;
|
||||
case "password":
|
||||
showToast({ message: "密码管理功能开发中", icon: "info-o" });
|
||||
break;
|
||||
case "cancel-account":
|
||||
showDialog({
|
||||
title: "注销账号",
|
||||
@@ -65,6 +67,44 @@ function onSettingClick(action: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function openProfileEditor() {
|
||||
profileForm.nickname = session.nickname || defaultName.value;
|
||||
profileForm.avatar_url = session.avatarUrl || "";
|
||||
showProfileEditor.value = true;
|
||||
}
|
||||
|
||||
async function saveProfile() {
|
||||
const nickname = profileForm.nickname.trim();
|
||||
const avatarURL = profileForm.avatar_url.trim();
|
||||
if (!nickname) {
|
||||
showToast({ message: "请输入昵称", icon: "warning-o" });
|
||||
return;
|
||||
}
|
||||
if (nickname.length > 24) {
|
||||
showToast({ message: "昵称不能超过 24 个字符", icon: "warning-o" });
|
||||
return;
|
||||
}
|
||||
|
||||
savingProfile.value = true;
|
||||
try {
|
||||
await session.updateProfile({ nickname, avatar_url: avatarURL });
|
||||
showProfileEditor.value = false;
|
||||
showToast({ message: "资料已更新", icon: "passed" });
|
||||
} catch (error) {
|
||||
showToast({ message: readError(error, "资料更新失败"), icon: "cross" });
|
||||
} finally {
|
||||
savingProfile.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function readError(error: unknown, fallback: string) {
|
||||
if (typeof error === "object" && error && "response" in error) {
|
||||
const response = (error as { response?: { data?: { message?: string } } }).response;
|
||||
return response?.data?.message || fallback;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function confirmLogout() {
|
||||
showSettings.value = false;
|
||||
showDialog({
|
||||
@@ -77,6 +117,7 @@ function confirmLogout() {
|
||||
})
|
||||
.then(() => {
|
||||
session.logout();
|
||||
router.replace("/m");
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
@@ -95,17 +136,19 @@ onMounted(() => {
|
||||
}
|
||||
});
|
||||
|
||||
const displayName = computed(() =>
|
||||
const defaultName = computed(() =>
|
||||
session.phone
|
||||
? `用户${session.phone.slice(-6)}`
|
||||
: `用户${session.userId || 883099}`
|
||||
);
|
||||
const displayName = computed(() => session.nickname || defaultName.value);
|
||||
const displayId = computed(() => session.userId || 138865);
|
||||
const maskedPhone = computed(() =>
|
||||
session.phone
|
||||
? `${session.phone.slice(0, 3)}****${session.phone.slice(-4)}`
|
||||
: "登录后查看手机号"
|
||||
);
|
||||
const avatarText = computed(() => displayName.value.slice(0, 1));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -117,7 +160,10 @@ const maskedPhone = computed(() =>
|
||||
<div class="hero-bg"></div>
|
||||
<div class="profile-hero-content">
|
||||
<div class="avatar-wrap">
|
||||
<div class="avatar-circle">👤</div>
|
||||
<div class="avatar-circle">
|
||||
<img v-if="session.avatarUrl" :src="session.avatarUrl" alt="" />
|
||||
<span v-else>{{ avatarText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hero-user">
|
||||
<h1>{{ displayName }}</h1>
|
||||
@@ -197,6 +243,63 @@ const maskedPhone = computed(() =>
|
||||
</div>
|
||||
</van-popup>
|
||||
|
||||
<van-popup
|
||||
v-model:show="showProfileEditor"
|
||||
position="bottom"
|
||||
round
|
||||
:style="{ maxWidth: '430px', margin: '0 auto', left: 0, right: 0 }"
|
||||
>
|
||||
<section class="profile-editor">
|
||||
<header class="profile-editor-header">
|
||||
<h2>资料更改</h2>
|
||||
<button type="button" @click="showProfileEditor = false">
|
||||
<van-icon name="cross" :size="20" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="profile-preview">
|
||||
<div class="profile-preview-avatar">
|
||||
<img v-if="profileForm.avatar_url" :src="profileForm.avatar_url" alt="" />
|
||||
<span v-else>{{ (profileForm.nickname || defaultName).slice(0, 1) }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>{{ profileForm.nickname || defaultName }}</strong>
|
||||
<p>{{ maskedPhone }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="editor-field">
|
||||
<span>昵称</span>
|
||||
<input
|
||||
v-model="profileForm.nickname"
|
||||
maxlength="24"
|
||||
placeholder="请输入昵称"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="editor-field">
|
||||
<span>头像地址</span>
|
||||
<input
|
||||
v-model="profileForm.avatar_url"
|
||||
maxlength="512"
|
||||
placeholder="可填写图片 URL,留空使用文字头像"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<van-button
|
||||
type="primary"
|
||||
block
|
||||
round
|
||||
class="profile-save-btn"
|
||||
:loading="savingProfile"
|
||||
loading-text="保存中..."
|
||||
@click="saveProfile"
|
||||
>
|
||||
保存资料
|
||||
</van-button>
|
||||
</section>
|
||||
</van-popup>
|
||||
|
||||
<!-- 底部导航 - 手写原生,和首页一致 -->
|
||||
<nav class="bottom-nav">
|
||||
<RouterLink
|
||||
@@ -280,9 +383,17 @@ const maskedPhone = computed(() =>
|
||||
height: 54px;
|
||||
place-items: center;
|
||||
border-radius: 16px;
|
||||
background: #fff3e8;
|
||||
color: #ff6a00;
|
||||
font-size: 26px;
|
||||
overflow: hidden;
|
||||
background: #eaf2ff;
|
||||
color: #1477ff;
|
||||
font-size: 22px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.avatar-circle img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.hero-user {
|
||||
@@ -427,6 +538,121 @@ const maskedPhone = computed(() =>
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
/* ========== 资料修改 ========== */
|
||||
.profile-editor {
|
||||
padding: 16px 16px max(18px, env(safe-area-inset-bottom));
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.profile-editor-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.profile-editor-header h2 {
|
||||
margin: 0;
|
||||
color: #17233d;
|
||||
font-size: 18px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.profile-editor-header button {
|
||||
display: grid;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
place-items: center;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: #f4f6f8;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.profile-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 18px 0;
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
background: #f7faff;
|
||||
}
|
||||
|
||||
.profile-preview-avatar {
|
||||
display: grid;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex: 0 0 auto;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border-radius: 16px;
|
||||
background: #1477ff;
|
||||
color: #fff;
|
||||
font-size: 22px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.profile-preview-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.profile-preview strong {
|
||||
display: block;
|
||||
max-width: 230px;
|
||||
overflow: hidden;
|
||||
color: #17233d;
|
||||
font-size: 16px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.profile-preview p {
|
||||
margin: 4px 0 0;
|
||||
color: #7b8798;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.editor-field {
|
||||
display: block;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.editor-field span {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
color: #697386;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.editor-field input {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 46px;
|
||||
border: 1px solid #e1e7ef;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
color: #17233d;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.editor-field input:focus {
|
||||
border-color: #1477ff;
|
||||
box-shadow: 0 0 0 3px rgba(20, 119, 255, 0.1);
|
||||
}
|
||||
|
||||
.profile-save-btn {
|
||||
height: 44px;
|
||||
margin-top: 6px;
|
||||
background: #1477ff;
|
||||
border-color: transparent;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
/* ========== 底部导航 - 手写原生 ========== */
|
||||
.bottom-nav {
|
||||
position: fixed;
|
||||
|
||||
Reference in New Issue
Block a user