user.go 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "one-api/common"
  8. "one-api/model"
  9. "one-api/setting"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "one-api/constant"
  14. "github.com/gin-contrib/sessions"
  15. "github.com/gin-gonic/gin"
  16. )
  17. type LoginRequest struct {
  18. Username string `json:"username"`
  19. Password string `json:"password"`
  20. }
  21. func Login(c *gin.Context) {
  22. if !common.PasswordLoginEnabled {
  23. c.JSON(http.StatusOK, gin.H{
  24. "message": "管理员关闭了密码登录",
  25. "success": false,
  26. })
  27. return
  28. }
  29. var loginRequest LoginRequest
  30. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  31. if err != nil {
  32. c.JSON(http.StatusOK, gin.H{
  33. "message": "无效的参数",
  34. "success": false,
  35. })
  36. return
  37. }
  38. username := loginRequest.Username
  39. password := loginRequest.Password
  40. if username == "" || password == "" {
  41. c.JSON(http.StatusOK, gin.H{
  42. "message": "无效的参数",
  43. "success": false,
  44. })
  45. return
  46. }
  47. user := model.User{
  48. Username: username,
  49. Password: password,
  50. }
  51. err = user.ValidateAndFill()
  52. if err != nil {
  53. c.JSON(http.StatusOK, gin.H{
  54. "message": err.Error(),
  55. "success": false,
  56. })
  57. return
  58. }
  59. setupLogin(&user, c)
  60. }
  61. // setup session & cookies and then return user info
  62. func setupLogin(user *model.User, c *gin.Context) {
  63. session := sessions.Default(c)
  64. session.Set("id", user.Id)
  65. session.Set("username", user.Username)
  66. session.Set("role", user.Role)
  67. session.Set("status", user.Status)
  68. session.Set("group", user.Group)
  69. err := session.Save()
  70. if err != nil {
  71. c.JSON(http.StatusOK, gin.H{
  72. "message": "无法保存会话信息,请重试",
  73. "success": false,
  74. })
  75. return
  76. }
  77. cleanUser := model.User{
  78. Id: user.Id,
  79. Username: user.Username,
  80. DisplayName: user.DisplayName,
  81. Role: user.Role,
  82. Status: user.Status,
  83. Group: user.Group,
  84. }
  85. c.JSON(http.StatusOK, gin.H{
  86. "message": "",
  87. "success": true,
  88. "data": cleanUser,
  89. })
  90. }
  91. func Logout(c *gin.Context) {
  92. session := sessions.Default(c)
  93. session.Clear()
  94. err := session.Save()
  95. if err != nil {
  96. c.JSON(http.StatusOK, gin.H{
  97. "message": err.Error(),
  98. "success": false,
  99. })
  100. return
  101. }
  102. c.JSON(http.StatusOK, gin.H{
  103. "message": "",
  104. "success": true,
  105. })
  106. }
  107. func Register(c *gin.Context) {
  108. if !common.RegisterEnabled {
  109. c.JSON(http.StatusOK, gin.H{
  110. "message": "管理员关闭了新用户注册",
  111. "success": false,
  112. })
  113. return
  114. }
  115. if !common.PasswordRegisterEnabled {
  116. c.JSON(http.StatusOK, gin.H{
  117. "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
  118. "success": false,
  119. })
  120. return
  121. }
  122. var user model.User
  123. err := json.NewDecoder(c.Request.Body).Decode(&user)
  124. if err != nil {
  125. c.JSON(http.StatusOK, gin.H{
  126. "success": false,
  127. "message": "无效的参数",
  128. })
  129. return
  130. }
  131. if err := common.Validate.Struct(&user); err != nil {
  132. c.JSON(http.StatusOK, gin.H{
  133. "success": false,
  134. "message": "输入不合法 " + err.Error(),
  135. })
  136. return
  137. }
  138. if common.EmailVerificationEnabled {
  139. if user.Email == "" || user.VerificationCode == "" {
  140. c.JSON(http.StatusOK, gin.H{
  141. "success": false,
  142. "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
  143. })
  144. return
  145. }
  146. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  147. c.JSON(http.StatusOK, gin.H{
  148. "success": false,
  149. "message": "验证码错误或已过期",
  150. })
  151. return
  152. }
  153. }
  154. exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
  155. if err != nil {
  156. c.JSON(http.StatusOK, gin.H{
  157. "success": false,
  158. "message": "数据库错误,请稍后重试",
  159. })
  160. common.SysError(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
  161. return
  162. }
  163. if exist {
  164. c.JSON(http.StatusOK, gin.H{
  165. "success": false,
  166. "message": "用户名已存在,或已注销",
  167. })
  168. return
  169. }
  170. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  171. inviterId, _ := model.GetUserIdByAffCode(affCode)
  172. cleanUser := model.User{
  173. Username: user.Username,
  174. Password: user.Password,
  175. DisplayName: user.Username,
  176. InviterId: inviterId,
  177. }
  178. if common.EmailVerificationEnabled {
  179. cleanUser.Email = user.Email
  180. }
  181. if err := cleanUser.Insert(inviterId); err != nil {
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": false,
  184. "message": err.Error(),
  185. })
  186. return
  187. }
  188. // 获取插入后的用户ID
  189. var insertedUser model.User
  190. if err := model.DB.Where("username = ?", cleanUser.Username).First(&insertedUser).Error; err != nil {
  191. c.JSON(http.StatusOK, gin.H{
  192. "success": false,
  193. "message": "用户注册失败或用户ID获取失败",
  194. })
  195. return
  196. }
  197. // 生成默认令牌
  198. if constant.GenerateDefaultToken {
  199. key, err := common.GenerateKey()
  200. if err != nil {
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": false,
  203. "message": "生成默认令牌失败",
  204. })
  205. common.SysError("failed to generate token key: " + err.Error())
  206. return
  207. }
  208. // 生成默认令牌
  209. token := model.Token{
  210. UserId: insertedUser.Id, // 使用插入后的用户ID
  211. Name: cleanUser.Username + "的初始令牌",
  212. Key: key,
  213. CreatedTime: common.GetTimestamp(),
  214. AccessedTime: common.GetTimestamp(),
  215. ExpiredTime: -1, // 永不过期
  216. RemainQuota: 500000, // 示例额度
  217. UnlimitedQuota: true,
  218. ModelLimitsEnabled: false,
  219. }
  220. if err := token.Insert(); err != nil {
  221. c.JSON(http.StatusOK, gin.H{
  222. "success": false,
  223. "message": "创建默认令牌失败",
  224. })
  225. return
  226. }
  227. }
  228. c.JSON(http.StatusOK, gin.H{
  229. "success": true,
  230. "message": "",
  231. })
  232. return
  233. }
  234. func GetAllUsers(c *gin.Context) {
  235. p, _ := strconv.Atoi(c.Query("p"))
  236. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  237. if p < 1 {
  238. p = 1
  239. }
  240. if pageSize < 0 {
  241. pageSize = common.ItemsPerPage
  242. }
  243. users, total, err := model.GetAllUsers((p-1)*pageSize, pageSize)
  244. if err != nil {
  245. c.JSON(http.StatusOK, gin.H{
  246. "success": false,
  247. "message": err.Error(),
  248. })
  249. return
  250. }
  251. c.JSON(http.StatusOK, gin.H{
  252. "success": true,
  253. "message": "",
  254. "data": gin.H{
  255. "items": users,
  256. "total": total,
  257. "page": p,
  258. "page_size": pageSize,
  259. },
  260. })
  261. return
  262. }
  263. func SearchUsers(c *gin.Context) {
  264. keyword := c.Query("keyword")
  265. group := c.Query("group")
  266. p, _ := strconv.Atoi(c.Query("p"))
  267. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  268. if p < 1 {
  269. p = 1
  270. }
  271. if pageSize < 0 {
  272. pageSize = common.ItemsPerPage
  273. }
  274. startIdx := (p - 1) * pageSize
  275. users, total, err := model.SearchUsers(keyword, group, startIdx, pageSize)
  276. if err != nil {
  277. c.JSON(http.StatusOK, gin.H{
  278. "success": false,
  279. "message": err.Error(),
  280. })
  281. return
  282. }
  283. c.JSON(http.StatusOK, gin.H{
  284. "success": true,
  285. "message": "",
  286. "data": gin.H{
  287. "items": users,
  288. "total": total,
  289. "page": p,
  290. "page_size": pageSize,
  291. },
  292. })
  293. return
  294. }
  295. func GetUser(c *gin.Context) {
  296. id, err := strconv.Atoi(c.Param("id"))
  297. if err != nil {
  298. c.JSON(http.StatusOK, gin.H{
  299. "success": false,
  300. "message": err.Error(),
  301. })
  302. return
  303. }
  304. user, err := model.GetUserById(id, false)
  305. if err != nil {
  306. c.JSON(http.StatusOK, gin.H{
  307. "success": false,
  308. "message": err.Error(),
  309. })
  310. return
  311. }
  312. myRole := c.GetInt("role")
  313. if myRole <= user.Role && myRole != common.RoleRootUser {
  314. c.JSON(http.StatusOK, gin.H{
  315. "success": false,
  316. "message": "无权获取同级或更高等级用户的信息",
  317. })
  318. return
  319. }
  320. c.JSON(http.StatusOK, gin.H{
  321. "success": true,
  322. "message": "",
  323. "data": user,
  324. })
  325. return
  326. }
  327. func GenerateAccessToken(c *gin.Context) {
  328. id := c.GetInt("id")
  329. user, err := model.GetUserById(id, true)
  330. if err != nil {
  331. c.JSON(http.StatusOK, gin.H{
  332. "success": false,
  333. "message": err.Error(),
  334. })
  335. return
  336. }
  337. // get rand int 28-32
  338. randI := common.GetRandomInt(4)
  339. key, err := common.GenerateRandomKey(29 + randI)
  340. if err != nil {
  341. c.JSON(http.StatusOK, gin.H{
  342. "success": false,
  343. "message": "生成失败",
  344. })
  345. common.SysError("failed to generate key: " + err.Error())
  346. return
  347. }
  348. user.SetAccessToken(key)
  349. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  350. c.JSON(http.StatusOK, gin.H{
  351. "success": false,
  352. "message": "请重试,系统生成的 UUID 竟然重复了!",
  353. })
  354. return
  355. }
  356. if err := user.Update(false); err != nil {
  357. c.JSON(http.StatusOK, gin.H{
  358. "success": false,
  359. "message": err.Error(),
  360. })
  361. return
  362. }
  363. c.JSON(http.StatusOK, gin.H{
  364. "success": true,
  365. "message": "",
  366. "data": user.AccessToken,
  367. })
  368. return
  369. }
  370. type TransferAffQuotaRequest struct {
  371. Quota int `json:"quota" binding:"required"`
  372. }
  373. func TransferAffQuota(c *gin.Context) {
  374. id := c.GetInt("id")
  375. user, err := model.GetUserById(id, true)
  376. if err != nil {
  377. c.JSON(http.StatusOK, gin.H{
  378. "success": false,
  379. "message": err.Error(),
  380. })
  381. return
  382. }
  383. tran := TransferAffQuotaRequest{}
  384. if err := c.ShouldBindJSON(&tran); err != nil {
  385. c.JSON(http.StatusOK, gin.H{
  386. "success": false,
  387. "message": err.Error(),
  388. })
  389. return
  390. }
  391. err = user.TransferAffQuotaToQuota(tran.Quota)
  392. if err != nil {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "划转失败 " + err.Error(),
  396. })
  397. return
  398. }
  399. c.JSON(http.StatusOK, gin.H{
  400. "success": true,
  401. "message": "划转成功",
  402. })
  403. }
  404. func GetAffCode(c *gin.Context) {
  405. id := c.GetInt("id")
  406. user, err := model.GetUserById(id, true)
  407. if err != nil {
  408. c.JSON(http.StatusOK, gin.H{
  409. "success": false,
  410. "message": err.Error(),
  411. })
  412. return
  413. }
  414. if user.AffCode == "" {
  415. user.AffCode = common.GetRandomString(4)
  416. if err := user.Update(false); err != nil {
  417. c.JSON(http.StatusOK, gin.H{
  418. "success": false,
  419. "message": err.Error(),
  420. })
  421. return
  422. }
  423. }
  424. c.JSON(http.StatusOK, gin.H{
  425. "success": true,
  426. "message": "",
  427. "data": user.AffCode,
  428. })
  429. return
  430. }
  431. func GetSelf(c *gin.Context) {
  432. id := c.GetInt("id")
  433. user, err := model.GetUserById(id, false)
  434. if err != nil {
  435. c.JSON(http.StatusOK, gin.H{
  436. "success": false,
  437. "message": err.Error(),
  438. })
  439. return
  440. }
  441. c.JSON(http.StatusOK, gin.H{
  442. "success": true,
  443. "message": "",
  444. "data": user,
  445. })
  446. return
  447. }
  448. func GetUserModels(c *gin.Context) {
  449. id, err := strconv.Atoi(c.Param("id"))
  450. if err != nil {
  451. id = c.GetInt("id")
  452. }
  453. user, err := model.GetUserCache(id)
  454. if err != nil {
  455. c.JSON(http.StatusOK, gin.H{
  456. "success": false,
  457. "message": err.Error(),
  458. })
  459. return
  460. }
  461. groups := setting.GetUserUsableGroups(user.Group)
  462. var models []string
  463. for group := range groups {
  464. for _, g := range model.GetGroupModels(group) {
  465. if !common.StringsContains(models, g) {
  466. models = append(models, g)
  467. }
  468. }
  469. }
  470. c.JSON(http.StatusOK, gin.H{
  471. "success": true,
  472. "message": "",
  473. "data": models,
  474. })
  475. return
  476. }
  477. func UpdateUser(c *gin.Context) {
  478. var updatedUser model.User
  479. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  480. if err != nil || updatedUser.Id == 0 {
  481. c.JSON(http.StatusOK, gin.H{
  482. "success": false,
  483. "message": "无效的参数",
  484. })
  485. return
  486. }
  487. if updatedUser.Password == "" {
  488. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  489. }
  490. if err := common.Validate.Struct(&updatedUser); err != nil {
  491. c.JSON(http.StatusOK, gin.H{
  492. "success": false,
  493. "message": "输入不合法 " + err.Error(),
  494. })
  495. return
  496. }
  497. originUser, err := model.GetUserById(updatedUser.Id, false)
  498. if err != nil {
  499. c.JSON(http.StatusOK, gin.H{
  500. "success": false,
  501. "message": err.Error(),
  502. })
  503. return
  504. }
  505. myRole := c.GetInt("role")
  506. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  507. c.JSON(http.StatusOK, gin.H{
  508. "success": false,
  509. "message": "无权更新同权限等级或更高权限等级的用户信息",
  510. })
  511. return
  512. }
  513. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  514. c.JSON(http.StatusOK, gin.H{
  515. "success": false,
  516. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  517. })
  518. return
  519. }
  520. if updatedUser.Password == "$I_LOVE_U" {
  521. updatedUser.Password = "" // rollback to what it should be
  522. }
  523. updatePassword := updatedUser.Password != ""
  524. if err := updatedUser.Edit(updatePassword); err != nil {
  525. c.JSON(http.StatusOK, gin.H{
  526. "success": false,
  527. "message": err.Error(),
  528. })
  529. return
  530. }
  531. if originUser.Quota != updatedUser.Quota {
  532. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota)))
  533. }
  534. c.JSON(http.StatusOK, gin.H{
  535. "success": true,
  536. "message": "",
  537. })
  538. return
  539. }
  540. func UpdateSelf(c *gin.Context) {
  541. var user model.User
  542. err := json.NewDecoder(c.Request.Body).Decode(&user)
  543. if err != nil {
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": false,
  546. "message": "无效的参数",
  547. })
  548. return
  549. }
  550. if user.Password == "" {
  551. user.Password = "$I_LOVE_U" // make Validator happy :)
  552. }
  553. if err := common.Validate.Struct(&user); err != nil {
  554. c.JSON(http.StatusOK, gin.H{
  555. "success": false,
  556. "message": "输入不合法 " + err.Error(),
  557. })
  558. return
  559. }
  560. cleanUser := model.User{
  561. Id: c.GetInt("id"),
  562. Username: user.Username,
  563. Password: user.Password,
  564. DisplayName: user.DisplayName,
  565. }
  566. if user.Password == "$I_LOVE_U" {
  567. user.Password = "" // rollback to what it should be
  568. cleanUser.Password = ""
  569. }
  570. updatePassword := user.Password != ""
  571. if err := cleanUser.Update(updatePassword); err != nil {
  572. c.JSON(http.StatusOK, gin.H{
  573. "success": false,
  574. "message": err.Error(),
  575. })
  576. return
  577. }
  578. c.JSON(http.StatusOK, gin.H{
  579. "success": true,
  580. "message": "",
  581. })
  582. return
  583. }
  584. func DeleteUser(c *gin.Context) {
  585. id, err := strconv.Atoi(c.Param("id"))
  586. if err != nil {
  587. c.JSON(http.StatusOK, gin.H{
  588. "success": false,
  589. "message": err.Error(),
  590. })
  591. return
  592. }
  593. originUser, err := model.GetUserById(id, false)
  594. if err != nil {
  595. c.JSON(http.StatusOK, gin.H{
  596. "success": false,
  597. "message": err.Error(),
  598. })
  599. return
  600. }
  601. myRole := c.GetInt("role")
  602. if myRole <= originUser.Role {
  603. c.JSON(http.StatusOK, gin.H{
  604. "success": false,
  605. "message": "无权删除同权限等级或更高权限等级的用户",
  606. })
  607. return
  608. }
  609. err = model.HardDeleteUserById(id)
  610. if err != nil {
  611. c.JSON(http.StatusOK, gin.H{
  612. "success": true,
  613. "message": "",
  614. })
  615. return
  616. }
  617. }
  618. func DeleteSelf(c *gin.Context) {
  619. id := c.GetInt("id")
  620. user, _ := model.GetUserById(id, false)
  621. if user.Role == common.RoleRootUser {
  622. c.JSON(http.StatusOK, gin.H{
  623. "success": false,
  624. "message": "不能删除超级管理员账户",
  625. })
  626. return
  627. }
  628. err := model.DeleteUserById(id)
  629. if err != nil {
  630. c.JSON(http.StatusOK, gin.H{
  631. "success": false,
  632. "message": err.Error(),
  633. })
  634. return
  635. }
  636. c.JSON(http.StatusOK, gin.H{
  637. "success": true,
  638. "message": "",
  639. })
  640. return
  641. }
  642. func CreateUser(c *gin.Context) {
  643. var user model.User
  644. err := json.NewDecoder(c.Request.Body).Decode(&user)
  645. user.Username = strings.TrimSpace(user.Username)
  646. if err != nil || user.Username == "" || user.Password == "" {
  647. c.JSON(http.StatusOK, gin.H{
  648. "success": false,
  649. "message": "无效的参数",
  650. })
  651. return
  652. }
  653. if err := common.Validate.Struct(&user); err != nil {
  654. c.JSON(http.StatusOK, gin.H{
  655. "success": false,
  656. "message": "输入不合法 " + err.Error(),
  657. })
  658. return
  659. }
  660. if user.DisplayName == "" {
  661. user.DisplayName = user.Username
  662. }
  663. myRole := c.GetInt("role")
  664. if user.Role >= myRole {
  665. c.JSON(http.StatusOK, gin.H{
  666. "success": false,
  667. "message": "无法创建权限大于等于自己的用户",
  668. })
  669. return
  670. }
  671. // Even for admin users, we cannot fully trust them!
  672. cleanUser := model.User{
  673. Username: user.Username,
  674. Password: user.Password,
  675. DisplayName: user.DisplayName,
  676. }
  677. if err := cleanUser.Insert(0); err != nil {
  678. c.JSON(http.StatusOK, gin.H{
  679. "success": false,
  680. "message": err.Error(),
  681. })
  682. return
  683. }
  684. c.JSON(http.StatusOK, gin.H{
  685. "success": true,
  686. "message": "",
  687. })
  688. return
  689. }
  690. type ManageRequest struct {
  691. Id int `json:"id"`
  692. Action string `json:"action"`
  693. }
  694. // ManageUser Only admin user can do this
  695. func ManageUser(c *gin.Context) {
  696. var req ManageRequest
  697. err := json.NewDecoder(c.Request.Body).Decode(&req)
  698. if err != nil {
  699. c.JSON(http.StatusOK, gin.H{
  700. "success": false,
  701. "message": "无效的参数",
  702. })
  703. return
  704. }
  705. user := model.User{
  706. Id: req.Id,
  707. }
  708. // Fill attributes
  709. model.DB.Unscoped().Where(&user).First(&user)
  710. if user.Id == 0 {
  711. c.JSON(http.StatusOK, gin.H{
  712. "success": false,
  713. "message": "用户不存在",
  714. })
  715. return
  716. }
  717. myRole := c.GetInt("role")
  718. if myRole <= user.Role && myRole != common.RoleRootUser {
  719. c.JSON(http.StatusOK, gin.H{
  720. "success": false,
  721. "message": "无权更新同权限等级或更高权限等级的用户信息",
  722. })
  723. return
  724. }
  725. switch req.Action {
  726. case "disable":
  727. user.Status = common.UserStatusDisabled
  728. if user.Role == common.RoleRootUser {
  729. c.JSON(http.StatusOK, gin.H{
  730. "success": false,
  731. "message": "无法禁用超级管理员用户",
  732. })
  733. return
  734. }
  735. case "enable":
  736. user.Status = common.UserStatusEnabled
  737. case "delete":
  738. if user.Role == common.RoleRootUser {
  739. c.JSON(http.StatusOK, gin.H{
  740. "success": false,
  741. "message": "无法删除超级管理员用户",
  742. })
  743. return
  744. }
  745. if err := user.Delete(); err != nil {
  746. c.JSON(http.StatusOK, gin.H{
  747. "success": false,
  748. "message": err.Error(),
  749. })
  750. return
  751. }
  752. case "promote":
  753. if myRole != common.RoleRootUser {
  754. c.JSON(http.StatusOK, gin.H{
  755. "success": false,
  756. "message": "普通管理员用户无法提升其他用户为管理员",
  757. })
  758. return
  759. }
  760. if user.Role >= common.RoleAdminUser {
  761. c.JSON(http.StatusOK, gin.H{
  762. "success": false,
  763. "message": "该用户已经是管理员",
  764. })
  765. return
  766. }
  767. user.Role = common.RoleAdminUser
  768. case "demote":
  769. if user.Role == common.RoleRootUser {
  770. c.JSON(http.StatusOK, gin.H{
  771. "success": false,
  772. "message": "无法降级超级管理员用户",
  773. })
  774. return
  775. }
  776. if user.Role == common.RoleCommonUser {
  777. c.JSON(http.StatusOK, gin.H{
  778. "success": false,
  779. "message": "该用户已经是普通用户",
  780. })
  781. return
  782. }
  783. user.Role = common.RoleCommonUser
  784. }
  785. if err := user.Update(false); err != nil {
  786. c.JSON(http.StatusOK, gin.H{
  787. "success": false,
  788. "message": err.Error(),
  789. })
  790. return
  791. }
  792. clearUser := model.User{
  793. Role: user.Role,
  794. Status: user.Status,
  795. }
  796. c.JSON(http.StatusOK, gin.H{
  797. "success": true,
  798. "message": "",
  799. "data": clearUser,
  800. })
  801. return
  802. }
  803. func EmailBind(c *gin.Context) {
  804. email := c.Query("email")
  805. code := c.Query("code")
  806. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  807. c.JSON(http.StatusOK, gin.H{
  808. "success": false,
  809. "message": "验证码错误或已过期",
  810. })
  811. return
  812. }
  813. session := sessions.Default(c)
  814. id := session.Get("id")
  815. user := model.User{
  816. Id: id.(int),
  817. }
  818. err := user.FillUserById()
  819. if err != nil {
  820. c.JSON(http.StatusOK, gin.H{
  821. "success": false,
  822. "message": err.Error(),
  823. })
  824. return
  825. }
  826. user.Email = email
  827. // no need to check if this email already taken, because we have used verification code to check it
  828. err = user.Update(false)
  829. if err != nil {
  830. c.JSON(http.StatusOK, gin.H{
  831. "success": false,
  832. "message": err.Error(),
  833. })
  834. return
  835. }
  836. c.JSON(http.StatusOK, gin.H{
  837. "success": true,
  838. "message": "",
  839. })
  840. return
  841. }
  842. type topUpRequest struct {
  843. Key string `json:"key"`
  844. }
  845. var topUpLock = sync.Mutex{}
  846. func TopUp(c *gin.Context) {
  847. topUpLock.Lock()
  848. defer topUpLock.Unlock()
  849. req := topUpRequest{}
  850. err := c.ShouldBindJSON(&req)
  851. if err != nil {
  852. c.JSON(http.StatusOK, gin.H{
  853. "success": false,
  854. "message": err.Error(),
  855. })
  856. return
  857. }
  858. id := c.GetInt("id")
  859. quota, err := model.Redeem(req.Key, id)
  860. if err != nil {
  861. c.JSON(http.StatusOK, gin.H{
  862. "success": false,
  863. "message": err.Error(),
  864. })
  865. return
  866. }
  867. c.JSON(http.StatusOK, gin.H{
  868. "success": true,
  869. "message": "",
  870. "data": quota,
  871. })
  872. return
  873. }
  874. type UpdateUserSettingRequest struct {
  875. QuotaWarningType string `json:"notify_type"`
  876. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  877. WebhookUrl string `json:"webhook_url,omitempty"`
  878. WebhookSecret string `json:"webhook_secret,omitempty"`
  879. NotificationEmail string `json:"notification_email,omitempty"`
  880. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  881. }
  882. func UpdateUserSetting(c *gin.Context) {
  883. var req UpdateUserSettingRequest
  884. if err := c.ShouldBindJSON(&req); err != nil {
  885. c.JSON(http.StatusOK, gin.H{
  886. "success": false,
  887. "message": "无效的参数",
  888. })
  889. return
  890. }
  891. // 验证预警类型
  892. if req.QuotaWarningType != constant.NotifyTypeEmail && req.QuotaWarningType != constant.NotifyTypeWebhook {
  893. c.JSON(http.StatusOK, gin.H{
  894. "success": false,
  895. "message": "无效的预警类型",
  896. })
  897. return
  898. }
  899. // 验证预警阈值
  900. if req.QuotaWarningThreshold <= 0 {
  901. c.JSON(http.StatusOK, gin.H{
  902. "success": false,
  903. "message": "预警阈值必须大于0",
  904. })
  905. return
  906. }
  907. // 如果是webhook类型,验证webhook地址
  908. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  909. if req.WebhookUrl == "" {
  910. c.JSON(http.StatusOK, gin.H{
  911. "success": false,
  912. "message": "Webhook地址不能为空",
  913. })
  914. return
  915. }
  916. // 验证URL格式
  917. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  918. c.JSON(http.StatusOK, gin.H{
  919. "success": false,
  920. "message": "无效的Webhook地址",
  921. })
  922. return
  923. }
  924. }
  925. // 如果是邮件类型,验证邮箱地址
  926. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  927. // 验证邮箱格式
  928. if !strings.Contains(req.NotificationEmail, "@") {
  929. c.JSON(http.StatusOK, gin.H{
  930. "success": false,
  931. "message": "无效的邮箱地址",
  932. })
  933. return
  934. }
  935. }
  936. userId := c.GetInt("id")
  937. user, err := model.GetUserById(userId, true)
  938. if err != nil {
  939. c.JSON(http.StatusOK, gin.H{
  940. "success": false,
  941. "message": err.Error(),
  942. })
  943. return
  944. }
  945. // 构建设置
  946. settings := map[string]interface{}{
  947. constant.UserSettingNotifyType: req.QuotaWarningType,
  948. constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold,
  949. "accept_unset_model_ratio_model": req.AcceptUnsetModelRatioModel,
  950. }
  951. // 如果是webhook类型,添加webhook相关设置
  952. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  953. settings[constant.UserSettingWebhookUrl] = req.WebhookUrl
  954. if req.WebhookSecret != "" {
  955. settings[constant.UserSettingWebhookSecret] = req.WebhookSecret
  956. }
  957. }
  958. // 如果提供了通知邮箱,添加到设置中
  959. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  960. settings[constant.UserSettingNotificationEmail] = req.NotificationEmail
  961. }
  962. // 更新用户设置
  963. user.SetSetting(settings)
  964. if err := user.Update(false); err != nil {
  965. c.JSON(http.StatusOK, gin.H{
  966. "success": false,
  967. "message": "更新设置失败: " + err.Error(),
  968. })
  969. return
  970. }
  971. c.JSON(http.StatusOK, gin.H{
  972. "success": true,
  973. "message": "设置已更新",
  974. })
  975. }