您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

1191 行
30 KiB

  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/i18n"
  14. "github.com/QuantumNous/new-api/logger"
  15. "github.com/QuantumNous/new-api/middleware"
  16. "github.com/QuantumNous/new-api/model"
  17. "github.com/QuantumNous/new-api/service"
  18. "github.com/QuantumNous/new-api/service/region_sync"
  19. "github.com/QuantumNous/new-api/setting"
  20. "github.com/QuantumNous/new-api/constant"
  21. "github.com/gin-contrib/sessions"
  22. "github.com/gin-gonic/gin"
  23. )
  24. type LoginRequest struct {
  25. Username string `json:"username"`
  26. Password string `json:"password"`
  27. }
  28. func Login(c *gin.Context) {
  29. if !common.PasswordLoginEnabled {
  30. common.ApiErrorI18n(c, i18n.MsgUserPasswordLoginDisabled)
  31. return
  32. }
  33. var loginRequest LoginRequest
  34. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  35. if err != nil {
  36. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  37. return
  38. }
  39. username := loginRequest.Username
  40. password := loginRequest.Password
  41. if username == "" || password == "" {
  42. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  43. return
  44. }
  45. user := model.User{
  46. Username: username,
  47. Password: password,
  48. }
  49. err = user.ValidateAndFill()
  50. if err != nil {
  51. c.JSON(http.StatusOK, gin.H{
  52. "message": err.Error(),
  53. "success": false,
  54. })
  55. return
  56. }
  57. // 检查是否启用2FA
  58. if model.IsTwoFAEnabled(user.Id) {
  59. // 设置pending session,等待2FA验证
  60. session := sessions.Default(c)
  61. session.Set("pending_username", user.Username)
  62. session.Set("pending_user_id", user.Id)
  63. err := session.Save()
  64. if err != nil {
  65. common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
  66. return
  67. }
  68. c.JSON(http.StatusOK, gin.H{
  69. "message": i18n.T(c, i18n.MsgUserRequire2FA),
  70. "success": true,
  71. "data": map[string]interface{}{
  72. "require_2fa": true,
  73. },
  74. })
  75. return
  76. }
  77. setupLogin(&user, c)
  78. }
  79. // setup session & cookies and then return user info
  80. func setupLogin(user *model.User, c *gin.Context) {
  81. session := sessions.Default(c)
  82. session.Set("id", user.Id)
  83. session.Set("username", user.Username)
  84. session.Set("role", user.Role)
  85. session.Set("status", user.Status)
  86. session.Set("group", user.Group)
  87. err := session.Save()
  88. if err != nil {
  89. common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
  90. return
  91. }
  92. c.JSON(http.StatusOK, gin.H{
  93. "message": "",
  94. "success": true,
  95. "data": map[string]any{
  96. "id": user.Id,
  97. "username": user.Username,
  98. "display_name": user.DisplayName,
  99. "role": user.Role,
  100. "status": user.Status,
  101. "group": user.Group,
  102. },
  103. })
  104. }
  105. func Logout(c *gin.Context) {
  106. session := sessions.Default(c)
  107. session.Clear()
  108. err := session.Save()
  109. if err != nil {
  110. c.JSON(http.StatusOK, gin.H{
  111. "message": err.Error(),
  112. "success": false,
  113. })
  114. return
  115. }
  116. c.JSON(http.StatusOK, gin.H{
  117. "message": "",
  118. "success": true,
  119. })
  120. }
  121. func Register(c *gin.Context) {
  122. if !common.RegisterEnabled {
  123. common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled)
  124. return
  125. }
  126. if !common.PasswordRegisterEnabled {
  127. common.ApiErrorI18n(c, i18n.MsgUserPasswordRegisterDisabled)
  128. return
  129. }
  130. var user model.User
  131. err := json.NewDecoder(c.Request.Body).Decode(&user)
  132. if err != nil {
  133. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  134. return
  135. }
  136. if err := common.Validate.Struct(&user); err != nil {
  137. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  138. return
  139. }
  140. if common.EmailVerificationEnabled {
  141. if user.Email == "" || user.VerificationCode == "" {
  142. common.ApiErrorI18n(c, i18n.MsgUserEmailVerificationRequired)
  143. return
  144. }
  145. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  146. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  147. return
  148. }
  149. }
  150. exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
  151. if err != nil {
  152. common.ApiErrorI18n(c, i18n.MsgDatabaseError)
  153. common.SysLog(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
  154. return
  155. }
  156. if exist {
  157. common.ApiErrorI18n(c, i18n.MsgUserExists)
  158. return
  159. }
  160. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  161. inviterId, _ := model.GetUserIdByAffCode(affCode)
  162. cleanUser := model.User{
  163. Username: user.Username,
  164. Password: user.Password,
  165. DisplayName: user.Username,
  166. InviterId: inviterId,
  167. Role: common.RoleCommonUser, // 明确设置角色为普通用户
  168. }
  169. if common.EmailVerificationEnabled {
  170. cleanUser.Email = user.Email
  171. }
  172. if err := cleanUser.Insert(inviterId); err != nil {
  173. common.ApiError(c, err)
  174. return
  175. }
  176. // 同步用户到海外节点(异步执行,不阻塞注册流程)
  177. region_sync.PushUserCreateToSlave(&cleanUser)
  178. // 生成默认令牌
  179. if constant.GenerateDefaultToken {
  180. key, err := common.GenerateKey()
  181. if err != nil {
  182. common.ApiErrorI18n(c, i18n.MsgUserDefaultTokenFailed)
  183. common.SysLog("failed to generate token key: " + err.Error())
  184. return
  185. }
  186. // 生成默认令牌
  187. token := model.Token{
  188. UserId: cleanUser.Id, // GORM Create 后已填充 ID
  189. Name: cleanUser.Username + "的初始令牌",
  190. Key: key,
  191. CreatedTime: common.GetTimestamp(),
  192. AccessedTime: common.GetTimestamp(),
  193. ExpiredTime: -1, // 永不过期
  194. RemainQuota: 500000, // 示例额度
  195. UnlimitedQuota: true,
  196. ModelLimitsEnabled: false,
  197. }
  198. if setting.DefaultUseAutoGroup {
  199. token.Group = "auto"
  200. }
  201. if err := token.Insert(); err != nil {
  202. common.ApiErrorI18n(c, i18n.MsgCreateDefaultTokenErr)
  203. return
  204. }
  205. }
  206. c.JSON(http.StatusOK, gin.H{
  207. "success": true,
  208. "message": "",
  209. })
  210. return
  211. }
  212. func GetAllUsers(c *gin.Context) {
  213. pageInfo := common.GetPageQuery(c)
  214. users, total, err := model.GetAllUsers(pageInfo)
  215. if err != nil {
  216. common.ApiError(c, err)
  217. return
  218. }
  219. pageInfo.SetTotal(int(total))
  220. pageInfo.SetItems(users)
  221. common.ApiSuccess(c, pageInfo)
  222. return
  223. }
  224. func SearchUsers(c *gin.Context) {
  225. keyword := c.Query("keyword")
  226. group := c.Query("group")
  227. pageInfo := common.GetPageQuery(c)
  228. users, total, err := model.SearchUsers(keyword, group, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  229. if err != nil {
  230. common.ApiError(c, err)
  231. return
  232. }
  233. pageInfo.SetTotal(int(total))
  234. pageInfo.SetItems(users)
  235. common.ApiSuccess(c, pageInfo)
  236. return
  237. }
  238. func GetUser(c *gin.Context) {
  239. id, err := strconv.Atoi(c.Param("id"))
  240. if err != nil {
  241. common.ApiError(c, err)
  242. return
  243. }
  244. user, err := model.GetUserById(id, false)
  245. if err != nil {
  246. common.ApiError(c, err)
  247. return
  248. }
  249. myRole := c.GetInt("role")
  250. if myRole <= user.Role && myRole != common.RoleRootUser {
  251. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  252. return
  253. }
  254. user.ApplySyncedQuota()
  255. c.JSON(http.StatusOK, gin.H{
  256. "success": true,
  257. "message": "",
  258. "data": user,
  259. })
  260. return
  261. }
  262. func GenerateAccessToken(c *gin.Context) {
  263. id := c.GetInt("id")
  264. user, err := model.GetUserById(id, true)
  265. if err != nil {
  266. common.ApiError(c, err)
  267. return
  268. }
  269. // get rand int 28-32
  270. randI := common.GetRandomInt(4)
  271. key, err := common.GenerateRandomKey(29 + randI)
  272. if err != nil {
  273. common.ApiErrorI18n(c, i18n.MsgGenerateFailed)
  274. common.SysLog("failed to generate key: " + err.Error())
  275. return
  276. }
  277. user.SetAccessToken(key)
  278. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  279. common.ApiErrorI18n(c, i18n.MsgUuidDuplicate)
  280. return
  281. }
  282. if err := user.Update(false); err != nil {
  283. common.ApiError(c, err)
  284. return
  285. }
  286. c.JSON(http.StatusOK, gin.H{
  287. "success": true,
  288. "message": "",
  289. "data": user.AccessToken,
  290. })
  291. return
  292. }
  293. type TransferAffQuotaRequest struct {
  294. Quota int `json:"quota" binding:"required"`
  295. }
  296. func TransferAffQuota(c *gin.Context) {
  297. id := c.GetInt("id")
  298. user, err := model.GetUserById(id, true)
  299. if err != nil {
  300. common.ApiError(c, err)
  301. return
  302. }
  303. tran := TransferAffQuotaRequest{}
  304. if err := c.ShouldBindJSON(&tran); err != nil {
  305. common.ApiError(c, err)
  306. return
  307. }
  308. err = user.TransferAffQuotaToQuota(tran.Quota)
  309. if err != nil {
  310. common.ApiErrorI18n(c, i18n.MsgUserTransferFailed, map[string]any{"Error": err.Error()})
  311. return
  312. }
  313. common.ApiSuccessI18n(c, i18n.MsgUserTransferSuccess, nil)
  314. }
  315. func GetAffCode(c *gin.Context) {
  316. id := c.GetInt("id")
  317. user, err := model.GetUserById(id, true)
  318. if err != nil {
  319. common.ApiError(c, err)
  320. return
  321. }
  322. if user.AffCode == "" {
  323. user.AffCode = common.GetRandomString(4)
  324. if err := user.Update(false); err != nil {
  325. c.JSON(http.StatusOK, gin.H{
  326. "success": false,
  327. "message": err.Error(),
  328. })
  329. return
  330. }
  331. }
  332. c.JSON(http.StatusOK, gin.H{
  333. "success": true,
  334. "message": "",
  335. "data": user.AffCode,
  336. })
  337. return
  338. }
  339. func GetSelf(c *gin.Context) {
  340. id := c.GetInt("id")
  341. userRole := c.GetInt("role")
  342. user, err := model.GetUserById(id, false)
  343. if err != nil {
  344. common.ApiError(c, err)
  345. return
  346. }
  347. // Hide admin remarks: set to empty to trigger omitempty tag, ensuring the remark field is not included in JSON returned to regular users
  348. user.Remark = ""
  349. // 计算用户权限信息
  350. permissions := calculateUserPermissions(userRole)
  351. // 获取用户设置并提取sidebar_modules
  352. userSetting := user.GetSetting()
  353. // 构建响应数据,包含用户信息和权限
  354. // Slave 节点使用 SyncedQuota 作为用户额度
  355. quota := user.Quota
  356. if user.IsSyncedUser() {
  357. quota = user.SyncedQuota
  358. }
  359. responseData := map[string]interface{}{
  360. "id": user.Id,
  361. "username": user.Username,
  362. "display_name": user.DisplayName,
  363. "role": user.Role,
  364. "status": user.Status,
  365. "email": user.Email,
  366. "github_id": user.GitHubId,
  367. "discord_id": user.DiscordId,
  368. "oidc_id": user.OidcId,
  369. "wechat_id": user.WeChatId,
  370. "telegram_id": user.TelegramId,
  371. "group": user.Group,
  372. "quota": quota,
  373. "used_quota": user.UsedQuota,
  374. "request_count": user.RequestCount,
  375. "aff_code": user.AffCode,
  376. "aff_count": user.AffCount,
  377. "aff_quota": user.AffQuota,
  378. "aff_history_quota": user.AffHistoryQuota,
  379. "inviter_id": user.InviterId,
  380. "linux_do_id": user.LinuxDOId,
  381. "setting": user.Setting,
  382. "stripe_customer": user.StripeCustomer,
  383. "sidebar_modules": userSetting.SidebarModules, // 正确提取sidebar_modules字段
  384. "permissions": permissions, // 新增权限字段
  385. }
  386. c.JSON(http.StatusOK, gin.H{
  387. "success": true,
  388. "message": "",
  389. "data": responseData,
  390. })
  391. return
  392. }
  393. // 计算用户权限的辅助函数
  394. func calculateUserPermissions(userRole int) map[string]interface{} {
  395. permissions := map[string]interface{}{}
  396. // 根据用户角色计算权限
  397. if userRole == common.RoleRootUser {
  398. // 超级管理员不需要边栏设置功能
  399. permissions["sidebar_settings"] = false
  400. permissions["sidebar_modules"] = map[string]interface{}{}
  401. } else if userRole == common.RoleAdminUser {
  402. // 管理员可以设置边栏,但不包含系统设置功能
  403. permissions["sidebar_settings"] = true
  404. permissions["sidebar_modules"] = map[string]interface{}{
  405. "admin": map[string]interface{}{
  406. "setting": false, // 管理员不能访问系统设置
  407. },
  408. }
  409. } else {
  410. // 普通用户只能设置个人功能,不包含管理员区域
  411. permissions["sidebar_settings"] = true
  412. permissions["sidebar_modules"] = map[string]interface{}{
  413. "admin": false, // 普通用户不能访问管理员区域
  414. }
  415. }
  416. return permissions
  417. }
  418. // 根据用户角色生成默认的边栏配置
  419. func generateDefaultSidebarConfig(userRole int) string {
  420. defaultConfig := map[string]interface{}{}
  421. // 聊天区域 - 所有用户都可以访问
  422. defaultConfig["chat"] = map[string]interface{}{
  423. "enabled": true,
  424. "playground": true,
  425. "chat": true,
  426. }
  427. // 控制台区域 - 所有用户都可以访问
  428. defaultConfig["console"] = map[string]interface{}{
  429. "enabled": true,
  430. "detail": true,
  431. "token": true,
  432. "log": true,
  433. "midjourney": true,
  434. "task": true,
  435. }
  436. // 个人中心区域 - 所有用户都可以访问
  437. defaultConfig["personal"] = map[string]interface{}{
  438. "enabled": true,
  439. "topup": true,
  440. "personal": true,
  441. }
  442. // 管理员区域 - 根据角色决定
  443. if userRole == common.RoleAdminUser {
  444. // 管理员可以访问管理员区域,但不能访问系统设置
  445. defaultConfig["admin"] = map[string]interface{}{
  446. "enabled": true,
  447. "channel": true,
  448. "models": true,
  449. "redemption": true,
  450. "user": true,
  451. "setting": false, // 管理员不能访问系统设置
  452. }
  453. } else if userRole == common.RoleRootUser {
  454. // 超级管理员可以访问所有功能
  455. defaultConfig["admin"] = map[string]interface{}{
  456. "enabled": true,
  457. "channel": true,
  458. "models": true,
  459. "redemption": true,
  460. "user": true,
  461. "setting": true,
  462. }
  463. }
  464. // 普通用户不包含admin区域
  465. // 转换为JSON字符串
  466. configBytes, err := json.Marshal(defaultConfig)
  467. if err != nil {
  468. common.SysLog("生成默认边栏配置失败: " + err.Error())
  469. return ""
  470. }
  471. return string(configBytes)
  472. }
  473. func GetUserModels(c *gin.Context) {
  474. id, err := strconv.Atoi(c.Param("id"))
  475. if err != nil {
  476. id = c.GetInt("id")
  477. }
  478. user, err := model.GetUserCache(id)
  479. if err != nil {
  480. common.ApiError(c, err)
  481. return
  482. }
  483. groups := service.GetUserUsableGroups(user.Group)
  484. var models []string
  485. seen := make(map[string]struct{})
  486. for group := range groups {
  487. for _, g := range model.GetGroupEnabledModels(group) {
  488. if _, ok := seen[g]; !ok {
  489. seen[g] = struct{}{}
  490. models = append(models, g)
  491. }
  492. }
  493. }
  494. models = common.StringsSubtract(models, model.GetDisabledModelNames(models))
  495. c.JSON(http.StatusOK, gin.H{
  496. "success": true,
  497. "message": "",
  498. "data": models,
  499. })
  500. return
  501. }
  502. func UpdateUser(c *gin.Context) {
  503. var updatedUser model.User
  504. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  505. if err != nil || updatedUser.Id == 0 {
  506. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  507. return
  508. }
  509. if updatedUser.Password == "" {
  510. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  511. }
  512. if err := common.Validate.Struct(&updatedUser); err != nil {
  513. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  514. return
  515. }
  516. originUser, err := model.GetUserById(updatedUser.Id, false)
  517. if err != nil {
  518. common.ApiError(c, err)
  519. return
  520. }
  521. myRole := c.GetInt("role")
  522. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  523. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  524. return
  525. }
  526. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  527. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  528. return
  529. }
  530. if updatedUser.Password == "$I_LOVE_U" {
  531. updatedUser.Password = "" // rollback to what it should be
  532. }
  533. updatePassword := updatedUser.Password != ""
  534. if err := updatedUser.Edit(updatePassword); err != nil {
  535. common.ApiError(c, err)
  536. return
  537. }
  538. middleware.SetCaptureEnabled(int64(updatedUser.Id), updatedUser.CaptureRelay)
  539. if originUser.Quota != updatedUser.Quota {
  540. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", logger.LogQuota(originUser.Quota), logger.LogQuota(updatedUser.Quota)))
  541. }
  542. c.JSON(http.StatusOK, gin.H{
  543. "success": true,
  544. "message": "",
  545. })
  546. return
  547. }
  548. func AdminClearUserBinding(c *gin.Context) {
  549. id, err := strconv.Atoi(c.Param("id"))
  550. if err != nil {
  551. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  552. return
  553. }
  554. bindingType := strings.ToLower(strings.TrimSpace(c.Param("binding_type")))
  555. if bindingType == "" {
  556. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  557. return
  558. }
  559. user, err := model.GetUserById(id, false)
  560. if err != nil {
  561. common.ApiError(c, err)
  562. return
  563. }
  564. myRole := c.GetInt("role")
  565. if myRole <= user.Role && myRole != common.RoleRootUser {
  566. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  567. return
  568. }
  569. if err := user.ClearBinding(bindingType); err != nil {
  570. common.ApiError(c, err)
  571. return
  572. }
  573. model.RecordLog(user.Id, model.LogTypeManage, fmt.Sprintf("admin cleared %s binding for user %s", bindingType, user.Username))
  574. c.JSON(http.StatusOK, gin.H{
  575. "success": true,
  576. "message": "success",
  577. })
  578. }
  579. func UpdateSelf(c *gin.Context) {
  580. var requestData map[string]interface{}
  581. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  582. if err != nil {
  583. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  584. return
  585. }
  586. // 检查是否是用户设置更新请求 (sidebar_modules 或 language)
  587. if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
  588. userId := c.GetInt("id")
  589. user, err := model.GetUserById(userId, false)
  590. if err != nil {
  591. common.ApiError(c, err)
  592. return
  593. }
  594. // 获取当前用户设置
  595. currentSetting := user.GetSetting()
  596. // 更新sidebar_modules字段
  597. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  598. currentSetting.SidebarModules = sidebarModulesStr
  599. }
  600. // 保存更新后的设置
  601. user.SetSetting(currentSetting)
  602. if err := user.Update(false); err != nil {
  603. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  604. return
  605. }
  606. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  607. return
  608. }
  609. // 检查是否是语言偏好更新请求
  610. if language, langExists := requestData["language"]; langExists {
  611. userId := c.GetInt("id")
  612. user, err := model.GetUserById(userId, false)
  613. if err != nil {
  614. common.ApiError(c, err)
  615. return
  616. }
  617. // 获取当前用户设置
  618. currentSetting := user.GetSetting()
  619. // 更新language字段
  620. if langStr, ok := language.(string); ok {
  621. currentSetting.Language = langStr
  622. }
  623. // 保存更新后的设置
  624. user.SetSetting(currentSetting)
  625. if err := user.Update(false); err != nil {
  626. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  627. return
  628. }
  629. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  630. return
  631. }
  632. // 原有的用户信息更新逻辑
  633. var user model.User
  634. requestDataBytes, err := json.Marshal(requestData)
  635. if err != nil {
  636. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  637. return
  638. }
  639. err = json.Unmarshal(requestDataBytes, &user)
  640. if err != nil {
  641. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  642. return
  643. }
  644. if user.Password == "" {
  645. user.Password = "$I_LOVE_U" // make Validator happy :)
  646. }
  647. if err := common.Validate.Struct(&user); err != nil {
  648. common.ApiErrorI18n(c, i18n.MsgInvalidInput)
  649. return
  650. }
  651. cleanUser := model.User{
  652. Id: c.GetInt("id"),
  653. Username: user.Username,
  654. Password: user.Password,
  655. DisplayName: user.DisplayName,
  656. }
  657. if user.Password == "$I_LOVE_U" {
  658. user.Password = "" // rollback to what it should be
  659. cleanUser.Password = ""
  660. }
  661. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  662. if err != nil {
  663. common.ApiError(c, err)
  664. return
  665. }
  666. if err := cleanUser.Update(updatePassword); err != nil {
  667. common.ApiError(c, err)
  668. return
  669. }
  670. c.JSON(http.StatusOK, gin.H{
  671. "success": true,
  672. "message": "",
  673. })
  674. return
  675. }
  676. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  677. var currentUser *model.User
  678. currentUser, err = model.GetUserById(userId, true)
  679. if err != nil {
  680. return
  681. }
  682. // 密码不为空,需要验证原密码
  683. // 支持第一次账号绑定时原密码为空的情况
  684. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) && currentUser.Password != "" {
  685. err = fmt.Errorf("原密码错误")
  686. return
  687. }
  688. if newPassword == "" {
  689. return
  690. }
  691. updatePassword = true
  692. return
  693. }
  694. func DeleteUser(c *gin.Context) {
  695. id, err := strconv.Atoi(c.Param("id"))
  696. if err != nil {
  697. common.ApiError(c, err)
  698. return
  699. }
  700. originUser, err := model.GetUserById(id, false)
  701. if err != nil {
  702. common.ApiError(c, err)
  703. return
  704. }
  705. myRole := c.GetInt("role")
  706. if myRole <= originUser.Role {
  707. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  708. return
  709. }
  710. err = model.HardDeleteUserById(id)
  711. if err != nil {
  712. c.JSON(http.StatusOK, gin.H{
  713. "success": true,
  714. "message": "",
  715. })
  716. return
  717. }
  718. }
  719. func DeleteSelf(c *gin.Context) {
  720. id := c.GetInt("id")
  721. user, _ := model.GetUserById(id, false)
  722. if user.Role == common.RoleRootUser {
  723. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  724. return
  725. }
  726. err := model.DeleteUserById(id)
  727. if err != nil {
  728. common.ApiError(c, err)
  729. return
  730. }
  731. c.JSON(http.StatusOK, gin.H{
  732. "success": true,
  733. "message": "",
  734. })
  735. return
  736. }
  737. func CreateUser(c *gin.Context) {
  738. var user model.User
  739. err := json.NewDecoder(c.Request.Body).Decode(&user)
  740. user.Username = strings.TrimSpace(user.Username)
  741. if err != nil || user.Username == "" || user.Password == "" {
  742. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  743. return
  744. }
  745. if err := common.Validate.Struct(&user); err != nil {
  746. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  747. return
  748. }
  749. if user.DisplayName == "" {
  750. user.DisplayName = user.Username
  751. }
  752. myRole := c.GetInt("role")
  753. if user.Role >= myRole {
  754. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  755. return
  756. }
  757. // Even for admin users, we cannot fully trust them!
  758. cleanUser := model.User{
  759. Username: user.Username,
  760. Password: user.Password,
  761. DisplayName: user.DisplayName,
  762. Role: user.Role, // 保持管理员设置的角色
  763. }
  764. if err := cleanUser.Insert(0); err != nil {
  765. common.ApiError(c, err)
  766. return
  767. }
  768. c.JSON(http.StatusOK, gin.H{
  769. "success": true,
  770. "message": "",
  771. })
  772. return
  773. }
  774. type ManageRequest struct {
  775. Id int `json:"id"`
  776. Action string `json:"action"`
  777. }
  778. // ManageUser Only admin user can do this
  779. func ManageUser(c *gin.Context) {
  780. var req ManageRequest
  781. err := json.NewDecoder(c.Request.Body).Decode(&req)
  782. if err != nil {
  783. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  784. return
  785. }
  786. user := model.User{
  787. Id: req.Id,
  788. }
  789. // Fill attributes
  790. model.DB.Unscoped().Where(&user).First(&user)
  791. if user.Id == 0 {
  792. common.ApiErrorI18n(c, i18n.MsgUserNotExists)
  793. return
  794. }
  795. myRole := c.GetInt("role")
  796. if myRole <= user.Role && myRole != common.RoleRootUser {
  797. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  798. return
  799. }
  800. switch req.Action {
  801. case "disable":
  802. user.Status = common.UserStatusDisabled
  803. if user.Role == common.RoleRootUser {
  804. common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
  805. return
  806. }
  807. case "enable":
  808. user.Status = common.UserStatusEnabled
  809. case "delete":
  810. if user.Role == common.RoleRootUser {
  811. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  812. return
  813. }
  814. if err := user.Delete(); err != nil {
  815. c.JSON(http.StatusOK, gin.H{
  816. "success": false,
  817. "message": err.Error(),
  818. })
  819. return
  820. }
  821. case "promote":
  822. if myRole != common.RoleRootUser {
  823. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  824. return
  825. }
  826. if user.Role >= common.RoleAdminUser {
  827. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  828. return
  829. }
  830. user.Role = common.RoleAdminUser
  831. case "demote":
  832. if user.Role == common.RoleRootUser {
  833. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  834. return
  835. }
  836. if user.Role == common.RoleCommonUser {
  837. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  838. return
  839. }
  840. user.Role = common.RoleCommonUser
  841. }
  842. if err := user.Update(false); err != nil {
  843. common.ApiError(c, err)
  844. return
  845. }
  846. clearUser := model.User{
  847. Role: user.Role,
  848. Status: user.Status,
  849. }
  850. c.JSON(http.StatusOK, gin.H{
  851. "success": true,
  852. "message": "",
  853. "data": clearUser,
  854. })
  855. return
  856. }
  857. func EmailBind(c *gin.Context) {
  858. email := c.Query("email")
  859. code := c.Query("code")
  860. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  861. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  862. return
  863. }
  864. session := sessions.Default(c)
  865. id := session.Get("id")
  866. user := model.User{
  867. Id: id.(int),
  868. }
  869. err := user.FillUserById()
  870. if err != nil {
  871. common.ApiError(c, err)
  872. return
  873. }
  874. user.Email = email
  875. // no need to check if this email already taken, because we have used verification code to check it
  876. err = user.Update(false)
  877. if err != nil {
  878. common.ApiError(c, err)
  879. return
  880. }
  881. c.JSON(http.StatusOK, gin.H{
  882. "success": true,
  883. "message": "",
  884. })
  885. return
  886. }
  887. type topUpRequest struct {
  888. Key string `json:"key"`
  889. }
  890. var topUpLocks sync.Map
  891. var topUpCreateLock sync.Mutex
  892. type topUpTryLock struct {
  893. ch chan struct{}
  894. }
  895. func newTopUpTryLock() *topUpTryLock {
  896. return &topUpTryLock{ch: make(chan struct{}, 1)}
  897. }
  898. func (l *topUpTryLock) TryLock() bool {
  899. select {
  900. case l.ch <- struct{}{}:
  901. return true
  902. default:
  903. return false
  904. }
  905. }
  906. func (l *topUpTryLock) Unlock() {
  907. select {
  908. case <-l.ch:
  909. default:
  910. }
  911. }
  912. func getTopUpLock(userID int) *topUpTryLock {
  913. if v, ok := topUpLocks.Load(userID); ok {
  914. return v.(*topUpTryLock)
  915. }
  916. topUpCreateLock.Lock()
  917. defer topUpCreateLock.Unlock()
  918. if v, ok := topUpLocks.Load(userID); ok {
  919. return v.(*topUpTryLock)
  920. }
  921. l := newTopUpTryLock()
  922. topUpLocks.Store(userID, l)
  923. return l
  924. }
  925. func TopUp(c *gin.Context) {
  926. id := c.GetInt("id")
  927. lock := getTopUpLock(id)
  928. if !lock.TryLock() {
  929. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  930. return
  931. }
  932. defer lock.Unlock()
  933. req := topUpRequest{}
  934. err := c.ShouldBindJSON(&req)
  935. if err != nil {
  936. common.ApiError(c, err)
  937. return
  938. }
  939. quota, err := model.Redeem(req.Key, id)
  940. if err != nil {
  941. if errors.Is(err, model.ErrRedeemFailed) {
  942. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  943. return
  944. }
  945. common.ApiError(c, err)
  946. return
  947. }
  948. c.JSON(http.StatusOK, gin.H{
  949. "success": true,
  950. "message": "",
  951. "data": quota,
  952. })
  953. }
  954. type UpdateUserSettingRequest struct {
  955. QuotaWarningType string `json:"notify_type"`
  956. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  957. WebhookUrl string `json:"webhook_url,omitempty"`
  958. WebhookSecret string `json:"webhook_secret,omitempty"`
  959. NotificationEmail string `json:"notification_email,omitempty"`
  960. BarkUrl string `json:"bark_url,omitempty"`
  961. GotifyUrl string `json:"gotify_url,omitempty"`
  962. GotifyToken string `json:"gotify_token,omitempty"`
  963. GotifyPriority int `json:"gotify_priority,omitempty"`
  964. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  965. RecordIpLog bool `json:"record_ip_log"`
  966. }
  967. func UpdateUserSetting(c *gin.Context) {
  968. var req UpdateUserSettingRequest
  969. if err := c.ShouldBindJSON(&req); err != nil {
  970. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  971. return
  972. }
  973. // 验证预警类型
  974. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  975. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  976. return
  977. }
  978. // 验证预警阈值
  979. if req.QuotaWarningThreshold <= 0 {
  980. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  981. return
  982. }
  983. // 如果是webhook类型,验证webhook地址
  984. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  985. if req.WebhookUrl == "" {
  986. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  987. return
  988. }
  989. // 验证URL格式
  990. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  991. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  992. return
  993. }
  994. }
  995. // 如果是邮件类型,验证邮箱地址
  996. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  997. // 验证邮箱格式
  998. if !strings.Contains(req.NotificationEmail, "@") {
  999. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  1000. return
  1001. }
  1002. }
  1003. // 如果是Bark类型,验证Bark URL
  1004. if req.QuotaWarningType == dto.NotifyTypeBark {
  1005. if req.BarkUrl == "" {
  1006. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  1007. return
  1008. }
  1009. // 验证URL格式
  1010. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1011. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  1012. return
  1013. }
  1014. // 检查是否是HTTP或HTTPS
  1015. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1016. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1017. return
  1018. }
  1019. }
  1020. // 如果是Gotify类型,验证Gotify URL和Token
  1021. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1022. if req.GotifyUrl == "" {
  1023. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  1024. return
  1025. }
  1026. if req.GotifyToken == "" {
  1027. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  1028. return
  1029. }
  1030. // 验证URL格式
  1031. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  1032. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  1033. return
  1034. }
  1035. // 检查是否是HTTP或HTTPS
  1036. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  1037. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1038. return
  1039. }
  1040. }
  1041. userId := c.GetInt("id")
  1042. user, err := model.GetUserById(userId, true)
  1043. if err != nil {
  1044. common.ApiError(c, err)
  1045. return
  1046. }
  1047. // 构建设置
  1048. settings := dto.UserSetting{
  1049. NotifyType: req.QuotaWarningType,
  1050. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1051. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1052. RecordIpLog: req.RecordIpLog,
  1053. }
  1054. // 如果是webhook类型,添加webhook相关设置
  1055. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1056. settings.WebhookUrl = req.WebhookUrl
  1057. if req.WebhookSecret != "" {
  1058. settings.WebhookSecret = req.WebhookSecret
  1059. }
  1060. }
  1061. // 如果提供了通知邮箱,添加到设置中
  1062. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1063. settings.NotificationEmail = req.NotificationEmail
  1064. }
  1065. // 如果是Bark类型,添加Bark URL到设置中
  1066. if req.QuotaWarningType == dto.NotifyTypeBark {
  1067. settings.BarkUrl = req.BarkUrl
  1068. }
  1069. // 如果是Gotify类型,添加Gotify配置到设置中
  1070. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1071. settings.GotifyUrl = req.GotifyUrl
  1072. settings.GotifyToken = req.GotifyToken
  1073. // Gotify优先级范围0-10,超出范围则使用默认值5
  1074. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1075. settings.GotifyPriority = 5
  1076. } else {
  1077. settings.GotifyPriority = req.GotifyPriority
  1078. }
  1079. }
  1080. // 更新用户设置
  1081. user.SetSetting(settings)
  1082. if err := user.Update(false); err != nil {
  1083. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1084. return
  1085. }
  1086. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1087. }