user.go 30 KB

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