admin_controller.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. Permissions []string `json:"permissions"`
  55. }
  56. // CreateAgent 处理创建客服或管理员账号的请求。
  57. func (a *AdminController) CreateAgent(c *gin.Context) {
  58. var req createAgentRequest
  59. if err := c.ShouldBindJSON(&req); err != nil {
  60. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  61. return
  62. }
  63. user, err := a.authService.CreateAgent(service.CreateAgentInput{
  64. Username: req.Username,
  65. Password: req.Password,
  66. Role: req.Role,
  67. })
  68. if err != nil {
  69. switch err {
  70. case service.ErrUsernameExists:
  71. c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在"})
  72. default:
  73. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  74. }
  75. return
  76. }
  77. c.JSON(http.StatusOK, gin.H{
  78. "message": "创建成功",
  79. "user_id": user.ID,
  80. "username": user.Username,
  81. "role": user.Role,
  82. })
  83. }
  84. // ListUsers 获取所有用户列表。
  85. func (a *AdminController) ListUsers(c *gin.Context) {
  86. // 检查权限
  87. currentUserID, ok := a.checkAdminPermission(c)
  88. if !ok {
  89. return
  90. }
  91. _ = currentUserID // 暂时不使用,但保留用于后续日志记录
  92. users, err := a.userService.ListUsers()
  93. if err != nil {
  94. log.Printf("❌ 获取用户列表失败: %v", err)
  95. c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户列表失败"})
  96. return
  97. }
  98. c.JSON(http.StatusOK, users)
  99. }
  100. // GetUser 获取用户详情。
  101. func (a *AdminController) GetUser(c *gin.Context) {
  102. // 检查权限
  103. currentUserID, ok := a.checkAdminPermission(c)
  104. if !ok {
  105. return
  106. }
  107. _ = currentUserID
  108. // 获取用户ID
  109. idStr := c.Param("id")
  110. id, err := strconv.ParseUint(idStr, 10, 64)
  111. if err != nil || id == 0 {
  112. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  113. return
  114. }
  115. user, err := a.userService.GetUser(uint(id))
  116. if err != nil {
  117. if err.Error() == "用户不存在" {
  118. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  119. } else {
  120. log.Printf("❌ 获取用户详情失败: %v", err)
  121. c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户详情失败"})
  122. }
  123. return
  124. }
  125. c.JSON(http.StatusOK, user)
  126. }
  127. // CreateUser 处理创建新用户的请求。
  128. func (a *AdminController) CreateUser(c *gin.Context) {
  129. // 检查权限
  130. currentUserID, ok := a.checkAdminPermission(c)
  131. if !ok {
  132. return
  133. }
  134. _ = currentUserID
  135. var req struct {
  136. Username string `json:"username"`
  137. Password string `json:"password"`
  138. Role string `json:"role"`
  139. Permissions []string `json:"permissions"`
  140. Nickname *string `json:"nickname"`
  141. Email *string `json:"email"`
  142. }
  143. if err := c.ShouldBindJSON(&req); err != nil {
  144. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  145. return
  146. }
  147. user, err := a.userService.CreateUser(service.CreateUserInput{
  148. Username: req.Username,
  149. Password: req.Password,
  150. Role: req.Role,
  151. Permissions: req.Permissions,
  152. Nickname: req.Nickname,
  153. Email: req.Email,
  154. })
  155. if err != nil {
  156. switch err {
  157. case service.ErrUsernameExists:
  158. c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在"})
  159. default:
  160. log.Printf("❌ 创建用户失败: %v", err)
  161. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  162. }
  163. return
  164. }
  165. c.JSON(http.StatusOK, gin.H{
  166. "message": "创建成功",
  167. "user": user,
  168. })
  169. }
  170. // UpdateUser 处理更新用户信息的请求。
  171. func (a *AdminController) UpdateUser(c *gin.Context) {
  172. // 检查权限
  173. currentUserID, ok := a.checkAdminPermission(c)
  174. if !ok {
  175. return
  176. }
  177. _ = currentUserID
  178. // 获取用户ID
  179. idStr := c.Param("id")
  180. id, err := strconv.ParseUint(idStr, 10, 64)
  181. if err != nil || id == 0 {
  182. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  183. return
  184. }
  185. var req struct {
  186. Role *string `json:"role"`
  187. Permissions *[]string `json:"permissions"`
  188. Nickname *string `json:"nickname"`
  189. Email *string `json:"email"`
  190. ReceiveAIConversations *bool `json:"receive_ai_conversations"`
  191. }
  192. if err := c.ShouldBindJSON(&req); err != nil {
  193. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  194. return
  195. }
  196. user, err := a.userService.UpdateUser(service.UpdateUserInput{
  197. UserID: uint(id),
  198. Role: req.Role,
  199. Permissions: req.Permissions,
  200. Nickname: req.Nickname,
  201. Email: req.Email,
  202. ReceiveAIConversations: req.ReceiveAIConversations,
  203. })
  204. if err != nil {
  205. if err.Error() == "用户不存在" {
  206. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  207. } else {
  208. log.Printf("❌ 更新用户失败: %v", err)
  209. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  210. }
  211. return
  212. }
  213. c.JSON(http.StatusOK, gin.H{
  214. "message": "更新成功",
  215. "user": user,
  216. })
  217. }
  218. // DeleteUser 处理删除用户的请求。
  219. func (a *AdminController) DeleteUser(c *gin.Context) {
  220. // 检查权限
  221. currentUserID, ok := a.checkAdminPermission(c)
  222. if !ok {
  223. return
  224. }
  225. // 获取用户ID
  226. idStr := c.Param("id")
  227. id, err := strconv.ParseUint(idStr, 10, 64)
  228. if err != nil || id == 0 {
  229. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  230. return
  231. }
  232. transferred, err := a.userService.DeleteUser(uint(id), currentUserID)
  233. if err != nil {
  234. if err.Error() == "用户不存在" {
  235. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  236. } else {
  237. log.Printf("❌ 删除用户失败: %v", err)
  238. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  239. }
  240. return
  241. }
  242. c.JSON(http.StatusOK, gin.H{
  243. "message": "删除成功",
  244. "transferred_ai_configs": transferred,
  245. })
  246. }
  247. // UpdateUserPassword 处理更新用户密码的请求。
  248. func (a *AdminController) UpdateUserPassword(c *gin.Context) {
  249. // 检查权限
  250. currentUserID, ok := a.checkAdminPermission(c)
  251. if !ok {
  252. return
  253. }
  254. // 获取用户ID
  255. idStr := c.Param("id")
  256. id, err := strconv.ParseUint(idStr, 10, 64)
  257. if err != nil || id == 0 {
  258. c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不合法"})
  259. return
  260. }
  261. var req struct {
  262. OldPassword *string `json:"old_password"`
  263. NewPassword string `json:"new_password"`
  264. }
  265. if err := c.ShouldBindJSON(&req); err != nil {
  266. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  267. return
  268. }
  269. // 判断是否是管理员修改其他用户密码
  270. isAdmin := uint(id) != currentUserID
  271. if err := a.userService.UpdateUserPassword(service.UpdatePasswordInput{
  272. UserID: uint(id),
  273. OldPassword: req.OldPassword,
  274. NewPassword: req.NewPassword,
  275. IsAdmin: isAdmin,
  276. }); err != nil {
  277. if err.Error() == "用户不存在" {
  278. c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
  279. } else {
  280. log.Printf("❌ 更新密码失败: %v", err)
  281. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  282. }
  283. return
  284. }
  285. c.JSON(http.StatusOK, gin.H{"message": "密码更新成功"})
  286. }