Files
nannanwu 690b4d5961 fix(admin): 添加管理操作错误处理及更新模板样式
- 管理后台帖子与用户审核操作中添加失败错误重定向处理
- 管理后台帖子、用户、评论删除操作中添加错误检查及提示
- 用户角色更新操作失败时添加错误重定向
- 用户封禁通知失败时添加相应错误提示
- 登录登出时session保存加入错误处理
- 讨论区上传目录创建失败时显示错误提示
- 移除admin_dashboard.html多余样式及修正侧边栏当前页高亮
- admin_posts.html和admin_users.html添加状态样式动态使用的隐藏span元素
- admin_users.html为角色选择添加label以提升无障碍性
- 升级项目依赖版本,包含gin、gorm、validator等核心库版本更新
2026-02-24 21:14:55 +08:00

110 lines
2.7 KiB
Go

package controllers
import (
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"lv8girl/internal/middleware"
"lv8girl/internal/services"
"github.com/gin-gonic/gin"
)
type UserController struct {
userSvc *services.UserService
}
func NewUserController() *UserController {
return &UserController{
userSvc: services.NewUserService(),
}
}
func (c *UserController) ShowProfile(ctx *gin.Context) {
currentUserID, currentUsername, currentUserRole, isLoggedIn := middleware.GetCurrentUser(ctx)
userIDStr := ctx.Param("id")
var userID uint
if userIDStr == "" {
userID = currentUserID
} else {
userID = parseUint(userIDStr)
}
if userID == 0 {
ctx.Redirect(http.StatusFound, "/")
return
}
profile, err := c.userSvc.GetUserProfile(currentUserID, userID)
if err != nil {
ctx.String(http.StatusNotFound, "用户不存在")
return
}
avatar := ""
if profile.User.Avatar != "" {
// 确保路径使用正斜杠,并添加前导斜杠
avatarPath := filepath.ToSlash(profile.User.Avatar)
avatar = "/" + avatarPath
}
ctx.HTML(http.StatusOK, "profile.html", gin.H{
"IsLoggedIn": isLoggedIn,
"CurrentUserID": currentUserID,
"CurrentUsername": currentUsername,
"CurrentUserRole": currentUserRole,
"User": profile.User,
"UserAvatar": avatar,
"Posts": profile.Posts,
"PostCount": profile.PostCount,
"IsOwner": profile.IsOwner,
"UnreadCount": profile.UnreadCount,
"Message": "",
})
}
func (c *UserController) UploadAvatar(ctx *gin.Context) {
userID, _, _, _ := middleware.GetCurrentUser(ctx)
file, err := ctx.FormFile("avatar")
if err != nil {
ctx.Redirect(http.StatusFound, "/profile?error=上传失败")
return
}
if file.Size > 2*1024*1024 {
ctx.Redirect(http.StatusFound, "/profile?error=图片大小不能超过2MB")
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
filename := "avatar_" + strconv.FormatUint(uint64(userID), 10) + "_" + time.Now().Format("20060102150405") + ext
uploadDir := "uploads/avatars"
if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
if err := os.MkdirAll(uploadDir, 0755); err != nil {
ctx.Redirect(http.StatusFound, "/profile?error=创建上传目录失败")
return
}
}
imagePath := filepath.Join(uploadDir, filename)
if err := ctx.SaveUploadedFile(file, imagePath); err != nil {
ctx.Redirect(http.StatusFound, "/profile?error=保存失败")
return
}
// 将路径转换为 URL 友好的格式(使用正斜杠)
avatarPath := filepath.ToSlash(imagePath)
if err := c.userSvc.UpdateAvatar(userID, avatarPath); err != nil {
ctx.Redirect(http.StatusFound, "/profile?error=头像更新失败")
return
}
ctx.Redirect(http.StatusFound, "/profile?success=头像更新成功")
}