user.go 30 KB

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