user.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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. switch {
  50. case errors.Is(err, model.ErrDatabase):
  51. common.SysLog(fmt.Sprintf("Login database error for user %s: %v", username, err))
  52. common.ApiErrorI18n(c, i18n.MsgDatabaseError)
  53. case errors.Is(err, model.ErrUserEmptyCredentials):
  54. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  55. default:
  56. common.ApiErrorI18n(c, i18n.MsgUserUsernameOrPasswordError)
  57. }
  58. return
  59. }
  60. // 检查是否启用2FA
  61. if model.IsTwoFAEnabled(user.Id) {
  62. // 设置pending session,等待2FA验证
  63. session := sessions.Default(c)
  64. session.Set("pending_username", user.Username)
  65. session.Set("pending_user_id", user.Id)
  66. err := session.Save()
  67. if err != nil {
  68. common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
  69. return
  70. }
  71. c.JSON(http.StatusOK, gin.H{
  72. "message": i18n.T(c, i18n.MsgUserRequire2FA),
  73. "success": true,
  74. "data": map[string]interface{}{
  75. "require_2fa": true,
  76. },
  77. })
  78. return
  79. }
  80. setupLogin(&user, c)
  81. }
  82. // setup session & cookies and then return user info
  83. func setupLogin(user *model.User, c *gin.Context) {
  84. session := sessions.Default(c)
  85. session.Set("id", user.Id)
  86. session.Set("username", user.Username)
  87. session.Set("role", user.Role)
  88. session.Set("status", user.Status)
  89. session.Set("group", user.Group)
  90. err := session.Save()
  91. if err != nil {
  92. common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
  93. return
  94. }
  95. c.JSON(http.StatusOK, gin.H{
  96. "message": "",
  97. "success": true,
  98. "data": map[string]any{
  99. "id": user.Id,
  100. "username": user.Username,
  101. "display_name": user.DisplayName,
  102. "role": user.Role,
  103. "status": user.Status,
  104. "group": user.Group,
  105. },
  106. })
  107. }
  108. func Logout(c *gin.Context) {
  109. session := sessions.Default(c)
  110. session.Clear()
  111. err := session.Save()
  112. if err != nil {
  113. c.JSON(http.StatusOK, gin.H{
  114. "message": err.Error(),
  115. "success": false,
  116. })
  117. return
  118. }
  119. c.JSON(http.StatusOK, gin.H{
  120. "message": "",
  121. "success": true,
  122. })
  123. }
  124. func Register(c *gin.Context) {
  125. if !common.RegisterEnabled {
  126. common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled)
  127. return
  128. }
  129. if !common.PasswordRegisterEnabled {
  130. common.ApiErrorI18n(c, i18n.MsgUserPasswordRegisterDisabled)
  131. return
  132. }
  133. var user model.User
  134. err := json.NewDecoder(c.Request.Body).Decode(&user)
  135. if err != nil {
  136. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  137. return
  138. }
  139. if err := common.Validate.Struct(&user); err != nil {
  140. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  141. return
  142. }
  143. if common.EmailVerificationEnabled {
  144. if user.Email == "" || user.VerificationCode == "" {
  145. common.ApiErrorI18n(c, i18n.MsgUserEmailVerificationRequired)
  146. return
  147. }
  148. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  149. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  150. return
  151. }
  152. }
  153. exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
  154. if err != nil {
  155. common.ApiErrorI18n(c, i18n.MsgDatabaseError)
  156. common.SysLog(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
  157. return
  158. }
  159. if exist {
  160. common.ApiErrorI18n(c, i18n.MsgUserExists)
  161. return
  162. }
  163. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  164. inviterId, _ := model.GetUserIdByAffCode(affCode)
  165. cleanUser := model.User{
  166. Username: user.Username,
  167. Password: user.Password,
  168. DisplayName: user.Username,
  169. InviterId: inviterId,
  170. Role: common.RoleCommonUser, // 明确设置角色为普通用户
  171. }
  172. if common.EmailVerificationEnabled {
  173. cleanUser.Email = user.Email
  174. }
  175. if err := cleanUser.Insert(inviterId); err != nil {
  176. common.ApiError(c, err)
  177. return
  178. }
  179. // 获取插入后的用户ID
  180. var insertedUser model.User
  181. if err := model.DB.Where("username = ?", cleanUser.Username).First(&insertedUser).Error; err != nil {
  182. common.ApiErrorI18n(c, i18n.MsgUserRegisterFailed)
  183. return
  184. }
  185. // 生成默认令牌
  186. if constant.GenerateDefaultToken {
  187. key, err := common.GenerateKey()
  188. if err != nil {
  189. common.ApiErrorI18n(c, i18n.MsgUserDefaultTokenFailed)
  190. common.SysLog("failed to generate token key: " + err.Error())
  191. return
  192. }
  193. // 生成默认令牌
  194. token := model.Token{
  195. UserId: insertedUser.Id, // 使用插入后的用户ID
  196. Name: cleanUser.Username + "的初始令牌",
  197. Key: key,
  198. CreatedTime: common.GetTimestamp(),
  199. AccessedTime: common.GetTimestamp(),
  200. ExpiredTime: -1, // 永不过期
  201. RemainQuota: 500000, // 示例额度
  202. UnlimitedQuota: true,
  203. ModelLimitsEnabled: false,
  204. }
  205. if setting.DefaultUseAutoGroup {
  206. token.Group = "auto"
  207. }
  208. if err := token.Insert(); err != nil {
  209. common.ApiErrorI18n(c, i18n.MsgCreateDefaultTokenErr)
  210. return
  211. }
  212. }
  213. c.JSON(http.StatusOK, gin.H{
  214. "success": true,
  215. "message": "",
  216. })
  217. return
  218. }
  219. func GetAllUsers(c *gin.Context) {
  220. pageInfo := common.GetPageQuery(c)
  221. users, total, err := model.GetAllUsers(pageInfo)
  222. if err != nil {
  223. common.ApiError(c, err)
  224. return
  225. }
  226. pageInfo.SetTotal(int(total))
  227. pageInfo.SetItems(users)
  228. common.ApiSuccess(c, pageInfo)
  229. return
  230. }
  231. func SearchUsers(c *gin.Context) {
  232. keyword := c.Query("keyword")
  233. group := c.Query("group")
  234. pageInfo := common.GetPageQuery(c)
  235. users, total, err := model.SearchUsers(keyword, group, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  236. if err != nil {
  237. common.ApiError(c, err)
  238. return
  239. }
  240. pageInfo.SetTotal(int(total))
  241. pageInfo.SetItems(users)
  242. common.ApiSuccess(c, pageInfo)
  243. return
  244. }
  245. func GetUser(c *gin.Context) {
  246. id, err := strconv.Atoi(c.Param("id"))
  247. if err != nil {
  248. common.ApiError(c, err)
  249. return
  250. }
  251. user, err := model.GetUserById(id, false)
  252. if err != nil {
  253. common.ApiError(c, err)
  254. return
  255. }
  256. myRole := c.GetInt("role")
  257. if myRole <= user.Role && myRole != common.RoleRootUser {
  258. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  259. return
  260. }
  261. c.JSON(http.StatusOK, gin.H{
  262. "success": true,
  263. "message": "",
  264. "data": user,
  265. })
  266. return
  267. }
  268. func GenerateAccessToken(c *gin.Context) {
  269. id := c.GetInt("id")
  270. user, err := model.GetUserById(id, true)
  271. if err != nil {
  272. common.ApiError(c, err)
  273. return
  274. }
  275. // get rand int 28-32
  276. randI := common.GetRandomInt(4)
  277. key, err := common.GenerateRandomKey(29 + randI)
  278. if err != nil {
  279. common.ApiErrorI18n(c, i18n.MsgGenerateFailed)
  280. common.SysLog("failed to generate key: " + err.Error())
  281. return
  282. }
  283. user.SetAccessToken(key)
  284. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  285. common.ApiErrorI18n(c, i18n.MsgUuidDuplicate)
  286. return
  287. }
  288. if err := user.Update(false); err != nil {
  289. common.ApiError(c, err)
  290. return
  291. }
  292. c.JSON(http.StatusOK, gin.H{
  293. "success": true,
  294. "message": "",
  295. "data": user.AccessToken,
  296. })
  297. return
  298. }
  299. type TransferAffQuotaRequest struct {
  300. Quota int `json:"quota" binding:"required"`
  301. }
  302. func TransferAffQuota(c *gin.Context) {
  303. id := c.GetInt("id")
  304. user, err := model.GetUserById(id, true)
  305. if err != nil {
  306. common.ApiError(c, err)
  307. return
  308. }
  309. tran := TransferAffQuotaRequest{}
  310. if err := c.ShouldBindJSON(&tran); err != nil {
  311. common.ApiError(c, err)
  312. return
  313. }
  314. err = user.TransferAffQuotaToQuota(tran.Quota)
  315. if err != nil {
  316. common.ApiErrorI18n(c, i18n.MsgUserTransferFailed, map[string]any{"Error": err.Error()})
  317. return
  318. }
  319. common.ApiSuccessI18n(c, i18n.MsgUserTransferSuccess, nil)
  320. }
  321. func GetAffCode(c *gin.Context) {
  322. id := c.GetInt("id")
  323. user, err := model.GetUserById(id, true)
  324. if err != nil {
  325. common.ApiError(c, err)
  326. return
  327. }
  328. if user.AffCode == "" {
  329. user.AffCode = common.GetRandomString(4)
  330. if err := user.Update(false); err != nil {
  331. c.JSON(http.StatusOK, gin.H{
  332. "success": false,
  333. "message": err.Error(),
  334. })
  335. return
  336. }
  337. }
  338. c.JSON(http.StatusOK, gin.H{
  339. "success": true,
  340. "message": "",
  341. "data": user.AffCode,
  342. })
  343. return
  344. }
  345. func GetSelf(c *gin.Context) {
  346. id := c.GetInt("id")
  347. userRole := c.GetInt("role")
  348. user, err := model.GetUserById(id, false)
  349. if err != nil {
  350. common.ApiError(c, err)
  351. return
  352. }
  353. // Hide admin remarks: set to empty to trigger omitempty tag, ensuring the remark field is not included in JSON returned to regular users
  354. user.Remark = ""
  355. // 计算用户权限信息
  356. permissions := calculateUserPermissions(userRole)
  357. // 获取用户设置并提取sidebar_modules
  358. userSetting := user.GetSetting()
  359. // 构建响应数据,包含用户信息和权限
  360. responseData := map[string]interface{}{
  361. "id": user.Id,
  362. "username": user.Username,
  363. "display_name": user.DisplayName,
  364. "role": user.Role,
  365. "status": user.Status,
  366. "email": user.Email,
  367. "github_id": user.GitHubId,
  368. "discord_id": user.DiscordId,
  369. "oidc_id": user.OidcId,
  370. "wechat_id": user.WeChatId,
  371. "telegram_id": user.TelegramId,
  372. "group": user.Group,
  373. "quota": user.Quota,
  374. "used_quota": user.UsedQuota,
  375. "request_count": user.RequestCount,
  376. "aff_code": user.AffCode,
  377. "aff_count": user.AffCount,
  378. "aff_quota": user.AffQuota,
  379. "aff_history_quota": user.AffHistoryQuota,
  380. "inviter_id": user.InviterId,
  381. "linux_do_id": user.LinuxDOId,
  382. "setting": user.Setting,
  383. "stripe_customer": user.StripeCustomer,
  384. "sidebar_modules": userSetting.SidebarModules, // 正确提取sidebar_modules字段
  385. "permissions": permissions, // 新增权限字段
  386. }
  387. c.JSON(http.StatusOK, gin.H{
  388. "success": true,
  389. "message": "",
  390. "data": responseData,
  391. })
  392. return
  393. }
  394. // 计算用户权限的辅助函数
  395. func calculateUserPermissions(userRole int) map[string]interface{} {
  396. permissions := map[string]interface{}{}
  397. // 根据用户角色计算权限
  398. if userRole == common.RoleRootUser {
  399. // 超级管理员不需要边栏设置功能
  400. permissions["sidebar_settings"] = false
  401. permissions["sidebar_modules"] = map[string]interface{}{}
  402. } else if userRole == common.RoleAdminUser {
  403. // 管理员可以设置边栏,但不包含系统设置功能
  404. permissions["sidebar_settings"] = true
  405. permissions["sidebar_modules"] = map[string]interface{}{
  406. "admin": map[string]interface{}{
  407. "setting": false, // 管理员不能访问系统设置
  408. },
  409. }
  410. } else {
  411. // 普通用户只能设置个人功能,不包含管理员区域
  412. permissions["sidebar_settings"] = true
  413. permissions["sidebar_modules"] = map[string]interface{}{
  414. "admin": false, // 普通用户不能访问管理员区域
  415. }
  416. }
  417. return permissions
  418. }
  419. // 根据用户角色生成默认的边栏配置
  420. func generateDefaultSidebarConfig(userRole int) string {
  421. defaultConfig := map[string]interface{}{}
  422. // 聊天区域 - 所有用户都可以访问
  423. defaultConfig["chat"] = map[string]interface{}{
  424. "enabled": true,
  425. "playground": true,
  426. "chat": true,
  427. }
  428. // 控制台区域 - 所有用户都可以访问
  429. defaultConfig["console"] = map[string]interface{}{
  430. "enabled": true,
  431. "detail": true,
  432. "token": true,
  433. "log": true,
  434. "midjourney": true,
  435. "task": true,
  436. }
  437. // 个人中心区域 - 所有用户都可以访问
  438. defaultConfig["personal"] = map[string]interface{}{
  439. "enabled": true,
  440. "topup": true,
  441. "personal": true,
  442. }
  443. // 管理员区域 - 根据角色决定
  444. if userRole == common.RoleAdminUser {
  445. // 管理员可以访问管理员区域,但不能访问系统设置
  446. defaultConfig["admin"] = map[string]interface{}{
  447. "enabled": true,
  448. "channel": true,
  449. "models": true,
  450. "redemption": true,
  451. "user": true,
  452. "setting": false, // 管理员不能访问系统设置
  453. }
  454. } else if userRole == common.RoleRootUser {
  455. // 超级管理员可以访问所有功能
  456. defaultConfig["admin"] = map[string]interface{}{
  457. "enabled": true,
  458. "channel": true,
  459. "models": true,
  460. "redemption": true,
  461. "user": true,
  462. "setting": true,
  463. }
  464. }
  465. // 普通用户不包含admin区域
  466. // 转换为JSON字符串
  467. configBytes, err := json.Marshal(defaultConfig)
  468. if err != nil {
  469. common.SysLog("生成默认边栏配置失败: " + err.Error())
  470. return ""
  471. }
  472. return string(configBytes)
  473. }
  474. func GetUserModels(c *gin.Context) {
  475. id, err := strconv.Atoi(c.Param("id"))
  476. if err != nil {
  477. id = c.GetInt("id")
  478. }
  479. user, err := model.GetUserCache(id)
  480. if err != nil {
  481. common.ApiError(c, err)
  482. return
  483. }
  484. groups := service.GetUserUsableGroups(user.Group)
  485. var models []string
  486. for group := range groups {
  487. for _, g := range model.GetGroupEnabledModels(group) {
  488. if !common.StringsContains(models, g) {
  489. models = append(models, g)
  490. }
  491. }
  492. }
  493. c.JSON(http.StatusOK, gin.H{
  494. "success": true,
  495. "message": "",
  496. "data": models,
  497. })
  498. return
  499. }
  500. func UpdateUser(c *gin.Context) {
  501. var updatedUser model.User
  502. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  503. if err != nil || updatedUser.Id == 0 {
  504. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  505. return
  506. }
  507. if updatedUser.Password == "" {
  508. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  509. }
  510. if err := common.Validate.Struct(&updatedUser); err != nil {
  511. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  512. return
  513. }
  514. originUser, err := model.GetUserById(updatedUser.Id, false)
  515. if err != nil {
  516. common.ApiError(c, err)
  517. return
  518. }
  519. myRole := c.GetInt("role")
  520. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  521. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  522. return
  523. }
  524. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  525. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  526. return
  527. }
  528. if updatedUser.Password == "$I_LOVE_U" {
  529. updatedUser.Password = "" // rollback to what it should be
  530. }
  531. updatePassword := updatedUser.Password != ""
  532. if err := updatedUser.Edit(updatePassword); err != nil {
  533. common.ApiError(c, err)
  534. return
  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. Value int `json:"value"`
  772. Mode string `json:"mode"`
  773. }
  774. // ManageUser Only admin user can do this
  775. func ManageUser(c *gin.Context) {
  776. var req ManageRequest
  777. err := json.NewDecoder(c.Request.Body).Decode(&req)
  778. if err != nil {
  779. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  780. return
  781. }
  782. user := model.User{
  783. Id: req.Id,
  784. }
  785. // Fill attributes
  786. model.DB.Unscoped().Where(&user).First(&user)
  787. if user.Id == 0 {
  788. common.ApiErrorI18n(c, i18n.MsgUserNotExists)
  789. return
  790. }
  791. myRole := c.GetInt("role")
  792. if myRole <= user.Role && myRole != common.RoleRootUser {
  793. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  794. return
  795. }
  796. switch req.Action {
  797. case "disable":
  798. user.Status = common.UserStatusDisabled
  799. if user.Role == common.RoleRootUser {
  800. common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
  801. return
  802. }
  803. case "enable":
  804. user.Status = common.UserStatusEnabled
  805. case "delete":
  806. if user.Role == common.RoleRootUser {
  807. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  808. return
  809. }
  810. if err := user.Delete(); err != nil {
  811. c.JSON(http.StatusOK, gin.H{
  812. "success": false,
  813. "message": err.Error(),
  814. })
  815. return
  816. }
  817. // 删除用户后,强制清理 Redis 中所有该用户令牌的缓存,
  818. // 避免已缓存的令牌在 TTL 过期前仍能通过 TokenAuth 校验。
  819. if err := model.InvalidateUserTokensCache(user.Id); err != nil {
  820. common.SysLog(fmt.Sprintf("failed to invalidate tokens cache for user %d: %s", user.Id, err.Error()))
  821. }
  822. case "promote":
  823. if myRole != common.RoleRootUser {
  824. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  825. return
  826. }
  827. if user.Role >= common.RoleAdminUser {
  828. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  829. return
  830. }
  831. user.Role = common.RoleAdminUser
  832. case "demote":
  833. if user.Role == common.RoleRootUser {
  834. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  835. return
  836. }
  837. if user.Role == common.RoleCommonUser {
  838. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  839. return
  840. }
  841. user.Role = common.RoleCommonUser
  842. case "add_quota":
  843. adminName := c.GetString("username")
  844. adminId := c.GetInt("id")
  845. adminInfo := map[string]interface{}{
  846. "admin_id": adminId,
  847. "admin_username": adminName,
  848. }
  849. switch req.Mode {
  850. case "add":
  851. if req.Value <= 0 {
  852. common.ApiErrorI18n(c, i18n.MsgUserQuotaChangeZero)
  853. return
  854. }
  855. if err := model.IncreaseUserQuota(user.Id, req.Value, true); err != nil {
  856. common.ApiError(c, err)
  857. return
  858. }
  859. model.RecordLogWithAdminInfo(user.Id, model.LogTypeManage,
  860. fmt.Sprintf("管理员增加用户额度 %s", logger.LogQuota(req.Value)), adminInfo)
  861. case "subtract":
  862. if req.Value <= 0 {
  863. common.ApiErrorI18n(c, i18n.MsgUserQuotaChangeZero)
  864. return
  865. }
  866. if err := model.DecreaseUserQuota(user.Id, req.Value, true); err != nil {
  867. common.ApiError(c, err)
  868. return
  869. }
  870. model.RecordLogWithAdminInfo(user.Id, model.LogTypeManage,
  871. fmt.Sprintf("管理员减少用户额度 %s", logger.LogQuota(req.Value)), adminInfo)
  872. case "override":
  873. oldQuota := user.Quota
  874. if err := model.DB.Model(&model.User{}).Where("id = ?", user.Id).Update("quota", req.Value).Error; err != nil {
  875. common.ApiError(c, err)
  876. return
  877. }
  878. model.RecordLogWithAdminInfo(user.Id, model.LogTypeManage,
  879. fmt.Sprintf("管理员覆盖用户额度从 %s 为 %s", logger.LogQuota(oldQuota), logger.LogQuota(req.Value)), adminInfo)
  880. default:
  881. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  882. return
  883. }
  884. c.JSON(http.StatusOK, gin.H{
  885. "success": true,
  886. "message": "",
  887. })
  888. return
  889. }
  890. if err := user.Update(false); err != nil {
  891. common.ApiError(c, err)
  892. return
  893. }
  894. // 禁用 / 角色调整后,强制失效用户缓存与其全部令牌缓存,
  895. // 避免在 Redis TTL 过期前仍使用旧状态(尤其是禁用后仍可发起请求的问题)。
  896. // InvalidateUserCache 会让下一次 GetUserCache 从数据库重新加载,
  897. // InvalidateUserTokensCache 则确保令牌侧的缓存也同步刷新。
  898. if req.Action == "disable" || req.Action == "promote" || req.Action == "demote" {
  899. if err := model.InvalidateUserCache(user.Id); err != nil {
  900. common.SysLog(fmt.Sprintf("failed to invalidate user cache for user %d: %s", user.Id, err.Error()))
  901. }
  902. if err := model.InvalidateUserTokensCache(user.Id); err != nil {
  903. common.SysLog(fmt.Sprintf("failed to invalidate tokens cache for user %d: %s", user.Id, err.Error()))
  904. }
  905. }
  906. clearUser := model.User{
  907. Role: user.Role,
  908. Status: user.Status,
  909. }
  910. c.JSON(http.StatusOK, gin.H{
  911. "success": true,
  912. "message": "",
  913. "data": clearUser,
  914. })
  915. return
  916. }
  917. type emailBindRequest struct {
  918. Email string `json:"email"`
  919. Code string `json:"code"`
  920. }
  921. func EmailBind(c *gin.Context) {
  922. var req emailBindRequest
  923. if err := common.DecodeJson(c.Request.Body, &req); err != nil {
  924. common.ApiError(c, errors.New("invalid request body"))
  925. return
  926. }
  927. email := req.Email
  928. code := req.Code
  929. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  930. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  931. return
  932. }
  933. session := sessions.Default(c)
  934. id := session.Get("id")
  935. user := model.User{
  936. Id: id.(int),
  937. }
  938. err := user.FillUserById()
  939. if err != nil {
  940. common.ApiError(c, err)
  941. return
  942. }
  943. user.Email = email
  944. // no need to check if this email already taken, because we have used verification code to check it
  945. err = user.Update(false)
  946. if err != nil {
  947. common.ApiError(c, err)
  948. return
  949. }
  950. c.JSON(http.StatusOK, gin.H{
  951. "success": true,
  952. "message": "",
  953. })
  954. return
  955. }
  956. type topUpRequest struct {
  957. Key string `json:"key"`
  958. }
  959. var topUpLocks sync.Map
  960. var topUpCreateLock sync.Mutex
  961. type topUpTryLock struct {
  962. ch chan struct{}
  963. }
  964. func newTopUpTryLock() *topUpTryLock {
  965. return &topUpTryLock{ch: make(chan struct{}, 1)}
  966. }
  967. func (l *topUpTryLock) TryLock() bool {
  968. select {
  969. case l.ch <- struct{}{}:
  970. return true
  971. default:
  972. return false
  973. }
  974. }
  975. func (l *topUpTryLock) Unlock() {
  976. select {
  977. case <-l.ch:
  978. default:
  979. }
  980. }
  981. func getTopUpLock(userID int) *topUpTryLock {
  982. if v, ok := topUpLocks.Load(userID); ok {
  983. return v.(*topUpTryLock)
  984. }
  985. topUpCreateLock.Lock()
  986. defer topUpCreateLock.Unlock()
  987. if v, ok := topUpLocks.Load(userID); ok {
  988. return v.(*topUpTryLock)
  989. }
  990. l := newTopUpTryLock()
  991. topUpLocks.Store(userID, l)
  992. return l
  993. }
  994. func TopUp(c *gin.Context) {
  995. id := c.GetInt("id")
  996. lock := getTopUpLock(id)
  997. if !lock.TryLock() {
  998. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  999. return
  1000. }
  1001. defer lock.Unlock()
  1002. req := topUpRequest{}
  1003. err := c.ShouldBindJSON(&req)
  1004. if err != nil {
  1005. common.ApiError(c, err)
  1006. return
  1007. }
  1008. quota, err := model.Redeem(req.Key, id)
  1009. if err != nil {
  1010. if errors.Is(err, model.ErrRedeemFailed) {
  1011. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  1012. return
  1013. }
  1014. common.ApiError(c, err)
  1015. return
  1016. }
  1017. c.JSON(http.StatusOK, gin.H{
  1018. "success": true,
  1019. "message": "",
  1020. "data": quota,
  1021. })
  1022. }
  1023. type UpdateUserSettingRequest struct {
  1024. QuotaWarningType string `json:"notify_type"`
  1025. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  1026. WebhookUrl string `json:"webhook_url,omitempty"`
  1027. WebhookSecret string `json:"webhook_secret,omitempty"`
  1028. NotificationEmail string `json:"notification_email,omitempty"`
  1029. BarkUrl string `json:"bark_url,omitempty"`
  1030. GotifyUrl string `json:"gotify_url,omitempty"`
  1031. GotifyToken string `json:"gotify_token,omitempty"`
  1032. GotifyPriority int `json:"gotify_priority,omitempty"`
  1033. UpstreamModelUpdateNotifyEnabled *bool `json:"upstream_model_update_notify_enabled,omitempty"`
  1034. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  1035. RecordIpLog bool `json:"record_ip_log"`
  1036. }
  1037. func UpdateUserSetting(c *gin.Context) {
  1038. var req UpdateUserSettingRequest
  1039. if err := c.ShouldBindJSON(&req); err != nil {
  1040. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  1041. return
  1042. }
  1043. // 验证预警类型
  1044. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  1045. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  1046. return
  1047. }
  1048. // 验证预警阈值
  1049. if req.QuotaWarningThreshold <= 0 {
  1050. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  1051. return
  1052. }
  1053. // 如果是webhook类型,验证webhook地址
  1054. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1055. if req.WebhookUrl == "" {
  1056. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  1057. return
  1058. }
  1059. // 验证URL格式
  1060. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1061. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  1062. return
  1063. }
  1064. }
  1065. // 如果是邮件类型,验证邮箱地址
  1066. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1067. // 验证邮箱格式
  1068. if !strings.Contains(req.NotificationEmail, "@") {
  1069. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  1070. return
  1071. }
  1072. }
  1073. // 如果是Bark类型,验证Bark URL
  1074. if req.QuotaWarningType == dto.NotifyTypeBark {
  1075. if req.BarkUrl == "" {
  1076. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  1077. return
  1078. }
  1079. // 验证URL格式
  1080. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1081. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  1082. return
  1083. }
  1084. // 检查是否是HTTP或HTTPS
  1085. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1086. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1087. return
  1088. }
  1089. }
  1090. // 如果是Gotify类型,验证Gotify URL和Token
  1091. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1092. if req.GotifyUrl == "" {
  1093. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  1094. return
  1095. }
  1096. if req.GotifyToken == "" {
  1097. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  1098. return
  1099. }
  1100. // 验证URL格式
  1101. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  1102. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  1103. return
  1104. }
  1105. // 检查是否是HTTP或HTTPS
  1106. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  1107. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1108. return
  1109. }
  1110. }
  1111. userId := c.GetInt("id")
  1112. user, err := model.GetUserById(userId, true)
  1113. if err != nil {
  1114. common.ApiError(c, err)
  1115. return
  1116. }
  1117. existingSettings := user.GetSetting()
  1118. upstreamModelUpdateNotifyEnabled := existingSettings.UpstreamModelUpdateNotifyEnabled
  1119. if user.Role >= common.RoleAdminUser && req.UpstreamModelUpdateNotifyEnabled != nil {
  1120. upstreamModelUpdateNotifyEnabled = *req.UpstreamModelUpdateNotifyEnabled
  1121. }
  1122. // 构建设置
  1123. settings := dto.UserSetting{
  1124. NotifyType: req.QuotaWarningType,
  1125. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1126. UpstreamModelUpdateNotifyEnabled: upstreamModelUpdateNotifyEnabled,
  1127. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1128. RecordIpLog: req.RecordIpLog,
  1129. }
  1130. // 如果是webhook类型,添加webhook相关设置
  1131. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1132. settings.WebhookUrl = req.WebhookUrl
  1133. if req.WebhookSecret != "" {
  1134. settings.WebhookSecret = req.WebhookSecret
  1135. }
  1136. }
  1137. // 如果提供了通知邮箱,添加到设置中
  1138. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1139. settings.NotificationEmail = req.NotificationEmail
  1140. }
  1141. // 如果是Bark类型,添加Bark URL到设置中
  1142. if req.QuotaWarningType == dto.NotifyTypeBark {
  1143. settings.BarkUrl = req.BarkUrl
  1144. }
  1145. // 如果是Gotify类型,添加Gotify配置到设置中
  1146. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1147. settings.GotifyUrl = req.GotifyUrl
  1148. settings.GotifyToken = req.GotifyToken
  1149. // Gotify优先级范围0-10,超出范围则使用默认值5
  1150. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1151. settings.GotifyPriority = 5
  1152. } else {
  1153. settings.GotifyPriority = req.GotifyPriority
  1154. }
  1155. }
  1156. // 更新用户设置
  1157. user.SetSetting(settings)
  1158. if err := user.Update(false); err != nil {
  1159. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1160. return
  1161. }
  1162. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1163. }