Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

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