admin_controller.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package controller
  2. import (
  3. "log"
  4. "net/http"
  5. "strconv"
  6. "github.com/2930134478/AI-CS/backend/service"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // AdminController 负责处理管理员相关的 HTTP 请求。
  10. type AdminController struct {
  11. authService *service.AuthService
  12. userService *service.UserService
  13. }
  14. // NewAdminController 创建 AdminController 实例。
  15. func NewAdminController(authService *service.AuthService, userService *service.UserService) *AdminController {
  16. return &AdminController{
  17. authService: authService,
  18. userService: userService,
  19. }
  20. }
  21. // checkAdminPermission 检查当前用户是否是管理员。
  22. // 暂时从 query 参数获取 current_user_id,后续可以改为从 JWT token 获取。
  23. func (a *AdminController) checkAdminPermission(c *gin.Context) (uint, bool) {
  24. userIDStr := c.Query("current_user_id")
  25. if userIDStr == "" {
  26. // 也可以从请求头获取
  27. userIDStr = c.GetHeader("X-Current-User-ID")
  28. }
  29. if userIDStr == "" {
  30. c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供当前用户ID"})
  31. return 0, false
  32. }
  33. userID, err := strconv.ParseUint(userIDStr, 10, 64)
  34. if err != nil || userID == 0 {
  35. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  36. return 0, false
  37. }
  38. // 检查用户是否是管理员
  39. user, err := a.userService.GetUser(uint(userID))
  40. if err != nil {
  41. c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
  42. return 0, false
  43. }
  44. if user.Role != "admin" {
  45. c.JSON(http.StatusForbidden, gin.H{"error": "权限不足,只有管理员才能执行此操作"})
  46. return 0, false
  47. }
  48. return uint(userID), true
  49. }
  50. type createAgentRequest struct {
  51. Username string `json:"username"`
  52. Password string `json:"password"`
  53. Role string `json:"role"`
  54. }
  55. // CreateAgent 处理创建客服或管理员账号的请求。
  56. func (a *AdminController) CreateAgent(c *gin.Context) {
  57. var req createAgentRequest
  58. if err := c.ShouldBindJSON(&req); err != nil {
  59. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  60. return
  61. }
  62. user, err := a.authService.CreateAgent(service.CreateAgentInput{
  63. Username: req.Username,
  64. Password: req.Password,
  65. Role: req.Role,
  66. })
  67. if err != nil {
  68. switch err {
  69. case service.ErrUsernameExists:
  70. c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在"})
  71. default:
  72. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  73. }
  74. return
  75. }
  76. c.JSON(http.StatusOK, gin.H{
  77. "message": "创建成功",
  78. "user_id": user.ID,
  79. "username": user.Username,
  80. "role": user.Role,
  81. })
  82. }
  83. // ListUsers 获取所有用户列表。
  84. func (a *AdminController) ListUsers(c *gin.Context) {
  85. // 检查权限
  86. currentUserID, ok := a.checkAdminPermission(c)
  87. if !ok {
  88. return
  89. }
  90. _ = currentUserID // 暂时不使用,但保留用于后续日志记录
  91. users, err := a.userService.ListUsers()
  92. if err != nil {
  93. log.Printf("❌ 获取用户列表失败: %v", err)
  94. c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户列表失败"})
  95. return
  96. }
  97. c.JSON(http.StatusOK, users)
  98. }
  99. // GetUser 获取用户详情。
  100. func (a *AdminController) GetUser(c *gin.Context) {
  101. // 检查权限
  102. currentUserID, ok := a.checkAdminPermission(c)
  103. if !ok {
  104. return
  105. }
  106. _ = currentUserID
  107. // 获取用户ID
  108. idStr := c.Param("id")
  109. id, err := strconv.ParseUint(idStr, 10, 64)
  110. if err != nil || id == 0 {
  111. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  112. return
  113. }
  114. user, err := a.userService.GetUser(uint(id))
  115. if err != nil {
  116. if err.Error() == "用户不存在" {
  117. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  118. } else {
  119. log.Printf("❌ 获取用户详情失败: %v", err)
  120. c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户详情失败"})
  121. }
  122. return
  123. }
  124. c.JSON(http.StatusOK, user)
  125. }
  126. // CreateUser 处理创建新用户的请求。
  127. func (a *AdminController) CreateUser(c *gin.Context) {
  128. // 检查权限
  129. currentUserID, ok := a.checkAdminPermission(c)
  130. if !ok {
  131. return
  132. }
  133. _ = currentUserID
  134. var req struct {
  135. Username string `json:"username"`
  136. Password string `json:"password"`
  137. Role string `json:"role"`
  138. Nickname *string `json:"nickname"`
  139. Email *string `json:"email"`
  140. }
  141. if err := c.ShouldBindJSON(&req); err != nil {
  142. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  143. return
  144. }
  145. user, err := a.userService.CreateUser(service.CreateUserInput{
  146. Username: req.Username,
  147. Password: req.Password,
  148. Role: req.Role,
  149. Nickname: req.Nickname,
  150. Email: req.Email,
  151. })
  152. if err != nil {
  153. switch err {
  154. case service.ErrUsernameExists:
  155. c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在"})
  156. default:
  157. log.Printf("❌ 创建用户失败: %v", err)
  158. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  159. }
  160. return
  161. }
  162. c.JSON(http.StatusOK, gin.H{
  163. "message": "创建成功",
  164. "user": user,
  165. })
  166. }
  167. // UpdateUser 处理更新用户信息的请求。
  168. func (a *AdminController) UpdateUser(c *gin.Context) {
  169. // 检查权限
  170. currentUserID, ok := a.checkAdminPermission(c)
  171. if !ok {
  172. return
  173. }
  174. _ = currentUserID
  175. // 获取用户ID
  176. idStr := c.Param("id")
  177. id, err := strconv.ParseUint(idStr, 10, 64)
  178. if err != nil || id == 0 {
  179. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  180. return
  181. }
  182. var req struct {
  183. Role *string `json:"role"`
  184. Nickname *string `json:"nickname"`
  185. Email *string `json:"email"`
  186. ReceiveAIConversations *bool `json:"receive_ai_conversations"`
  187. }
  188. if err := c.ShouldBindJSON(&req); err != nil {
  189. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  190. return
  191. }
  192. user, err := a.userService.UpdateUser(service.UpdateUserInput{
  193. UserID: uint(id),
  194. Role: req.Role,
  195. Nickname: req.Nickname,
  196. Email: req.Email,
  197. ReceiveAIConversations: req.ReceiveAIConversations,
  198. })
  199. if err != nil {
  200. if err.Error() == "用户不存在" {
  201. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  202. } else {
  203. log.Printf("❌ 更新用户失败: %v", err)
  204. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  205. }
  206. return
  207. }
  208. c.JSON(http.StatusOK, gin.H{
  209. "message": "更新成功",
  210. "user": user,
  211. })
  212. }
  213. // DeleteUser 处理删除用户的请求。
  214. func (a *AdminController) DeleteUser(c *gin.Context) {
  215. // 检查权限
  216. currentUserID, ok := a.checkAdminPermission(c)
  217. if !ok {
  218. return
  219. }
  220. // 获取用户ID
  221. idStr := c.Param("id")
  222. id, err := strconv.ParseUint(idStr, 10, 64)
  223. if err != nil || id == 0 {
  224. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  225. return
  226. }
  227. if err := a.userService.DeleteUser(uint(id), currentUserID); err != nil {
  228. if err.Error() == "用户不存在" {
  229. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  230. } else {
  231. log.Printf("❌ 删除用户失败: %v", err)
  232. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  233. }
  234. return
  235. }
  236. c.JSON(http.StatusOK, gin.H{"message": "删除成功"})
  237. }
  238. // UpdateUserPassword 处理更新用户密码的请求。
  239. func (a *AdminController) UpdateUserPassword(c *gin.Context) {
  240. // 检查权限
  241. currentUserID, ok := a.checkAdminPermission(c)
  242. if !ok {
  243. return
  244. }
  245. // 获取用户ID
  246. idStr := c.Param("id")
  247. id, err := strconv.ParseUint(idStr, 10, 64)
  248. if err != nil || id == 0 {
  249. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  250. return
  251. }
  252. var req struct {
  253. OldPassword *string `json:"old_password"`
  254. NewPassword string `json:"new_password"`
  255. }
  256. if err := c.ShouldBindJSON(&req); err != nil {
  257. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  258. return
  259. }
  260. // 判断是否是管理员修改其他用户密码
  261. isAdmin := uint(id) != currentUserID
  262. if err := a.userService.UpdateUserPassword(service.UpdatePasswordInput{
  263. UserID: uint(id),
  264. OldPassword: req.OldPassword,
  265. NewPassword: req.NewPassword,
  266. IsAdmin: isAdmin,
  267. }); err != nil {
  268. if err.Error() == "用户不存在" {
  269. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  270. } else {
  271. log.Printf("❌ 更新密码失败: %v", err)
  272. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  273. }
  274. return
  275. }
  276. c.JSON(http.StatusOK, gin.H{"message": "密码更新成功"})
  277. }