user.go 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  571. if err != nil {
  572. c.JSON(http.StatusOK, gin.H{
  573. "success": false,
  574. "message": err.Error(),
  575. })
  576. return
  577. }
  578. if err := cleanUser.Update(updatePassword); err != nil {
  579. c.JSON(http.StatusOK, gin.H{
  580. "success": false,
  581. "message": err.Error(),
  582. })
  583. return
  584. }
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": true,
  587. "message": "",
  588. })
  589. return
  590. }
  591. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  592. var currentUser *model.User
  593. currentUser, err = model.GetUserById(userId, true)
  594. if err != nil {
  595. return
  596. }
  597. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) {
  598. err = fmt.Errorf("原密码错误")
  599. return
  600. }
  601. if newPassword == "" {
  602. return
  603. }
  604. updatePassword = true
  605. return
  606. }
  607. func DeleteUser(c *gin.Context) {
  608. id, err := strconv.Atoi(c.Param("id"))
  609. if err != nil {
  610. c.JSON(http.StatusOK, gin.H{
  611. "success": false,
  612. "message": err.Error(),
  613. })
  614. return
  615. }
  616. originUser, err := model.GetUserById(id, false)
  617. if err != nil {
  618. c.JSON(http.StatusOK, gin.H{
  619. "success": false,
  620. "message": err.Error(),
  621. })
  622. return
  623. }
  624. myRole := c.GetInt("role")
  625. if myRole <= originUser.Role {
  626. c.JSON(http.StatusOK, gin.H{
  627. "success": false,
  628. "message": "无权删除同权限等级或更高权限等级的用户",
  629. })
  630. return
  631. }
  632. err = model.HardDeleteUserById(id)
  633. if err != nil {
  634. c.JSON(http.StatusOK, gin.H{
  635. "success": true,
  636. "message": "",
  637. })
  638. return
  639. }
  640. }
  641. func DeleteSelf(c *gin.Context) {
  642. id := c.GetInt("id")
  643. user, _ := model.GetUserById(id, false)
  644. if user.Role == common.RoleRootUser {
  645. c.JSON(http.StatusOK, gin.H{
  646. "success": false,
  647. "message": "不能删除超级管理员账户",
  648. })
  649. return
  650. }
  651. err := model.DeleteUserById(id)
  652. if err != nil {
  653. c.JSON(http.StatusOK, gin.H{
  654. "success": false,
  655. "message": err.Error(),
  656. })
  657. return
  658. }
  659. c.JSON(http.StatusOK, gin.H{
  660. "success": true,
  661. "message": "",
  662. })
  663. return
  664. }
  665. func CreateUser(c *gin.Context) {
  666. var user model.User
  667. err := json.NewDecoder(c.Request.Body).Decode(&user)
  668. user.Username = strings.TrimSpace(user.Username)
  669. if err != nil || user.Username == "" || user.Password == "" {
  670. c.JSON(http.StatusOK, gin.H{
  671. "success": false,
  672. "message": "无效的参数",
  673. })
  674. return
  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. if user.DisplayName == "" {
  684. user.DisplayName = user.Username
  685. }
  686. myRole := c.GetInt("role")
  687. if user.Role >= myRole {
  688. c.JSON(http.StatusOK, gin.H{
  689. "success": false,
  690. "message": "无法创建权限大于等于自己的用户",
  691. })
  692. return
  693. }
  694. // Even for admin users, we cannot fully trust them!
  695. cleanUser := model.User{
  696. Username: user.Username,
  697. Password: user.Password,
  698. DisplayName: user.DisplayName,
  699. }
  700. if err := cleanUser.Insert(0); err != nil {
  701. c.JSON(http.StatusOK, gin.H{
  702. "success": false,
  703. "message": err.Error(),
  704. })
  705. return
  706. }
  707. c.JSON(http.StatusOK, gin.H{
  708. "success": true,
  709. "message": "",
  710. })
  711. return
  712. }
  713. type ManageRequest struct {
  714. Id int `json:"id"`
  715. Action string `json:"action"`
  716. }
  717. // ManageUser Only admin user can do this
  718. func ManageUser(c *gin.Context) {
  719. var req ManageRequest
  720. err := json.NewDecoder(c.Request.Body).Decode(&req)
  721. if err != nil {
  722. c.JSON(http.StatusOK, gin.H{
  723. "success": false,
  724. "message": "无效的参数",
  725. })
  726. return
  727. }
  728. user := model.User{
  729. Id: req.Id,
  730. }
  731. // Fill attributes
  732. model.DB.Unscoped().Where(&user).First(&user)
  733. if user.Id == 0 {
  734. c.JSON(http.StatusOK, gin.H{
  735. "success": false,
  736. "message": "用户不存在",
  737. })
  738. return
  739. }
  740. myRole := c.GetInt("role")
  741. if myRole <= user.Role && myRole != common.RoleRootUser {
  742. c.JSON(http.StatusOK, gin.H{
  743. "success": false,
  744. "message": "无权更新同权限等级或更高权限等级的用户信息",
  745. })
  746. return
  747. }
  748. switch req.Action {
  749. case "disable":
  750. user.Status = common.UserStatusDisabled
  751. if user.Role == common.RoleRootUser {
  752. c.JSON(http.StatusOK, gin.H{
  753. "success": false,
  754. "message": "无法禁用超级管理员用户",
  755. })
  756. return
  757. }
  758. case "enable":
  759. user.Status = common.UserStatusEnabled
  760. case "delete":
  761. if user.Role == common.RoleRootUser {
  762. c.JSON(http.StatusOK, gin.H{
  763. "success": false,
  764. "message": "无法删除超级管理员用户",
  765. })
  766. return
  767. }
  768. if err := user.Delete(); err != nil {
  769. c.JSON(http.StatusOK, gin.H{
  770. "success": false,
  771. "message": err.Error(),
  772. })
  773. return
  774. }
  775. case "promote":
  776. if myRole != common.RoleRootUser {
  777. c.JSON(http.StatusOK, gin.H{
  778. "success": false,
  779. "message": "普通管理员用户无法提升其他用户为管理员",
  780. })
  781. return
  782. }
  783. if user.Role >= common.RoleAdminUser {
  784. c.JSON(http.StatusOK, gin.H{
  785. "success": false,
  786. "message": "该用户已经是管理员",
  787. })
  788. return
  789. }
  790. user.Role = common.RoleAdminUser
  791. case "demote":
  792. if user.Role == common.RoleRootUser {
  793. c.JSON(http.StatusOK, gin.H{
  794. "success": false,
  795. "message": "无法降级超级管理员用户",
  796. })
  797. return
  798. }
  799. if user.Role == common.RoleCommonUser {
  800. c.JSON(http.StatusOK, gin.H{
  801. "success": false,
  802. "message": "该用户已经是普通用户",
  803. })
  804. return
  805. }
  806. user.Role = common.RoleCommonUser
  807. }
  808. if err := user.Update(false); err != nil {
  809. c.JSON(http.StatusOK, gin.H{
  810. "success": false,
  811. "message": err.Error(),
  812. })
  813. return
  814. }
  815. clearUser := model.User{
  816. Role: user.Role,
  817. Status: user.Status,
  818. }
  819. c.JSON(http.StatusOK, gin.H{
  820. "success": true,
  821. "message": "",
  822. "data": clearUser,
  823. })
  824. return
  825. }
  826. func EmailBind(c *gin.Context) {
  827. email := c.Query("email")
  828. code := c.Query("code")
  829. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  830. c.JSON(http.StatusOK, gin.H{
  831. "success": false,
  832. "message": "验证码错误或已过期",
  833. })
  834. return
  835. }
  836. session := sessions.Default(c)
  837. id := session.Get("id")
  838. user := model.User{
  839. Id: id.(int),
  840. }
  841. err := user.FillUserById()
  842. if err != nil {
  843. c.JSON(http.StatusOK, gin.H{
  844. "success": false,
  845. "message": err.Error(),
  846. })
  847. return
  848. }
  849. user.Email = email
  850. // no need to check if this email already taken, because we have used verification code to check it
  851. err = user.Update(false)
  852. if err != nil {
  853. c.JSON(http.StatusOK, gin.H{
  854. "success": false,
  855. "message": err.Error(),
  856. })
  857. return
  858. }
  859. c.JSON(http.StatusOK, gin.H{
  860. "success": true,
  861. "message": "",
  862. })
  863. return
  864. }
  865. type topUpRequest struct {
  866. Key string `json:"key"`
  867. }
  868. var topUpLock = sync.Mutex{}
  869. func TopUp(c *gin.Context) {
  870. topUpLock.Lock()
  871. defer topUpLock.Unlock()
  872. req := topUpRequest{}
  873. err := c.ShouldBindJSON(&req)
  874. if err != nil {
  875. c.JSON(http.StatusOK, gin.H{
  876. "success": false,
  877. "message": err.Error(),
  878. })
  879. return
  880. }
  881. id := c.GetInt("id")
  882. quota, err := model.Redeem(req.Key, id)
  883. if err != nil {
  884. c.JSON(http.StatusOK, gin.H{
  885. "success": false,
  886. "message": err.Error(),
  887. })
  888. return
  889. }
  890. c.JSON(http.StatusOK, gin.H{
  891. "success": true,
  892. "message": "",
  893. "data": quota,
  894. })
  895. return
  896. }
  897. type UpdateUserSettingRequest struct {
  898. QuotaWarningType string `json:"notify_type"`
  899. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  900. WebhookUrl string `json:"webhook_url,omitempty"`
  901. WebhookSecret string `json:"webhook_secret,omitempty"`
  902. NotificationEmail string `json:"notification_email,omitempty"`
  903. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  904. }
  905. func UpdateUserSetting(c *gin.Context) {
  906. var req UpdateUserSettingRequest
  907. if err := c.ShouldBindJSON(&req); err != nil {
  908. c.JSON(http.StatusOK, gin.H{
  909. "success": false,
  910. "message": "无效的参数",
  911. })
  912. return
  913. }
  914. // 验证预警类型
  915. if req.QuotaWarningType != constant.NotifyTypeEmail && req.QuotaWarningType != constant.NotifyTypeWebhook {
  916. c.JSON(http.StatusOK, gin.H{
  917. "success": false,
  918. "message": "无效的预警类型",
  919. })
  920. return
  921. }
  922. // 验证预警阈值
  923. if req.QuotaWarningThreshold <= 0 {
  924. c.JSON(http.StatusOK, gin.H{
  925. "success": false,
  926. "message": "预警阈值必须大于0",
  927. })
  928. return
  929. }
  930. // 如果是webhook类型,验证webhook地址
  931. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  932. if req.WebhookUrl == "" {
  933. c.JSON(http.StatusOK, gin.H{
  934. "success": false,
  935. "message": "Webhook地址不能为空",
  936. })
  937. return
  938. }
  939. // 验证URL格式
  940. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  941. c.JSON(http.StatusOK, gin.H{
  942. "success": false,
  943. "message": "无效的Webhook地址",
  944. })
  945. return
  946. }
  947. }
  948. // 如果是邮件类型,验证邮箱地址
  949. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  950. // 验证邮箱格式
  951. if !strings.Contains(req.NotificationEmail, "@") {
  952. c.JSON(http.StatusOK, gin.H{
  953. "success": false,
  954. "message": "无效的邮箱地址",
  955. })
  956. return
  957. }
  958. }
  959. userId := c.GetInt("id")
  960. user, err := model.GetUserById(userId, true)
  961. if err != nil {
  962. c.JSON(http.StatusOK, gin.H{
  963. "success": false,
  964. "message": err.Error(),
  965. })
  966. return
  967. }
  968. // 构建设置
  969. settings := map[string]interface{}{
  970. constant.UserSettingNotifyType: req.QuotaWarningType,
  971. constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold,
  972. "accept_unset_model_ratio_model": req.AcceptUnsetModelRatioModel,
  973. }
  974. // 如果是webhook类型,添加webhook相关设置
  975. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  976. settings[constant.UserSettingWebhookUrl] = req.WebhookUrl
  977. if req.WebhookSecret != "" {
  978. settings[constant.UserSettingWebhookSecret] = req.WebhookSecret
  979. }
  980. }
  981. // 如果提供了通知邮箱,添加到设置中
  982. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  983. settings[constant.UserSettingNotificationEmail] = req.NotificationEmail
  984. }
  985. // 更新用户设置
  986. user.SetSetting(settings)
  987. if err := user.Update(false); err != nil {
  988. c.JSON(http.StatusOK, gin.H{
  989. "success": false,
  990. "message": "更新设置失败: " + err.Error(),
  991. })
  992. return
  993. }
  994. c.JSON(http.StatusOK, gin.H{
  995. "success": true,
  996. "message": "设置已更新",
  997. })
  998. }