user.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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 UpdateSelf(c *gin.Context) {
  541. var requestData map[string]interface{}
  542. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  543. if err != nil {
  544. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  545. return
  546. }
  547. // 检查是否是用户设置更新请求 (sidebar_modules 或 language)
  548. if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
  549. userId := c.GetInt("id")
  550. user, err := model.GetUserById(userId, false)
  551. if err != nil {
  552. common.ApiError(c, err)
  553. return
  554. }
  555. // 获取当前用户设置
  556. currentSetting := user.GetSetting()
  557. // 更新sidebar_modules字段
  558. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  559. currentSetting.SidebarModules = sidebarModulesStr
  560. }
  561. // 保存更新后的设置
  562. user.SetSetting(currentSetting)
  563. if err := user.Update(false); err != nil {
  564. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  565. return
  566. }
  567. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  568. return
  569. }
  570. // 检查是否是语言偏好更新请求
  571. if language, langExists := requestData["language"]; langExists {
  572. userId := c.GetInt("id")
  573. user, err := model.GetUserById(userId, false)
  574. if err != nil {
  575. common.ApiError(c, err)
  576. return
  577. }
  578. // 获取当前用户设置
  579. currentSetting := user.GetSetting()
  580. // 更新language字段
  581. if langStr, ok := language.(string); ok {
  582. currentSetting.Language = langStr
  583. }
  584. // 保存更新后的设置
  585. user.SetSetting(currentSetting)
  586. if err := user.Update(false); err != nil {
  587. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  588. return
  589. }
  590. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  591. return
  592. }
  593. // 原有的用户信息更新逻辑
  594. var user model.User
  595. requestDataBytes, err := json.Marshal(requestData)
  596. if err != nil {
  597. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  598. return
  599. }
  600. err = json.Unmarshal(requestDataBytes, &user)
  601. if err != nil {
  602. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  603. return
  604. }
  605. if user.Password == "" {
  606. user.Password = "$I_LOVE_U" // make Validator happy :)
  607. }
  608. if err := common.Validate.Struct(&user); err != nil {
  609. common.ApiErrorI18n(c, i18n.MsgInvalidInput)
  610. return
  611. }
  612. cleanUser := model.User{
  613. Id: c.GetInt("id"),
  614. Username: user.Username,
  615. Password: user.Password,
  616. DisplayName: user.DisplayName,
  617. }
  618. if user.Password == "$I_LOVE_U" {
  619. user.Password = "" // rollback to what it should be
  620. cleanUser.Password = ""
  621. }
  622. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  623. if err != nil {
  624. common.ApiError(c, err)
  625. return
  626. }
  627. if err := cleanUser.Update(updatePassword); err != nil {
  628. common.ApiError(c, err)
  629. return
  630. }
  631. c.JSON(http.StatusOK, gin.H{
  632. "success": true,
  633. "message": "",
  634. })
  635. return
  636. }
  637. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  638. var currentUser *model.User
  639. currentUser, err = model.GetUserById(userId, true)
  640. if err != nil {
  641. return
  642. }
  643. // 密码不为空,需要验证原密码
  644. // 支持第一次账号绑定时原密码为空的情况
  645. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) && currentUser.Password != "" {
  646. err = fmt.Errorf("原密码错误")
  647. return
  648. }
  649. if newPassword == "" {
  650. return
  651. }
  652. updatePassword = true
  653. return
  654. }
  655. func DeleteUser(c *gin.Context) {
  656. id, err := strconv.Atoi(c.Param("id"))
  657. if err != nil {
  658. common.ApiError(c, err)
  659. return
  660. }
  661. originUser, err := model.GetUserById(id, false)
  662. if err != nil {
  663. common.ApiError(c, err)
  664. return
  665. }
  666. myRole := c.GetInt("role")
  667. if myRole <= originUser.Role {
  668. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  669. return
  670. }
  671. err = model.HardDeleteUserById(id)
  672. if err != nil {
  673. c.JSON(http.StatusOK, gin.H{
  674. "success": true,
  675. "message": "",
  676. })
  677. return
  678. }
  679. }
  680. func DeleteSelf(c *gin.Context) {
  681. id := c.GetInt("id")
  682. user, _ := model.GetUserById(id, false)
  683. if user.Role == common.RoleRootUser {
  684. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  685. return
  686. }
  687. err := model.DeleteUserById(id)
  688. if err != nil {
  689. common.ApiError(c, err)
  690. return
  691. }
  692. c.JSON(http.StatusOK, gin.H{
  693. "success": true,
  694. "message": "",
  695. })
  696. return
  697. }
  698. func CreateUser(c *gin.Context) {
  699. var user model.User
  700. err := json.NewDecoder(c.Request.Body).Decode(&user)
  701. user.Username = strings.TrimSpace(user.Username)
  702. if err != nil || user.Username == "" || user.Password == "" {
  703. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  704. return
  705. }
  706. if err := common.Validate.Struct(&user); err != nil {
  707. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  708. return
  709. }
  710. if user.DisplayName == "" {
  711. user.DisplayName = user.Username
  712. }
  713. myRole := c.GetInt("role")
  714. if user.Role >= myRole {
  715. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  716. return
  717. }
  718. // Even for admin users, we cannot fully trust them!
  719. cleanUser := model.User{
  720. Username: user.Username,
  721. Password: user.Password,
  722. DisplayName: user.DisplayName,
  723. Role: user.Role, // 保持管理员设置的角色
  724. }
  725. if err := cleanUser.Insert(0); err != nil {
  726. common.ApiError(c, err)
  727. return
  728. }
  729. c.JSON(http.StatusOK, gin.H{
  730. "success": true,
  731. "message": "",
  732. })
  733. return
  734. }
  735. type ManageRequest struct {
  736. Id int `json:"id"`
  737. Action string `json:"action"`
  738. }
  739. // ManageUser Only admin user can do this
  740. func ManageUser(c *gin.Context) {
  741. var req ManageRequest
  742. err := json.NewDecoder(c.Request.Body).Decode(&req)
  743. if err != nil {
  744. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  745. return
  746. }
  747. user := model.User{
  748. Id: req.Id,
  749. }
  750. // Fill attributes
  751. model.DB.Unscoped().Where(&user).First(&user)
  752. if user.Id == 0 {
  753. common.ApiErrorI18n(c, i18n.MsgUserNotExists)
  754. return
  755. }
  756. myRole := c.GetInt("role")
  757. if myRole <= user.Role && myRole != common.RoleRootUser {
  758. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  759. return
  760. }
  761. switch req.Action {
  762. case "disable":
  763. user.Status = common.UserStatusDisabled
  764. if user.Role == common.RoleRootUser {
  765. common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
  766. return
  767. }
  768. case "enable":
  769. user.Status = common.UserStatusEnabled
  770. case "delete":
  771. if user.Role == common.RoleRootUser {
  772. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  773. return
  774. }
  775. if err := user.Delete(); err != nil {
  776. c.JSON(http.StatusOK, gin.H{
  777. "success": false,
  778. "message": err.Error(),
  779. })
  780. return
  781. }
  782. case "promote":
  783. if myRole != common.RoleRootUser {
  784. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  785. return
  786. }
  787. if user.Role >= common.RoleAdminUser {
  788. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  789. return
  790. }
  791. user.Role = common.RoleAdminUser
  792. case "demote":
  793. if user.Role == common.RoleRootUser {
  794. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  795. return
  796. }
  797. if user.Role == common.RoleCommonUser {
  798. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  799. return
  800. }
  801. user.Role = common.RoleCommonUser
  802. }
  803. if err := user.Update(false); err != nil {
  804. common.ApiError(c, err)
  805. return
  806. }
  807. clearUser := model.User{
  808. Role: user.Role,
  809. Status: user.Status,
  810. }
  811. c.JSON(http.StatusOK, gin.H{
  812. "success": true,
  813. "message": "",
  814. "data": clearUser,
  815. })
  816. return
  817. }
  818. func EmailBind(c *gin.Context) {
  819. email := c.Query("email")
  820. code := c.Query("code")
  821. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  822. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  823. return
  824. }
  825. session := sessions.Default(c)
  826. id := session.Get("id")
  827. user := model.User{
  828. Id: id.(int),
  829. }
  830. err := user.FillUserById()
  831. if err != nil {
  832. common.ApiError(c, err)
  833. return
  834. }
  835. user.Email = email
  836. // no need to check if this email already taken, because we have used verification code to check it
  837. err = user.Update(false)
  838. if err != nil {
  839. common.ApiError(c, err)
  840. return
  841. }
  842. c.JSON(http.StatusOK, gin.H{
  843. "success": true,
  844. "message": "",
  845. })
  846. return
  847. }
  848. type topUpRequest struct {
  849. Key string `json:"key"`
  850. }
  851. var topUpLocks sync.Map
  852. var topUpCreateLock sync.Mutex
  853. type topUpTryLock struct {
  854. ch chan struct{}
  855. }
  856. func newTopUpTryLock() *topUpTryLock {
  857. return &topUpTryLock{ch: make(chan struct{}, 1)}
  858. }
  859. func (l *topUpTryLock) TryLock() bool {
  860. select {
  861. case l.ch <- struct{}{}:
  862. return true
  863. default:
  864. return false
  865. }
  866. }
  867. func (l *topUpTryLock) Unlock() {
  868. select {
  869. case <-l.ch:
  870. default:
  871. }
  872. }
  873. func getTopUpLock(userID int) *topUpTryLock {
  874. if v, ok := topUpLocks.Load(userID); ok {
  875. return v.(*topUpTryLock)
  876. }
  877. topUpCreateLock.Lock()
  878. defer topUpCreateLock.Unlock()
  879. if v, ok := topUpLocks.Load(userID); ok {
  880. return v.(*topUpTryLock)
  881. }
  882. l := newTopUpTryLock()
  883. topUpLocks.Store(userID, l)
  884. return l
  885. }
  886. func TopUp(c *gin.Context) {
  887. id := c.GetInt("id")
  888. lock := getTopUpLock(id)
  889. if !lock.TryLock() {
  890. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  891. return
  892. }
  893. defer lock.Unlock()
  894. req := topUpRequest{}
  895. err := c.ShouldBindJSON(&req)
  896. if err != nil {
  897. common.ApiError(c, err)
  898. return
  899. }
  900. quota, err := model.Redeem(req.Key, id)
  901. if err != nil {
  902. if errors.Is(err, model.ErrRedeemFailed) {
  903. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  904. return
  905. }
  906. common.ApiError(c, err)
  907. return
  908. }
  909. c.JSON(http.StatusOK, gin.H{
  910. "success": true,
  911. "message": "",
  912. "data": quota,
  913. })
  914. }
  915. type UpdateUserSettingRequest struct {
  916. QuotaWarningType string `json:"notify_type"`
  917. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  918. WebhookUrl string `json:"webhook_url,omitempty"`
  919. WebhookSecret string `json:"webhook_secret,omitempty"`
  920. NotificationEmail string `json:"notification_email,omitempty"`
  921. BarkUrl string `json:"bark_url,omitempty"`
  922. GotifyUrl string `json:"gotify_url,omitempty"`
  923. GotifyToken string `json:"gotify_token,omitempty"`
  924. GotifyPriority int `json:"gotify_priority,omitempty"`
  925. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  926. RecordIpLog bool `json:"record_ip_log"`
  927. }
  928. func UpdateUserSetting(c *gin.Context) {
  929. var req UpdateUserSettingRequest
  930. if err := c.ShouldBindJSON(&req); err != nil {
  931. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  932. return
  933. }
  934. // 验证预警类型
  935. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  936. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  937. return
  938. }
  939. // 验证预警阈值
  940. if req.QuotaWarningThreshold <= 0 {
  941. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  942. return
  943. }
  944. // 如果是webhook类型,验证webhook地址
  945. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  946. if req.WebhookUrl == "" {
  947. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  948. return
  949. }
  950. // 验证URL格式
  951. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  952. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  953. return
  954. }
  955. }
  956. // 如果是邮件类型,验证邮箱地址
  957. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  958. // 验证邮箱格式
  959. if !strings.Contains(req.NotificationEmail, "@") {
  960. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  961. return
  962. }
  963. }
  964. // 如果是Bark类型,验证Bark URL
  965. if req.QuotaWarningType == dto.NotifyTypeBark {
  966. if req.BarkUrl == "" {
  967. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  968. return
  969. }
  970. // 验证URL格式
  971. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  972. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  973. return
  974. }
  975. // 检查是否是HTTP或HTTPS
  976. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  977. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  978. return
  979. }
  980. }
  981. // 如果是Gotify类型,验证Gotify URL和Token
  982. if req.QuotaWarningType == dto.NotifyTypeGotify {
  983. if req.GotifyUrl == "" {
  984. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  985. return
  986. }
  987. if req.GotifyToken == "" {
  988. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  989. return
  990. }
  991. // 验证URL格式
  992. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  993. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  994. return
  995. }
  996. // 检查是否是HTTP或HTTPS
  997. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  998. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  999. return
  1000. }
  1001. }
  1002. userId := c.GetInt("id")
  1003. user, err := model.GetUserById(userId, true)
  1004. if err != nil {
  1005. common.ApiError(c, err)
  1006. return
  1007. }
  1008. // 构建设置
  1009. settings := dto.UserSetting{
  1010. NotifyType: req.QuotaWarningType,
  1011. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1012. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1013. RecordIpLog: req.RecordIpLog,
  1014. }
  1015. // 如果是webhook类型,添加webhook相关设置
  1016. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1017. settings.WebhookUrl = req.WebhookUrl
  1018. if req.WebhookSecret != "" {
  1019. settings.WebhookSecret = req.WebhookSecret
  1020. }
  1021. }
  1022. // 如果提供了通知邮箱,添加到设置中
  1023. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1024. settings.NotificationEmail = req.NotificationEmail
  1025. }
  1026. // 如果是Bark类型,添加Bark URL到设置中
  1027. if req.QuotaWarningType == dto.NotifyTypeBark {
  1028. settings.BarkUrl = req.BarkUrl
  1029. }
  1030. // 如果是Gotify类型,添加Gotify配置到设置中
  1031. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1032. settings.GotifyUrl = req.GotifyUrl
  1033. settings.GotifyToken = req.GotifyToken
  1034. // Gotify优先级范围0-10,超出范围则使用默认值5
  1035. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1036. settings.GotifyPriority = 5
  1037. } else {
  1038. settings.GotifyPriority = req.GotifyPriority
  1039. }
  1040. }
  1041. // 更新用户设置
  1042. user.SetSetting(settings)
  1043. if err := user.Update(false); err != nil {
  1044. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1045. return
  1046. }
  1047. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1048. }