user.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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. case "promote":
  818. if myRole != common.RoleRootUser {
  819. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  820. return
  821. }
  822. if user.Role >= common.RoleAdminUser {
  823. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  824. return
  825. }
  826. user.Role = common.RoleAdminUser
  827. case "demote":
  828. if user.Role == common.RoleRootUser {
  829. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  830. return
  831. }
  832. if user.Role == common.RoleCommonUser {
  833. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  834. return
  835. }
  836. user.Role = common.RoleCommonUser
  837. case "add_quota":
  838. switch req.Mode {
  839. case "add":
  840. if req.Value <= 0 {
  841. common.ApiErrorI18n(c, i18n.MsgUserQuotaChangeZero)
  842. return
  843. }
  844. if err := model.IncreaseUserQuota(user.Id, req.Value, true); err != nil {
  845. common.ApiError(c, err)
  846. return
  847. }
  848. model.RecordLog(user.Id, model.LogTypeManage,
  849. fmt.Sprintf("管理员增加用户额度 %s", logger.LogQuota(req.Value)))
  850. case "subtract":
  851. if req.Value <= 0 {
  852. common.ApiErrorI18n(c, i18n.MsgUserQuotaChangeZero)
  853. return
  854. }
  855. if err := model.DecreaseUserQuota(user.Id, req.Value, true); err != nil {
  856. common.ApiError(c, err)
  857. return
  858. }
  859. model.RecordLog(user.Id, model.LogTypeManage,
  860. fmt.Sprintf("管理员减少用户额度 %s", logger.LogQuota(req.Value)))
  861. case "override":
  862. oldQuota := user.Quota
  863. if err := model.DB.Model(&model.User{}).Where("id = ?", user.Id).Update("quota", req.Value).Error; err != nil {
  864. common.ApiError(c, err)
  865. return
  866. }
  867. model.RecordLog(user.Id, model.LogTypeManage,
  868. fmt.Sprintf("管理员覆盖用户额度从 %s 为 %s", logger.LogQuota(oldQuota), logger.LogQuota(req.Value)))
  869. default:
  870. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  871. return
  872. }
  873. c.JSON(http.StatusOK, gin.H{
  874. "success": true,
  875. "message": "",
  876. })
  877. return
  878. }
  879. if err := user.Update(false); err != nil {
  880. common.ApiError(c, err)
  881. return
  882. }
  883. clearUser := model.User{
  884. Role: user.Role,
  885. Status: user.Status,
  886. }
  887. c.JSON(http.StatusOK, gin.H{
  888. "success": true,
  889. "message": "",
  890. "data": clearUser,
  891. })
  892. return
  893. }
  894. type emailBindRequest struct {
  895. Email string `json:"email"`
  896. Code string `json:"code"`
  897. }
  898. func EmailBind(c *gin.Context) {
  899. var req emailBindRequest
  900. if err := common.DecodeJson(c.Request.Body, &req); err != nil {
  901. common.ApiError(c, errors.New("invalid request body"))
  902. return
  903. }
  904. email := req.Email
  905. code := req.Code
  906. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  907. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  908. return
  909. }
  910. session := sessions.Default(c)
  911. id := session.Get("id")
  912. user := model.User{
  913. Id: id.(int),
  914. }
  915. err := user.FillUserById()
  916. if err != nil {
  917. common.ApiError(c, err)
  918. return
  919. }
  920. user.Email = email
  921. // no need to check if this email already taken, because we have used verification code to check it
  922. err = user.Update(false)
  923. if err != nil {
  924. common.ApiError(c, err)
  925. return
  926. }
  927. c.JSON(http.StatusOK, gin.H{
  928. "success": true,
  929. "message": "",
  930. })
  931. return
  932. }
  933. type topUpRequest struct {
  934. Key string `json:"key"`
  935. }
  936. var topUpLocks sync.Map
  937. var topUpCreateLock sync.Mutex
  938. type topUpTryLock struct {
  939. ch chan struct{}
  940. }
  941. func newTopUpTryLock() *topUpTryLock {
  942. return &topUpTryLock{ch: make(chan struct{}, 1)}
  943. }
  944. func (l *topUpTryLock) TryLock() bool {
  945. select {
  946. case l.ch <- struct{}{}:
  947. return true
  948. default:
  949. return false
  950. }
  951. }
  952. func (l *topUpTryLock) Unlock() {
  953. select {
  954. case <-l.ch:
  955. default:
  956. }
  957. }
  958. func getTopUpLock(userID int) *topUpTryLock {
  959. if v, ok := topUpLocks.Load(userID); ok {
  960. return v.(*topUpTryLock)
  961. }
  962. topUpCreateLock.Lock()
  963. defer topUpCreateLock.Unlock()
  964. if v, ok := topUpLocks.Load(userID); ok {
  965. return v.(*topUpTryLock)
  966. }
  967. l := newTopUpTryLock()
  968. topUpLocks.Store(userID, l)
  969. return l
  970. }
  971. func TopUp(c *gin.Context) {
  972. id := c.GetInt("id")
  973. lock := getTopUpLock(id)
  974. if !lock.TryLock() {
  975. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  976. return
  977. }
  978. defer lock.Unlock()
  979. req := topUpRequest{}
  980. err := c.ShouldBindJSON(&req)
  981. if err != nil {
  982. common.ApiError(c, err)
  983. return
  984. }
  985. quota, err := model.Redeem(req.Key, id)
  986. if err != nil {
  987. if errors.Is(err, model.ErrRedeemFailed) {
  988. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  989. return
  990. }
  991. common.ApiError(c, err)
  992. return
  993. }
  994. c.JSON(http.StatusOK, gin.H{
  995. "success": true,
  996. "message": "",
  997. "data": quota,
  998. })
  999. }
  1000. type UpdateUserSettingRequest struct {
  1001. QuotaWarningType string `json:"notify_type"`
  1002. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  1003. WebhookUrl string `json:"webhook_url,omitempty"`
  1004. WebhookSecret string `json:"webhook_secret,omitempty"`
  1005. NotificationEmail string `json:"notification_email,omitempty"`
  1006. BarkUrl string `json:"bark_url,omitempty"`
  1007. GotifyUrl string `json:"gotify_url,omitempty"`
  1008. GotifyToken string `json:"gotify_token,omitempty"`
  1009. GotifyPriority int `json:"gotify_priority,omitempty"`
  1010. UpstreamModelUpdateNotifyEnabled *bool `json:"upstream_model_update_notify_enabled,omitempty"`
  1011. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  1012. RecordIpLog bool `json:"record_ip_log"`
  1013. }
  1014. func UpdateUserSetting(c *gin.Context) {
  1015. var req UpdateUserSettingRequest
  1016. if err := c.ShouldBindJSON(&req); err != nil {
  1017. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  1018. return
  1019. }
  1020. // 验证预警类型
  1021. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  1022. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  1023. return
  1024. }
  1025. // 验证预警阈值
  1026. if req.QuotaWarningThreshold <= 0 {
  1027. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  1028. return
  1029. }
  1030. // 如果是webhook类型,验证webhook地址
  1031. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1032. if req.WebhookUrl == "" {
  1033. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  1034. return
  1035. }
  1036. // 验证URL格式
  1037. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1038. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  1039. return
  1040. }
  1041. }
  1042. // 如果是邮件类型,验证邮箱地址
  1043. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1044. // 验证邮箱格式
  1045. if !strings.Contains(req.NotificationEmail, "@") {
  1046. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  1047. return
  1048. }
  1049. }
  1050. // 如果是Bark类型,验证Bark URL
  1051. if req.QuotaWarningType == dto.NotifyTypeBark {
  1052. if req.BarkUrl == "" {
  1053. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  1054. return
  1055. }
  1056. // 验证URL格式
  1057. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1058. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  1059. return
  1060. }
  1061. // 检查是否是HTTP或HTTPS
  1062. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1063. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1064. return
  1065. }
  1066. }
  1067. // 如果是Gotify类型,验证Gotify URL和Token
  1068. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1069. if req.GotifyUrl == "" {
  1070. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  1071. return
  1072. }
  1073. if req.GotifyToken == "" {
  1074. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  1075. return
  1076. }
  1077. // 验证URL格式
  1078. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  1079. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  1080. return
  1081. }
  1082. // 检查是否是HTTP或HTTPS
  1083. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  1084. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1085. return
  1086. }
  1087. }
  1088. userId := c.GetInt("id")
  1089. user, err := model.GetUserById(userId, true)
  1090. if err != nil {
  1091. common.ApiError(c, err)
  1092. return
  1093. }
  1094. existingSettings := user.GetSetting()
  1095. upstreamModelUpdateNotifyEnabled := existingSettings.UpstreamModelUpdateNotifyEnabled
  1096. if user.Role >= common.RoleAdminUser && req.UpstreamModelUpdateNotifyEnabled != nil {
  1097. upstreamModelUpdateNotifyEnabled = *req.UpstreamModelUpdateNotifyEnabled
  1098. }
  1099. // 构建设置
  1100. settings := dto.UserSetting{
  1101. NotifyType: req.QuotaWarningType,
  1102. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1103. UpstreamModelUpdateNotifyEnabled: upstreamModelUpdateNotifyEnabled,
  1104. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1105. RecordIpLog: req.RecordIpLog,
  1106. }
  1107. // 如果是webhook类型,添加webhook相关设置
  1108. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1109. settings.WebhookUrl = req.WebhookUrl
  1110. if req.WebhookSecret != "" {
  1111. settings.WebhookSecret = req.WebhookSecret
  1112. }
  1113. }
  1114. // 如果提供了通知邮箱,添加到设置中
  1115. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1116. settings.NotificationEmail = req.NotificationEmail
  1117. }
  1118. // 如果是Bark类型,添加Bark URL到设置中
  1119. if req.QuotaWarningType == dto.NotifyTypeBark {
  1120. settings.BarkUrl = req.BarkUrl
  1121. }
  1122. // 如果是Gotify类型,添加Gotify配置到设置中
  1123. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1124. settings.GotifyUrl = req.GotifyUrl
  1125. settings.GotifyToken = req.GotifyToken
  1126. // Gotify优先级范围0-10,超出范围则使用默认值5
  1127. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1128. settings.GotifyPriority = 5
  1129. } else {
  1130. settings.GotifyPriority = req.GotifyPriority
  1131. }
  1132. }
  1133. // 更新用户设置
  1134. user.SetSetting(settings)
  1135. if err := user.Update(false); err != nil {
  1136. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1137. return
  1138. }
  1139. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1140. }