user.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. RecordIpLog bool `json:"record_ip_log"`
  905. }
  906. func UpdateUserSetting(c *gin.Context) {
  907. var req UpdateUserSettingRequest
  908. if err := c.ShouldBindJSON(&req); err != nil {
  909. c.JSON(http.StatusOK, gin.H{
  910. "success": false,
  911. "message": "无效的参数",
  912. })
  913. return
  914. }
  915. // 验证预警类型
  916. if req.QuotaWarningType != constant.NotifyTypeEmail && req.QuotaWarningType != constant.NotifyTypeWebhook {
  917. c.JSON(http.StatusOK, gin.H{
  918. "success": false,
  919. "message": "无效的预警类型",
  920. })
  921. return
  922. }
  923. // 验证预警阈值
  924. if req.QuotaWarningThreshold <= 0 {
  925. c.JSON(http.StatusOK, gin.H{
  926. "success": false,
  927. "message": "预警阈值必须大于0",
  928. })
  929. return
  930. }
  931. // 如果是webhook类型,验证webhook地址
  932. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  933. if req.WebhookUrl == "" {
  934. c.JSON(http.StatusOK, gin.H{
  935. "success": false,
  936. "message": "Webhook地址不能为空",
  937. })
  938. return
  939. }
  940. // 验证URL格式
  941. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  942. c.JSON(http.StatusOK, gin.H{
  943. "success": false,
  944. "message": "无效的Webhook地址",
  945. })
  946. return
  947. }
  948. }
  949. // 如果是邮件类型,验证邮箱地址
  950. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  951. // 验证邮箱格式
  952. if !strings.Contains(req.NotificationEmail, "@") {
  953. c.JSON(http.StatusOK, gin.H{
  954. "success": false,
  955. "message": "无效的邮箱地址",
  956. })
  957. return
  958. }
  959. }
  960. userId := c.GetInt("id")
  961. user, err := model.GetUserById(userId, true)
  962. if err != nil {
  963. c.JSON(http.StatusOK, gin.H{
  964. "success": false,
  965. "message": err.Error(),
  966. })
  967. return
  968. }
  969. // 构建设置
  970. settings := map[string]interface{}{
  971. constant.UserSettingNotifyType: req.QuotaWarningType,
  972. constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold,
  973. "accept_unset_model_ratio_model": req.AcceptUnsetModelRatioModel,
  974. constant.UserSettingRecordIpLog: req.RecordIpLog,
  975. }
  976. // 如果是webhook类型,添加webhook相关设置
  977. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  978. settings[constant.UserSettingWebhookUrl] = req.WebhookUrl
  979. if req.WebhookSecret != "" {
  980. settings[constant.UserSettingWebhookSecret] = req.WebhookSecret
  981. }
  982. }
  983. // 如果提供了通知邮箱,添加到设置中
  984. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  985. settings[constant.UserSettingNotificationEmail] = req.NotificationEmail
  986. }
  987. // 更新用户设置
  988. user.SetSetting(settings)
  989. if err := user.Update(false); err != nil {
  990. c.JSON(http.StatusOK, gin.H{
  991. "success": false,
  992. "message": "更新设置失败: " + err.Error(),
  993. })
  994. return
  995. }
  996. c.JSON(http.StatusOK, gin.H{
  997. "success": true,
  998. "message": "设置已更新",
  999. })
  1000. }