user.go 30 KB

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