user.go 33 KB

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