user.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  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. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  1032. RecordIpLog bool `json:"record_ip_log"`
  1033. }
  1034. func UpdateUserSetting(c *gin.Context) {
  1035. var req UpdateUserSettingRequest
  1036. if err := c.ShouldBindJSON(&req); err != nil {
  1037. c.JSON(http.StatusOK, gin.H{
  1038. "success": false,
  1039. "message": "无效的参数",
  1040. })
  1041. return
  1042. }
  1043. // 验证预警类型
  1044. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark {
  1045. c.JSON(http.StatusOK, gin.H{
  1046. "success": false,
  1047. "message": "无效的预警类型",
  1048. })
  1049. return
  1050. }
  1051. // 验证预警阈值
  1052. if req.QuotaWarningThreshold <= 0 {
  1053. c.JSON(http.StatusOK, gin.H{
  1054. "success": false,
  1055. "message": "预警阈值必须大于0",
  1056. })
  1057. return
  1058. }
  1059. // 如果是webhook类型,验证webhook地址
  1060. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1061. if req.WebhookUrl == "" {
  1062. c.JSON(http.StatusOK, gin.H{
  1063. "success": false,
  1064. "message": "Webhook地址不能为空",
  1065. })
  1066. return
  1067. }
  1068. // 验证URL格式
  1069. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1070. c.JSON(http.StatusOK, gin.H{
  1071. "success": false,
  1072. "message": "无效的Webhook地址",
  1073. })
  1074. return
  1075. }
  1076. }
  1077. // 如果是邮件类型,验证邮箱地址
  1078. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1079. // 验证邮箱格式
  1080. if !strings.Contains(req.NotificationEmail, "@") {
  1081. c.JSON(http.StatusOK, gin.H{
  1082. "success": false,
  1083. "message": "无效的邮箱地址",
  1084. })
  1085. return
  1086. }
  1087. }
  1088. // 如果是Bark类型,验证Bark URL
  1089. if req.QuotaWarningType == dto.NotifyTypeBark {
  1090. if req.BarkUrl == "" {
  1091. c.JSON(http.StatusOK, gin.H{
  1092. "success": false,
  1093. "message": "Bark推送URL不能为空",
  1094. })
  1095. return
  1096. }
  1097. // 验证URL格式
  1098. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1099. c.JSON(http.StatusOK, gin.H{
  1100. "success": false,
  1101. "message": "无效的Bark推送URL",
  1102. })
  1103. return
  1104. }
  1105. // 检查是否是HTTP或HTTPS
  1106. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1107. c.JSON(http.StatusOK, gin.H{
  1108. "success": false,
  1109. "message": "Bark推送URL必须以http://或https://开头",
  1110. })
  1111. return
  1112. }
  1113. }
  1114. userId := c.GetInt("id")
  1115. user, err := model.GetUserById(userId, true)
  1116. if err != nil {
  1117. common.ApiError(c, err)
  1118. return
  1119. }
  1120. // 构建设置
  1121. settings := dto.UserSetting{
  1122. NotifyType: req.QuotaWarningType,
  1123. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1124. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1125. RecordIpLog: req.RecordIpLog,
  1126. }
  1127. // 如果是webhook类型,添加webhook相关设置
  1128. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1129. settings.WebhookUrl = req.WebhookUrl
  1130. if req.WebhookSecret != "" {
  1131. settings.WebhookSecret = req.WebhookSecret
  1132. }
  1133. }
  1134. // 如果提供了通知邮箱,添加到设置中
  1135. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1136. settings.NotificationEmail = req.NotificationEmail
  1137. }
  1138. // 如果是Bark类型,添加Bark URL到设置中
  1139. if req.QuotaWarningType == dto.NotifyTypeBark {
  1140. settings.BarkUrl = req.BarkUrl
  1141. }
  1142. // 更新用户设置
  1143. user.SetSetting(settings)
  1144. if err := user.Update(false); err != nil {
  1145. c.JSON(http.StatusOK, gin.H{
  1146. "success": false,
  1147. "message": "更新设置失败: " + err.Error(),
  1148. })
  1149. return
  1150. }
  1151. c.JSON(http.StatusOK, gin.H{
  1152. "success": true,
  1153. "message": "设置已更新",
  1154. })
  1155. }