user.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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. "group": user.Group,
  424. "quota": user.Quota,
  425. "used_quota": user.UsedQuota,
  426. "request_count": user.RequestCount,
  427. "aff_code": user.AffCode,
  428. "aff_count": user.AffCount,
  429. "aff_quota": user.AffQuota,
  430. "aff_history_quota": user.AffHistoryQuota,
  431. "inviter_id": user.InviterId,
  432. "linux_do_id": user.LinuxDOId,
  433. "setting": user.Setting,
  434. "stripe_customer": user.StripeCustomer,
  435. "sidebar_modules": userSetting.SidebarModules, // 正确提取sidebar_modules字段
  436. "permissions": permissions, // 新增权限字段
  437. }
  438. c.JSON(http.StatusOK, gin.H{
  439. "success": true,
  440. "message": "",
  441. "data": responseData,
  442. })
  443. return
  444. }
  445. // 计算用户权限的辅助函数
  446. func calculateUserPermissions(userRole int) map[string]interface{} {
  447. permissions := map[string]interface{}{}
  448. // 根据用户角色计算权限
  449. if userRole == common.RoleRootUser {
  450. // 超级管理员不需要边栏设置功能
  451. permissions["sidebar_settings"] = false
  452. permissions["sidebar_modules"] = map[string]interface{}{}
  453. } else if userRole == common.RoleAdminUser {
  454. // 管理员可以设置边栏,但不包含系统设置功能
  455. permissions["sidebar_settings"] = true
  456. permissions["sidebar_modules"] = map[string]interface{}{
  457. "admin": map[string]interface{}{
  458. "setting": false, // 管理员不能访问系统设置
  459. },
  460. }
  461. } else {
  462. // 普通用户只能设置个人功能,不包含管理员区域
  463. permissions["sidebar_settings"] = true
  464. permissions["sidebar_modules"] = map[string]interface{}{
  465. "admin": false, // 普通用户不能访问管理员区域
  466. }
  467. }
  468. return permissions
  469. }
  470. // 根据用户角色生成默认的边栏配置
  471. func generateDefaultSidebarConfig(userRole int) string {
  472. defaultConfig := map[string]interface{}{}
  473. // 聊天区域 - 所有用户都可以访问
  474. defaultConfig["chat"] = map[string]interface{}{
  475. "enabled": true,
  476. "playground": true,
  477. "chat": true,
  478. }
  479. // 控制台区域 - 所有用户都可以访问
  480. defaultConfig["console"] = map[string]interface{}{
  481. "enabled": true,
  482. "detail": true,
  483. "token": true,
  484. "log": true,
  485. "midjourney": true,
  486. "task": true,
  487. }
  488. // 个人中心区域 - 所有用户都可以访问
  489. defaultConfig["personal"] = map[string]interface{}{
  490. "enabled": true,
  491. "topup": true,
  492. "personal": true,
  493. }
  494. // 管理员区域 - 根据角色决定
  495. if userRole == common.RoleAdminUser {
  496. // 管理员可以访问管理员区域,但不能访问系统设置
  497. defaultConfig["admin"] = map[string]interface{}{
  498. "enabled": true,
  499. "channel": true,
  500. "models": true,
  501. "redemption": true,
  502. "user": true,
  503. "setting": false, // 管理员不能访问系统设置
  504. }
  505. } else if userRole == common.RoleRootUser {
  506. // 超级管理员可以访问所有功能
  507. defaultConfig["admin"] = map[string]interface{}{
  508. "enabled": true,
  509. "channel": true,
  510. "models": true,
  511. "redemption": true,
  512. "user": true,
  513. "setting": true,
  514. }
  515. }
  516. // 普通用户不包含admin区域
  517. // 转换为JSON字符串
  518. configBytes, err := json.Marshal(defaultConfig)
  519. if err != nil {
  520. common.SysLog("生成默认边栏配置失败: " + err.Error())
  521. return ""
  522. }
  523. return string(configBytes)
  524. }
  525. func GetUserModels(c *gin.Context) {
  526. id, err := strconv.Atoi(c.Param("id"))
  527. if err != nil {
  528. id = c.GetInt("id")
  529. }
  530. user, err := model.GetUserCache(id)
  531. if err != nil {
  532. common.ApiError(c, err)
  533. return
  534. }
  535. groups := setting.GetUserUsableGroups(user.Group)
  536. var models []string
  537. for group := range groups {
  538. for _, g := range model.GetGroupEnabledModels(group) {
  539. if !common.StringsContains(models, g) {
  540. models = append(models, g)
  541. }
  542. }
  543. }
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": true,
  546. "message": "",
  547. "data": models,
  548. })
  549. return
  550. }
  551. func UpdateUser(c *gin.Context) {
  552. var updatedUser model.User
  553. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  554. if err != nil || updatedUser.Id == 0 {
  555. c.JSON(http.StatusOK, gin.H{
  556. "success": false,
  557. "message": "无效的参数",
  558. })
  559. return
  560. }
  561. if updatedUser.Password == "" {
  562. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  563. }
  564. if err := common.Validate.Struct(&updatedUser); err != nil {
  565. c.JSON(http.StatusOK, gin.H{
  566. "success": false,
  567. "message": "输入不合法 " + err.Error(),
  568. })
  569. return
  570. }
  571. originUser, err := model.GetUserById(updatedUser.Id, false)
  572. if err != nil {
  573. common.ApiError(c, err)
  574. return
  575. }
  576. myRole := c.GetInt("role")
  577. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  578. c.JSON(http.StatusOK, gin.H{
  579. "success": false,
  580. "message": "无权更新同权限等级或更高权限等级的用户信息",
  581. })
  582. return
  583. }
  584. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": false,
  587. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  588. })
  589. return
  590. }
  591. if updatedUser.Password == "$I_LOVE_U" {
  592. updatedUser.Password = "" // rollback to what it should be
  593. }
  594. updatePassword := updatedUser.Password != ""
  595. if err := updatedUser.Edit(updatePassword); err != nil {
  596. common.ApiError(c, err)
  597. return
  598. }
  599. if originUser.Quota != updatedUser.Quota {
  600. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", logger.LogQuota(originUser.Quota), logger.LogQuota(updatedUser.Quota)))
  601. }
  602. c.JSON(http.StatusOK, gin.H{
  603. "success": true,
  604. "message": "",
  605. })
  606. return
  607. }
  608. func UpdateSelf(c *gin.Context) {
  609. var requestData map[string]interface{}
  610. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  611. if err != nil {
  612. c.JSON(http.StatusOK, gin.H{
  613. "success": false,
  614. "message": "无效的参数",
  615. })
  616. return
  617. }
  618. // 检查是否是sidebar_modules更新请求
  619. if sidebarModules, exists := requestData["sidebar_modules"]; exists {
  620. userId := c.GetInt("id")
  621. userRole := c.GetInt("role")
  622. if userRole != common.RoleRootUser && userRole != common.RoleAdminUser {
  623. c.JSON(http.StatusOK, gin.H{
  624. "success": false,
  625. "message": "无权更新设置",
  626. })
  627. return
  628. }
  629. user, err := model.GetUserById(userId, false)
  630. if err != nil {
  631. common.ApiError(c, err)
  632. return
  633. }
  634. // 获取当前用户设置
  635. currentSetting := user.GetSetting()
  636. // 更新sidebar_modules字段
  637. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  638. currentSetting.SidebarModules = sidebarModulesStr
  639. }
  640. // 保存更新后的设置
  641. user.SetSetting(currentSetting)
  642. if err := user.Update(false); err != nil {
  643. c.JSON(http.StatusOK, gin.H{
  644. "success": false,
  645. "message": "更新设置失败: " + err.Error(),
  646. })
  647. return
  648. }
  649. c.JSON(http.StatusOK, gin.H{
  650. "success": true,
  651. "message": "设置更新成功",
  652. })
  653. return
  654. }
  655. // 原有的用户信息更新逻辑
  656. var user model.User
  657. requestDataBytes, err := json.Marshal(requestData)
  658. if err != nil {
  659. c.JSON(http.StatusOK, gin.H{
  660. "success": false,
  661. "message": "无效的参数",
  662. })
  663. return
  664. }
  665. err = json.Unmarshal(requestDataBytes, &user)
  666. if err != nil {
  667. c.JSON(http.StatusOK, gin.H{
  668. "success": false,
  669. "message": "无效的参数",
  670. })
  671. return
  672. }
  673. if user.Password == "" {
  674. user.Password = "$I_LOVE_U" // make Validator happy :)
  675. }
  676. if err := common.Validate.Struct(&user); err != nil {
  677. c.JSON(http.StatusOK, gin.H{
  678. "success": false,
  679. "message": "输入不合法 " + err.Error(),
  680. })
  681. return
  682. }
  683. cleanUser := model.User{
  684. Id: c.GetInt("id"),
  685. Username: user.Username,
  686. Password: user.Password,
  687. DisplayName: user.DisplayName,
  688. }
  689. if user.Password == "$I_LOVE_U" {
  690. user.Password = "" // rollback to what it should be
  691. cleanUser.Password = ""
  692. }
  693. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  694. if err != nil {
  695. common.ApiError(c, err)
  696. return
  697. }
  698. if err := cleanUser.Update(updatePassword); err != nil {
  699. common.ApiError(c, err)
  700. return
  701. }
  702. c.JSON(http.StatusOK, gin.H{
  703. "success": true,
  704. "message": "",
  705. })
  706. return
  707. }
  708. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  709. var currentUser *model.User
  710. currentUser, err = model.GetUserById(userId, true)
  711. if err != nil {
  712. return
  713. }
  714. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) {
  715. err = fmt.Errorf("原密码错误")
  716. return
  717. }
  718. if newPassword == "" {
  719. return
  720. }
  721. updatePassword = true
  722. return
  723. }
  724. func DeleteUser(c *gin.Context) {
  725. id, err := strconv.Atoi(c.Param("id"))
  726. if err != nil {
  727. common.ApiError(c, err)
  728. return
  729. }
  730. originUser, err := model.GetUserById(id, false)
  731. if err != nil {
  732. common.ApiError(c, err)
  733. return
  734. }
  735. myRole := c.GetInt("role")
  736. if myRole <= originUser.Role {
  737. c.JSON(http.StatusOK, gin.H{
  738. "success": false,
  739. "message": "无权删除同权限等级或更高权限等级的用户",
  740. })
  741. return
  742. }
  743. err = model.HardDeleteUserById(id)
  744. if err != nil {
  745. c.JSON(http.StatusOK, gin.H{
  746. "success": true,
  747. "message": "",
  748. })
  749. return
  750. }
  751. }
  752. func DeleteSelf(c *gin.Context) {
  753. id := c.GetInt("id")
  754. user, _ := model.GetUserById(id, false)
  755. if user.Role == common.RoleRootUser {
  756. c.JSON(http.StatusOK, gin.H{
  757. "success": false,
  758. "message": "不能删除超级管理员账户",
  759. })
  760. return
  761. }
  762. err := model.DeleteUserById(id)
  763. if err != nil {
  764. common.ApiError(c, err)
  765. return
  766. }
  767. c.JSON(http.StatusOK, gin.H{
  768. "success": true,
  769. "message": "",
  770. })
  771. return
  772. }
  773. func CreateUser(c *gin.Context) {
  774. var user model.User
  775. err := json.NewDecoder(c.Request.Body).Decode(&user)
  776. user.Username = strings.TrimSpace(user.Username)
  777. if err != nil || user.Username == "" || user.Password == "" {
  778. c.JSON(http.StatusOK, gin.H{
  779. "success": false,
  780. "message": "无效的参数",
  781. })
  782. return
  783. }
  784. if err := common.Validate.Struct(&user); err != nil {
  785. c.JSON(http.StatusOK, gin.H{
  786. "success": false,
  787. "message": "输入不合法 " + err.Error(),
  788. })
  789. return
  790. }
  791. if user.DisplayName == "" {
  792. user.DisplayName = user.Username
  793. }
  794. myRole := c.GetInt("role")
  795. if user.Role >= myRole {
  796. c.JSON(http.StatusOK, gin.H{
  797. "success": false,
  798. "message": "无法创建权限大于等于自己的用户",
  799. })
  800. return
  801. }
  802. // Even for admin users, we cannot fully trust them!
  803. cleanUser := model.User{
  804. Username: user.Username,
  805. Password: user.Password,
  806. DisplayName: user.DisplayName,
  807. Role: user.Role, // 保持管理员设置的角色
  808. }
  809. if err := cleanUser.Insert(0); err != nil {
  810. common.ApiError(c, err)
  811. return
  812. }
  813. c.JSON(http.StatusOK, gin.H{
  814. "success": true,
  815. "message": "",
  816. })
  817. return
  818. }
  819. type ManageRequest struct {
  820. Id int `json:"id"`
  821. Action string `json:"action"`
  822. }
  823. // ManageUser Only admin user can do this
  824. func ManageUser(c *gin.Context) {
  825. var req ManageRequest
  826. err := json.NewDecoder(c.Request.Body).Decode(&req)
  827. if err != nil {
  828. c.JSON(http.StatusOK, gin.H{
  829. "success": false,
  830. "message": "无效的参数",
  831. })
  832. return
  833. }
  834. user := model.User{
  835. Id: req.Id,
  836. }
  837. // Fill attributes
  838. model.DB.Unscoped().Where(&user).First(&user)
  839. if user.Id == 0 {
  840. c.JSON(http.StatusOK, gin.H{
  841. "success": false,
  842. "message": "用户不存在",
  843. })
  844. return
  845. }
  846. myRole := c.GetInt("role")
  847. if myRole <= user.Role && myRole != common.RoleRootUser {
  848. c.JSON(http.StatusOK, gin.H{
  849. "success": false,
  850. "message": "无权更新同权限等级或更高权限等级的用户信息",
  851. })
  852. return
  853. }
  854. switch req.Action {
  855. case "disable":
  856. user.Status = common.UserStatusDisabled
  857. if user.Role == common.RoleRootUser {
  858. c.JSON(http.StatusOK, gin.H{
  859. "success": false,
  860. "message": "无法禁用超级管理员用户",
  861. })
  862. return
  863. }
  864. case "enable":
  865. user.Status = common.UserStatusEnabled
  866. case "delete":
  867. if user.Role == common.RoleRootUser {
  868. c.JSON(http.StatusOK, gin.H{
  869. "success": false,
  870. "message": "无法删除超级管理员用户",
  871. })
  872. return
  873. }
  874. if err := user.Delete(); err != nil {
  875. c.JSON(http.StatusOK, gin.H{
  876. "success": false,
  877. "message": err.Error(),
  878. })
  879. return
  880. }
  881. case "promote":
  882. if myRole != common.RoleRootUser {
  883. c.JSON(http.StatusOK, gin.H{
  884. "success": false,
  885. "message": "普通管理员用户无法提升其他用户为管理员",
  886. })
  887. return
  888. }
  889. if user.Role >= common.RoleAdminUser {
  890. c.JSON(http.StatusOK, gin.H{
  891. "success": false,
  892. "message": "该用户已经是管理员",
  893. })
  894. return
  895. }
  896. user.Role = common.RoleAdminUser
  897. case "demote":
  898. if user.Role == common.RoleRootUser {
  899. c.JSON(http.StatusOK, gin.H{
  900. "success": false,
  901. "message": "无法降级超级管理员用户",
  902. })
  903. return
  904. }
  905. if user.Role == common.RoleCommonUser {
  906. c.JSON(http.StatusOK, gin.H{
  907. "success": false,
  908. "message": "该用户已经是普通用户",
  909. })
  910. return
  911. }
  912. user.Role = common.RoleCommonUser
  913. }
  914. if err := user.Update(false); err != nil {
  915. common.ApiError(c, err)
  916. return
  917. }
  918. clearUser := model.User{
  919. Role: user.Role,
  920. Status: user.Status,
  921. }
  922. c.JSON(http.StatusOK, gin.H{
  923. "success": true,
  924. "message": "",
  925. "data": clearUser,
  926. })
  927. return
  928. }
  929. func EmailBind(c *gin.Context) {
  930. email := c.Query("email")
  931. code := c.Query("code")
  932. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  933. c.JSON(http.StatusOK, gin.H{
  934. "success": false,
  935. "message": "验证码错误或已过期",
  936. })
  937. return
  938. }
  939. session := sessions.Default(c)
  940. id := session.Get("id")
  941. user := model.User{
  942. Id: id.(int),
  943. }
  944. err := user.FillUserById()
  945. if err != nil {
  946. common.ApiError(c, err)
  947. return
  948. }
  949. user.Email = email
  950. // no need to check if this email already taken, because we have used verification code to check it
  951. err = user.Update(false)
  952. if err != nil {
  953. common.ApiError(c, err)
  954. return
  955. }
  956. c.JSON(http.StatusOK, gin.H{
  957. "success": true,
  958. "message": "",
  959. })
  960. return
  961. }
  962. type topUpRequest struct {
  963. Key string `json:"key"`
  964. }
  965. var topUpLocks sync.Map
  966. var topUpCreateLock sync.Mutex
  967. type topUpTryLock struct {
  968. ch chan struct{}
  969. }
  970. func newTopUpTryLock() *topUpTryLock {
  971. return &topUpTryLock{ch: make(chan struct{}, 1)}
  972. }
  973. func (l *topUpTryLock) TryLock() bool {
  974. select {
  975. case l.ch <- struct{}{}:
  976. return true
  977. default:
  978. return false
  979. }
  980. }
  981. func (l *topUpTryLock) Unlock() {
  982. select {
  983. case <-l.ch:
  984. default:
  985. }
  986. }
  987. func getTopUpLock(userID int) *topUpTryLock {
  988. if v, ok := topUpLocks.Load(userID); ok {
  989. return v.(*topUpTryLock)
  990. }
  991. topUpCreateLock.Lock()
  992. defer topUpCreateLock.Unlock()
  993. if v, ok := topUpLocks.Load(userID); ok {
  994. return v.(*topUpTryLock)
  995. }
  996. l := newTopUpTryLock()
  997. topUpLocks.Store(userID, l)
  998. return l
  999. }
  1000. func TopUp(c *gin.Context) {
  1001. id := c.GetInt("id")
  1002. lock := getTopUpLock(id)
  1003. if !lock.TryLock() {
  1004. c.JSON(http.StatusOK, gin.H{
  1005. "success": false,
  1006. "message": "充值处理中,请稍后重试",
  1007. })
  1008. return
  1009. }
  1010. defer lock.Unlock()
  1011. req := topUpRequest{}
  1012. err := c.ShouldBindJSON(&req)
  1013. if err != nil {
  1014. common.ApiError(c, err)
  1015. return
  1016. }
  1017. quota, err := model.Redeem(req.Key, id)
  1018. if err != nil {
  1019. common.ApiError(c, err)
  1020. return
  1021. }
  1022. c.JSON(http.StatusOK, gin.H{
  1023. "success": true,
  1024. "message": "",
  1025. "data": quota,
  1026. })
  1027. }
  1028. type UpdateUserSettingRequest struct {
  1029. QuotaWarningType string `json:"notify_type"`
  1030. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  1031. WebhookUrl string `json:"webhook_url,omitempty"`
  1032. WebhookSecret string `json:"webhook_secret,omitempty"`
  1033. NotificationEmail string `json:"notification_email,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 {
  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. userId := c.GetInt("id")
  1092. user, err := model.GetUserById(userId, true)
  1093. if err != nil {
  1094. common.ApiError(c, err)
  1095. return
  1096. }
  1097. // 构建设置
  1098. settings := dto.UserSetting{
  1099. NotifyType: req.QuotaWarningType,
  1100. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1101. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1102. RecordIpLog: req.RecordIpLog,
  1103. }
  1104. // 如果是webhook类型,添加webhook相关设置
  1105. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1106. settings.WebhookUrl = req.WebhookUrl
  1107. if req.WebhookSecret != "" {
  1108. settings.WebhookSecret = req.WebhookSecret
  1109. }
  1110. }
  1111. // 如果提供了通知邮箱,添加到设置中
  1112. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1113. settings.NotificationEmail = req.NotificationEmail
  1114. }
  1115. // 更新用户设置
  1116. user.SetSetting(settings)
  1117. if err := user.Update(false); err != nil {
  1118. c.JSON(http.StatusOK, gin.H{
  1119. "success": false,
  1120. "message": "更新设置失败: " + err.Error(),
  1121. })
  1122. return
  1123. }
  1124. c.JSON(http.StatusOK, gin.H{
  1125. "success": true,
  1126. "message": "设置已更新",
  1127. })
  1128. }