Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

1205 lignes
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. if originUser.IsSyncedUser() {
  522. // 对同步用户而言,界面展示和用户感知的“余额”是 synced_quota,
  523. // 不能用本地 quota 列做比较,否则在 quota / synced_quota 漂移后会误判。
  524. if originUser.SyncedQuota != updatedUser.Quota {
  525. common.ApiErrorI18n(c, i18n.MsgSyncedUserQuotaCannotModify)
  526. return
  527. }
  528. // 提交其他字段编辑时,保留本地 quota 原值,避免把展示用 synced_quota 回写到 quota 列。
  529. updatedUser.Quota = originUser.Quota
  530. }
  531. myRole := c.GetInt("role")
  532. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  533. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  534. return
  535. }
  536. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  537. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  538. return
  539. }
  540. if updatedUser.Password == "$I_LOVE_U" {
  541. updatedUser.Password = "" // rollback to what it should be
  542. }
  543. updatePassword := updatedUser.Password != ""
  544. if err := updatedUser.Edit(updatePassword); err != nil {
  545. common.ApiError(c, err)
  546. return
  547. }
  548. middleware.SetCaptureEnabled(int64(updatedUser.Id), updatedUser.CaptureRelay)
  549. if originUser.Quota != updatedUser.Quota {
  550. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", logger.LogQuota(originUser.Quota), logger.LogQuota(updatedUser.Quota)))
  551. }
  552. c.JSON(http.StatusOK, gin.H{
  553. "success": true,
  554. "message": "",
  555. })
  556. return
  557. }
  558. func AdminClearUserBinding(c *gin.Context) {
  559. id, err := strconv.Atoi(c.Param("id"))
  560. if err != nil {
  561. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  562. return
  563. }
  564. bindingType := strings.ToLower(strings.TrimSpace(c.Param("binding_type")))
  565. if bindingType == "" {
  566. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  567. return
  568. }
  569. user, err := model.GetUserById(id, false)
  570. if err != nil {
  571. common.ApiError(c, err)
  572. return
  573. }
  574. myRole := c.GetInt("role")
  575. if myRole <= user.Role && myRole != common.RoleRootUser {
  576. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  577. return
  578. }
  579. if err := user.ClearBinding(bindingType); err != nil {
  580. common.ApiError(c, err)
  581. return
  582. }
  583. model.RecordLog(user.Id, model.LogTypeManage, fmt.Sprintf("admin cleared %s binding for user %s", bindingType, user.Username))
  584. c.JSON(http.StatusOK, gin.H{
  585. "success": true,
  586. "message": "success",
  587. })
  588. }
  589. func UpdateSelf(c *gin.Context) {
  590. var requestData map[string]interface{}
  591. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  592. if err != nil {
  593. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  594. return
  595. }
  596. // 检查是否是用户设置更新请求 (sidebar_modules 或 language)
  597. if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
  598. userId := c.GetInt("id")
  599. user, err := model.GetUserById(userId, false)
  600. if err != nil {
  601. common.ApiError(c, err)
  602. return
  603. }
  604. // 获取当前用户设置
  605. currentSetting := user.GetSetting()
  606. // 更新sidebar_modules字段
  607. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  608. currentSetting.SidebarModules = sidebarModulesStr
  609. }
  610. // 保存更新后的设置
  611. user.SetSetting(currentSetting)
  612. if err := user.Update(false); err != nil {
  613. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  614. return
  615. }
  616. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  617. return
  618. }
  619. // 检查是否是语言偏好更新请求
  620. if language, langExists := requestData["language"]; langExists {
  621. userId := c.GetInt("id")
  622. user, err := model.GetUserById(userId, false)
  623. if err != nil {
  624. common.ApiError(c, err)
  625. return
  626. }
  627. // 获取当前用户设置
  628. currentSetting := user.GetSetting()
  629. // 更新language字段
  630. if langStr, ok := language.(string); ok {
  631. currentSetting.Language = langStr
  632. }
  633. // 保存更新后的设置
  634. user.SetSetting(currentSetting)
  635. if err := user.Update(false); err != nil {
  636. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  637. return
  638. }
  639. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  640. return
  641. }
  642. // 原有的用户信息更新逻辑
  643. var user model.User
  644. requestDataBytes, err := json.Marshal(requestData)
  645. if err != nil {
  646. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  647. return
  648. }
  649. err = json.Unmarshal(requestDataBytes, &user)
  650. if err != nil {
  651. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  652. return
  653. }
  654. if user.Password == "" {
  655. user.Password = "$I_LOVE_U" // make Validator happy :)
  656. }
  657. if err := common.Validate.Struct(&user); err != nil {
  658. common.ApiErrorI18n(c, i18n.MsgInvalidInput)
  659. return
  660. }
  661. cleanUser := model.User{
  662. Id: c.GetInt("id"),
  663. Username: user.Username,
  664. Password: user.Password,
  665. DisplayName: user.DisplayName,
  666. }
  667. if user.Password == "$I_LOVE_U" {
  668. user.Password = "" // rollback to what it should be
  669. cleanUser.Password = ""
  670. }
  671. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  672. if err != nil {
  673. common.ApiError(c, err)
  674. return
  675. }
  676. if err := cleanUser.Update(updatePassword); err != nil {
  677. common.ApiError(c, err)
  678. return
  679. }
  680. c.JSON(http.StatusOK, gin.H{
  681. "success": true,
  682. "message": "",
  683. })
  684. return
  685. }
  686. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  687. var currentUser *model.User
  688. currentUser, err = model.GetUserById(userId, true)
  689. if err != nil {
  690. return
  691. }
  692. // 密码不为空,需要验证原密码
  693. // 支持第一次账号绑定时原密码为空的情况
  694. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) && currentUser.Password != "" {
  695. err = fmt.Errorf("原密码错误")
  696. return
  697. }
  698. if newPassword == "" {
  699. return
  700. }
  701. updatePassword = true
  702. return
  703. }
  704. func DeleteUser(c *gin.Context) {
  705. id, err := strconv.Atoi(c.Param("id"))
  706. if err != nil {
  707. common.ApiError(c, err)
  708. return
  709. }
  710. originUser, err := model.GetUserById(id, false)
  711. if err != nil {
  712. common.ApiError(c, err)
  713. return
  714. }
  715. myRole := c.GetInt("role")
  716. if myRole <= originUser.Role {
  717. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  718. return
  719. }
  720. err = model.HardDeleteUserById(id)
  721. if err != nil {
  722. c.JSON(http.StatusOK, gin.H{
  723. "success": true,
  724. "message": "",
  725. })
  726. return
  727. }
  728. }
  729. func DeleteSelf(c *gin.Context) {
  730. id := c.GetInt("id")
  731. user, _ := model.GetUserById(id, false)
  732. if user.Role == common.RoleRootUser {
  733. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  734. return
  735. }
  736. err := model.DeleteUserById(id)
  737. if err != nil {
  738. common.ApiError(c, err)
  739. return
  740. }
  741. c.JSON(http.StatusOK, gin.H{
  742. "success": true,
  743. "message": "",
  744. })
  745. return
  746. }
  747. func CreateUser(c *gin.Context) {
  748. var user model.User
  749. err := json.NewDecoder(c.Request.Body).Decode(&user)
  750. user.Username = strings.TrimSpace(user.Username)
  751. if err != nil || user.Username == "" || user.Password == "" {
  752. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  753. return
  754. }
  755. if err := common.Validate.Struct(&user); err != nil {
  756. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  757. return
  758. }
  759. if user.DisplayName == "" {
  760. user.DisplayName = user.Username
  761. }
  762. myRole := c.GetInt("role")
  763. if user.Role >= myRole {
  764. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  765. return
  766. }
  767. // Even for admin users, we cannot fully trust them!
  768. cleanUser := model.User{
  769. Username: user.Username,
  770. Password: user.Password,
  771. DisplayName: user.DisplayName,
  772. Role: user.Role, // 保持管理员设置的角色
  773. }
  774. if err := cleanUser.Insert(0); err != nil {
  775. common.ApiError(c, err)
  776. return
  777. }
  778. c.JSON(http.StatusOK, gin.H{
  779. "success": true,
  780. "message": "",
  781. })
  782. return
  783. }
  784. type ManageRequest struct {
  785. Id int `json:"id"`
  786. Action string `json:"action"`
  787. }
  788. // ManageUser Only admin user can do this
  789. func ManageUser(c *gin.Context) {
  790. var req ManageRequest
  791. err := json.NewDecoder(c.Request.Body).Decode(&req)
  792. if err != nil {
  793. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  794. return
  795. }
  796. user := model.User{
  797. Id: req.Id,
  798. }
  799. // Fill attributes
  800. model.DB.Unscoped().Where(&user).First(&user)
  801. if user.Id == 0 {
  802. common.ApiErrorI18n(c, i18n.MsgUserNotExists)
  803. return
  804. }
  805. myRole := c.GetInt("role")
  806. if myRole <= user.Role && myRole != common.RoleRootUser {
  807. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  808. return
  809. }
  810. switch req.Action {
  811. case "disable":
  812. user.Status = common.UserStatusDisabled
  813. if user.Role == common.RoleRootUser {
  814. common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
  815. return
  816. }
  817. case "enable":
  818. user.Status = common.UserStatusEnabled
  819. case "delete":
  820. if user.Role == common.RoleRootUser {
  821. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  822. return
  823. }
  824. if err := user.Delete(); err != nil {
  825. c.JSON(http.StatusOK, gin.H{
  826. "success": false,
  827. "message": err.Error(),
  828. })
  829. return
  830. }
  831. case "promote":
  832. if myRole != common.RoleRootUser {
  833. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  834. return
  835. }
  836. if user.Role >= common.RoleAdminUser {
  837. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  838. return
  839. }
  840. user.Role = common.RoleAdminUser
  841. case "demote":
  842. if user.Role == common.RoleRootUser {
  843. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  844. return
  845. }
  846. if user.Role == common.RoleCommonUser {
  847. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  848. return
  849. }
  850. user.Role = common.RoleCommonUser
  851. }
  852. if err := user.Update(false); err != nil {
  853. common.ApiError(c, err)
  854. return
  855. }
  856. clearUser := model.User{
  857. Role: user.Role,
  858. Status: user.Status,
  859. }
  860. c.JSON(http.StatusOK, gin.H{
  861. "success": true,
  862. "message": "",
  863. "data": clearUser,
  864. })
  865. return
  866. }
  867. func EmailBind(c *gin.Context) {
  868. email := c.Query("email")
  869. code := c.Query("code")
  870. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  871. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  872. return
  873. }
  874. session := sessions.Default(c)
  875. id := session.Get("id")
  876. user := model.User{
  877. Id: id.(int),
  878. }
  879. err := user.FillUserById()
  880. if err != nil {
  881. common.ApiError(c, err)
  882. return
  883. }
  884. user.Email = email
  885. // no need to check if this email already taken, because we have used verification code to check it
  886. err = user.Update(false)
  887. if err != nil {
  888. common.ApiError(c, err)
  889. return
  890. }
  891. c.JSON(http.StatusOK, gin.H{
  892. "success": true,
  893. "message": "",
  894. })
  895. return
  896. }
  897. type topUpRequest struct {
  898. Key string `json:"key"`
  899. }
  900. var topUpLocks sync.Map
  901. var topUpCreateLock sync.Mutex
  902. type topUpTryLock struct {
  903. ch chan struct{}
  904. }
  905. func newTopUpTryLock() *topUpTryLock {
  906. return &topUpTryLock{ch: make(chan struct{}, 1)}
  907. }
  908. func (l *topUpTryLock) TryLock() bool {
  909. select {
  910. case l.ch <- struct{}{}:
  911. return true
  912. default:
  913. return false
  914. }
  915. }
  916. func (l *topUpTryLock) Unlock() {
  917. select {
  918. case <-l.ch:
  919. default:
  920. }
  921. }
  922. func getTopUpLock(userID int) *topUpTryLock {
  923. if v, ok := topUpLocks.Load(userID); ok {
  924. return v.(*topUpTryLock)
  925. }
  926. topUpCreateLock.Lock()
  927. defer topUpCreateLock.Unlock()
  928. if v, ok := topUpLocks.Load(userID); ok {
  929. return v.(*topUpTryLock)
  930. }
  931. l := newTopUpTryLock()
  932. topUpLocks.Store(userID, l)
  933. return l
  934. }
  935. func TopUp(c *gin.Context) {
  936. id := c.GetInt("id")
  937. lock := getTopUpLock(id)
  938. if !lock.TryLock() {
  939. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  940. return
  941. }
  942. defer lock.Unlock()
  943. req := topUpRequest{}
  944. err := c.ShouldBindJSON(&req)
  945. if err != nil {
  946. common.ApiError(c, err)
  947. return
  948. }
  949. quota, err := model.Redeem(req.Key, id)
  950. if err != nil {
  951. if errors.Is(err, model.ErrSyncedUserRedeemDenied) {
  952. common.ApiErrorI18n(c, i18n.MsgRedemptionSyncedUserDenied)
  953. return
  954. }
  955. if errors.Is(err, model.ErrRedeemFailed) {
  956. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  957. return
  958. }
  959. common.ApiError(c, err)
  960. return
  961. }
  962. c.JSON(http.StatusOK, gin.H{
  963. "success": true,
  964. "message": "",
  965. "data": quota,
  966. })
  967. }
  968. type UpdateUserSettingRequest struct {
  969. QuotaWarningType string `json:"notify_type"`
  970. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  971. WebhookUrl string `json:"webhook_url,omitempty"`
  972. WebhookSecret string `json:"webhook_secret,omitempty"`
  973. NotificationEmail string `json:"notification_email,omitempty"`
  974. BarkUrl string `json:"bark_url,omitempty"`
  975. GotifyUrl string `json:"gotify_url,omitempty"`
  976. GotifyToken string `json:"gotify_token,omitempty"`
  977. GotifyPriority int `json:"gotify_priority,omitempty"`
  978. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  979. RecordIpLog bool `json:"record_ip_log"`
  980. }
  981. func UpdateUserSetting(c *gin.Context) {
  982. var req UpdateUserSettingRequest
  983. if err := c.ShouldBindJSON(&req); err != nil {
  984. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  985. return
  986. }
  987. // 验证预警类型
  988. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  989. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  990. return
  991. }
  992. // 验证预警阈值
  993. if req.QuotaWarningThreshold <= 0 {
  994. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  995. return
  996. }
  997. // 如果是webhook类型,验证webhook地址
  998. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  999. if req.WebhookUrl == "" {
  1000. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  1001. return
  1002. }
  1003. // 验证URL格式
  1004. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1005. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  1006. return
  1007. }
  1008. }
  1009. // 如果是邮件类型,验证邮箱地址
  1010. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1011. // 验证邮箱格式
  1012. if !strings.Contains(req.NotificationEmail, "@") {
  1013. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  1014. return
  1015. }
  1016. }
  1017. // 如果是Bark类型,验证Bark URL
  1018. if req.QuotaWarningType == dto.NotifyTypeBark {
  1019. if req.BarkUrl == "" {
  1020. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  1021. return
  1022. }
  1023. // 验证URL格式
  1024. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1025. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  1026. return
  1027. }
  1028. // 检查是否是HTTP或HTTPS
  1029. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1030. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1031. return
  1032. }
  1033. }
  1034. // 如果是Gotify类型,验证Gotify URL和Token
  1035. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1036. if req.GotifyUrl == "" {
  1037. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  1038. return
  1039. }
  1040. if req.GotifyToken == "" {
  1041. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  1042. return
  1043. }
  1044. // 验证URL格式
  1045. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  1046. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  1047. return
  1048. }
  1049. // 检查是否是HTTP或HTTPS
  1050. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  1051. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1052. return
  1053. }
  1054. }
  1055. userId := c.GetInt("id")
  1056. user, err := model.GetUserById(userId, true)
  1057. if err != nil {
  1058. common.ApiError(c, err)
  1059. return
  1060. }
  1061. // 构建设置
  1062. settings := dto.UserSetting{
  1063. NotifyType: req.QuotaWarningType,
  1064. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1065. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1066. RecordIpLog: req.RecordIpLog,
  1067. }
  1068. // 如果是webhook类型,添加webhook相关设置
  1069. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1070. settings.WebhookUrl = req.WebhookUrl
  1071. if req.WebhookSecret != "" {
  1072. settings.WebhookSecret = req.WebhookSecret
  1073. }
  1074. }
  1075. // 如果提供了通知邮箱,添加到设置中
  1076. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1077. settings.NotificationEmail = req.NotificationEmail
  1078. }
  1079. // 如果是Bark类型,添加Bark URL到设置中
  1080. if req.QuotaWarningType == dto.NotifyTypeBark {
  1081. settings.BarkUrl = req.BarkUrl
  1082. }
  1083. // 如果是Gotify类型,添加Gotify配置到设置中
  1084. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1085. settings.GotifyUrl = req.GotifyUrl
  1086. settings.GotifyToken = req.GotifyToken
  1087. // Gotify优先级范围0-10,超出范围则使用默认值5
  1088. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1089. settings.GotifyPriority = 5
  1090. } else {
  1091. settings.GotifyPriority = req.GotifyPriority
  1092. }
  1093. }
  1094. // 更新用户设置
  1095. user.SetSetting(settings)
  1096. if err := user.Update(false); err != nil {
  1097. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1098. return
  1099. }
  1100. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1101. }