user.go 29 KB

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