user.go 23 KB

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