user.go 20 KB

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