Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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