Files
nl-im-service/internal/api/user_handler.go
2026-07-08 08:18:58 +08:00

238 lines
5.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* package api
* 作用用户管理相关API处理器
*/
package api
import (
"encoding/json"
"fmt"
"math/rand"
"strconv"
"time"
"xk-websocket-v2/internal/model"
"xk-websocket-v2/internal/service"
"xk-websocket-v2/internal/utils"
"github.com/gin-gonic/gin"
)
/**
* GetMyInfoHandler
* 功能:获取当前用户信息
* 路径GET /api/user/my-info
* 需要JWT认证
*/
func GetMyInfoHandler(c *gin.Context) {
// 从Context获取用户ID由JWT中间件注入
userID, exists := c.Get("user_id")
if !exists {
utils.Unauthorized(c, "未认证")
return
}
user, err := service.UserSvc.GetUserByID(userID.(string))
if err != nil {
utils.NotFound(c, "用户不存在")
return
}
utils.SuccessWithData(c, user, "获取成功")
}
/**
* GetUserByIDHandler
* 功能:根据用户 ID 获取公开资料
* 路径GET /api/user/:id
*/
func GetUserByIDHandler(c *gin.Context) {
targetID := c.Param("id")
if targetID == "" {
utils.BadRequest(c, "用户ID不能为空")
return
}
user, err := service.UserSvc.GetUserByID(targetID)
if err != nil {
utils.NotFound(c, "用户不存在")
return
}
user.Password = ""
utils.SuccessWithData(c, user, "获取成功")
}
/**
* GetUserListHandler
* 功能:获取用户列表
* 路径GET /api/user/list
*/
func GetUserListHandler(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 20
}
users, total, err := service.UserSvc.GetUserList(page, pageSize)
if err != nil {
utils.InternalError(c, "查询失败")
return
}
// 确保返回空数组而不是null
if users == nil {
users = []model.User{}
}
utils.SuccessWithData(c, gin.H{
"data": users,
"total": total,
"page": page,
"size": pageSize,
}, "获取成功")
}
/**
* CreateUserHandler
* 功能:创建用户(管理员)
* 路径POST /api/user/create
*/
func CreateUserHandler(c *gin.Context) {
var user model.User
if err := c.ShouldBindJSON(&user); err != nil {
utils.BadRequest(c, "参数错误: "+err.Error())
return
}
// 生成用户ID
user.ID = generateUserID()
if err := service.UserSvc.CreateUser(&user); err != nil {
utils.BadRequest(c, "创建用户失败: "+err.Error())
return
}
user.Password = "" // 清除密码
utils.SuccessWithData(c, user, "创建成功")
}
/**
* UpdateUserHandler
* 功能:更新用户信息
* 路径POST /api/user/update
*/
func UpdateUserHandler(c *gin.Context) {
var req struct {
ID string `json:"id" binding:"required"`
Updates map[string]interface{} `json:"updates" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
utils.BadRequest(c, "参数错误: "+err.Error())
return
}
if err := service.UserSvc.UpdateUser(req.ID, req.Updates); err != nil {
utils.BadRequest(c, "更新失败: "+err.Error())
return
}
// 如果更新了头像或名称,通知好友
if service.ContactSvc != nil && service.ChatSvc != nil {
if _, hasName := req.Updates["name"]; hasName {
go notifyFriendsOfProfileUpdate(req.ID, req.Updates)
} else if _, hasAvatar := req.Updates["avatar"]; hasAvatar {
go notifyFriendsOfProfileUpdate(req.ID, req.Updates)
}
}
utils.Success(c, "更新成功")
}
/**
* notifyFriendsOfProfileUpdate
* 功能:通知好友用户信息更新
*/
func notifyFriendsOfProfileUpdate(userID string, updates map[string]interface{}) {
if service.ContactSvc == nil || service.ChatSvc == nil || service.UserSvc == nil {
return
}
// 获取更新后的用户信息
user, err := service.UserSvc.GetUserByID(userID)
if err != nil {
return
}
// 获取好友列表
friendIDs, err := service.ContactSvc.GetFriendUserIDs(userID)
if err != nil || len(friendIDs) == 0 {
return
}
// 构建通知消息
notifExtra := map[string]interface{}{
"type": "profile_update",
"user_id": userID,
"name": user.Name,
"avatar": user.Avatar,
"updates": updates,
}
notifExtraJSON, _ := json.Marshal(notifExtra)
// 发送给所有好友
for _, friendID := range friendIDs {
notifMsg := model.ChatMessage{
RoomID: userID,
SenderUserID: userID,
ReceiverUserID: friendID,
MessageType: model.MessageTypeFriendNotif,
Content: user.Name + " 更新了个人资料",
Extra: string(notifExtraJSON),
}
// 不持久化此类通知,直接推送
pushMsg := model.WsPayload{
RequestType: "receive_message",
Data: notifMsg,
}
msgBytes, _ := json.Marshal(pushMsg)
service.ChatSvc.DispatchMessage(friendID, msgBytes)
}
}
/**
* DeleteUserHandler
* 功能:删除用户
* 路径POST /api/user/delete
*/
func DeleteUserHandler(c *gin.Context) {
var req struct {
ID string `json:"id" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
utils.BadRequest(c, "参数错误")
return
}
if err := service.UserSvc.DeleteUser(req.ID); err != nil {
utils.BadRequest(c, "删除失败: "+err.Error())
return
}
utils.Success(c, "删除成功")
}
// 辅助函数生成用户ID
func generateUserID() string {
// 使用时间戳+随机数生成用户ID
timestamp := time.Now().UnixNano()
random := rand.Intn(1000000)
return fmt.Sprintf("user_%d_%d", timestamp, random)
}