user.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gin-contrib/sessions"
  6. "github.com/gin-gonic/gin"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/model"
  10. "strconv"
  11. )
  12. type LoginRequest struct {
  13. Username string `json:"username"`
  14. Password string `json:"password"`
  15. }
  16. func Login(c *gin.Context) {
  17. if !common.PasswordLoginEnabled {
  18. c.JSON(http.StatusOK, gin.H{
  19. "message": "管理员关闭了密码登录",
  20. "success": false,
  21. })
  22. return
  23. }
  24. var loginRequest LoginRequest
  25. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  26. if err != nil {
  27. c.JSON(http.StatusOK, gin.H{
  28. "message": "无效的参数",
  29. "success": false,
  30. })
  31. return
  32. }
  33. username := loginRequest.Username
  34. password := loginRequest.Password
  35. if username == "" || password == "" {
  36. c.JSON(http.StatusOK, gin.H{
  37. "message": "无效的参数",
  38. "success": false,
  39. })
  40. return
  41. }
  42. user := model.User{
  43. Username: username,
  44. Password: password,
  45. }
  46. err = user.ValidateAndFill()
  47. if err != nil {
  48. c.JSON(http.StatusOK, gin.H{
  49. "message": err.Error(),
  50. "success": false,
  51. })
  52. return
  53. }
  54. setupLogin(&user, c)
  55. }
  56. // setup session & cookies and then return user info
  57. func setupLogin(user *model.User, c *gin.Context) {
  58. session := sessions.Default(c)
  59. session.Set("id", user.Id)
  60. session.Set("username", user.Username)
  61. session.Set("role", user.Role)
  62. session.Set("status", user.Status)
  63. err := session.Save()
  64. if err != nil {
  65. c.JSON(http.StatusOK, gin.H{
  66. "message": "无法保存会话信息,请重试",
  67. "success": false,
  68. })
  69. return
  70. }
  71. cleanUser := model.User{
  72. Id: user.Id,
  73. Username: user.Username,
  74. DisplayName: user.DisplayName,
  75. Role: user.Role,
  76. Status: user.Status,
  77. }
  78. c.JSON(http.StatusOK, gin.H{
  79. "message": "",
  80. "success": true,
  81. "data": cleanUser,
  82. })
  83. }
  84. func Logout(c *gin.Context) {
  85. session := sessions.Default(c)
  86. session.Clear()
  87. err := session.Save()
  88. if err != nil {
  89. c.JSON(http.StatusOK, gin.H{
  90. "message": err.Error(),
  91. "success": false,
  92. })
  93. return
  94. }
  95. c.JSON(http.StatusOK, gin.H{
  96. "message": "",
  97. "success": true,
  98. })
  99. }
  100. func Register(c *gin.Context) {
  101. if !common.RegisterEnabled {
  102. c.JSON(http.StatusOK, gin.H{
  103. "message": "管理员关闭了新用户注册",
  104. "success": false,
  105. })
  106. return
  107. }
  108. if !common.PasswordRegisterEnabled {
  109. c.JSON(http.StatusOK, gin.H{
  110. "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
  111. "success": false,
  112. })
  113. return
  114. }
  115. var user model.User
  116. err := json.NewDecoder(c.Request.Body).Decode(&user)
  117. if err != nil {
  118. c.JSON(http.StatusOK, gin.H{
  119. "success": false,
  120. "message": "无效的参数",
  121. })
  122. return
  123. }
  124. if err := common.Validate.Struct(&user); err != nil {
  125. c.JSON(http.StatusOK, gin.H{
  126. "success": false,
  127. "message": "输入不合法 " + err.Error(),
  128. })
  129. return
  130. }
  131. if common.EmailVerificationEnabled {
  132. if user.Email == "" || user.VerificationCode == "" {
  133. c.JSON(http.StatusOK, gin.H{
  134. "success": false,
  135. "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
  136. })
  137. return
  138. }
  139. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  140. c.JSON(http.StatusOK, gin.H{
  141. "success": false,
  142. "message": "验证码错误或已过期",
  143. })
  144. return
  145. }
  146. }
  147. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  148. inviterId, _ := model.GetUserIdByAffCode(affCode)
  149. cleanUser := model.User{
  150. Username: user.Username,
  151. Password: user.Password,
  152. DisplayName: user.Username,
  153. InviterId: inviterId,
  154. }
  155. if common.EmailVerificationEnabled {
  156. cleanUser.Email = user.Email
  157. }
  158. if err := cleanUser.Insert(inviterId); err != nil {
  159. c.JSON(http.StatusOK, gin.H{
  160. "success": false,
  161. "message": err.Error(),
  162. })
  163. return
  164. }
  165. c.JSON(http.StatusOK, gin.H{
  166. "success": true,
  167. "message": "",
  168. })
  169. return
  170. }
  171. func GetAllUsers(c *gin.Context) {
  172. p, _ := strconv.Atoi(c.Query("p"))
  173. if p < 0 {
  174. p = 0
  175. }
  176. users, err := model.GetAllUsers(p*common.ItemsPerPage, common.ItemsPerPage)
  177. if err != nil {
  178. c.JSON(http.StatusOK, gin.H{
  179. "success": false,
  180. "message": err.Error(),
  181. })
  182. return
  183. }
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": true,
  186. "message": "",
  187. "data": users,
  188. })
  189. return
  190. }
  191. func SearchUsers(c *gin.Context) {
  192. keyword := c.Query("keyword")
  193. users, err := model.SearchUsers(keyword)
  194. if err != nil {
  195. c.JSON(http.StatusOK, gin.H{
  196. "success": false,
  197. "message": err.Error(),
  198. })
  199. return
  200. }
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": true,
  203. "message": "",
  204. "data": users,
  205. })
  206. return
  207. }
  208. func GetUser(c *gin.Context) {
  209. id, err := strconv.Atoi(c.Param("id"))
  210. if err != nil {
  211. c.JSON(http.StatusOK, gin.H{
  212. "success": false,
  213. "message": err.Error(),
  214. })
  215. return
  216. }
  217. user, err := model.GetUserById(id, false)
  218. if err != nil {
  219. c.JSON(http.StatusOK, gin.H{
  220. "success": false,
  221. "message": err.Error(),
  222. })
  223. return
  224. }
  225. myRole := c.GetInt("role")
  226. if myRole <= user.Role && myRole != common.RoleRootUser {
  227. c.JSON(http.StatusOK, gin.H{
  228. "success": false,
  229. "message": "无权获取同级或更高等级用户的信息",
  230. })
  231. return
  232. }
  233. c.JSON(http.StatusOK, gin.H{
  234. "success": true,
  235. "message": "",
  236. "data": user,
  237. })
  238. return
  239. }
  240. func GenerateAccessToken(c *gin.Context) {
  241. id := c.GetInt("id")
  242. user, err := model.GetUserById(id, true)
  243. if err != nil {
  244. c.JSON(http.StatusOK, gin.H{
  245. "success": false,
  246. "message": err.Error(),
  247. })
  248. return
  249. }
  250. user.AccessToken = common.GetUUID()
  251. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  252. c.JSON(http.StatusOK, gin.H{
  253. "success": false,
  254. "message": "请重试,系统生成的 UUID 竟然重复了!",
  255. })
  256. return
  257. }
  258. if err := user.Update(false); err != nil {
  259. c.JSON(http.StatusOK, gin.H{
  260. "success": false,
  261. "message": err.Error(),
  262. })
  263. return
  264. }
  265. c.JSON(http.StatusOK, gin.H{
  266. "success": true,
  267. "message": "",
  268. "data": user.AccessToken,
  269. })
  270. return
  271. }
  272. func GetAffCode(c *gin.Context) {
  273. id := c.GetInt("id")
  274. user, err := model.GetUserById(id, true)
  275. if err != nil {
  276. c.JSON(http.StatusOK, gin.H{
  277. "success": false,
  278. "message": err.Error(),
  279. })
  280. return
  281. }
  282. if user.AffCode == "" {
  283. user.AffCode = common.GetRandomString(4)
  284. if err := user.Update(false); err != nil {
  285. c.JSON(http.StatusOK, gin.H{
  286. "success": false,
  287. "message": err.Error(),
  288. })
  289. return
  290. }
  291. }
  292. c.JSON(http.StatusOK, gin.H{
  293. "success": true,
  294. "message": "",
  295. "data": user.AffCode,
  296. })
  297. return
  298. }
  299. func GetSelf(c *gin.Context) {
  300. id := c.GetInt("id")
  301. user, err := model.GetUserById(id, false)
  302. if err != nil {
  303. c.JSON(http.StatusOK, gin.H{
  304. "success": false,
  305. "message": err.Error(),
  306. })
  307. return
  308. }
  309. c.JSON(http.StatusOK, gin.H{
  310. "success": true,
  311. "message": "",
  312. "data": user,
  313. })
  314. return
  315. }
  316. func UpdateUser(c *gin.Context) {
  317. var updatedUser model.User
  318. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  319. if err != nil || updatedUser.Id == 0 {
  320. c.JSON(http.StatusOK, gin.H{
  321. "success": false,
  322. "message": "无效的参数",
  323. })
  324. return
  325. }
  326. if updatedUser.Password == "" {
  327. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  328. }
  329. if err := common.Validate.Struct(&updatedUser); err != nil {
  330. c.JSON(http.StatusOK, gin.H{
  331. "success": false,
  332. "message": "输入不合法 " + err.Error(),
  333. })
  334. return
  335. }
  336. originUser, err := model.GetUserById(updatedUser.Id, false)
  337. if err != nil {
  338. c.JSON(http.StatusOK, gin.H{
  339. "success": false,
  340. "message": err.Error(),
  341. })
  342. return
  343. }
  344. myRole := c.GetInt("role")
  345. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  346. c.JSON(http.StatusOK, gin.H{
  347. "success": false,
  348. "message": "无权更新同权限等级或更高权限等级的用户信息",
  349. })
  350. return
  351. }
  352. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  353. c.JSON(http.StatusOK, gin.H{
  354. "success": false,
  355. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  356. })
  357. return
  358. }
  359. if updatedUser.Password == "$I_LOVE_U" {
  360. updatedUser.Password = "" // rollback to what it should be
  361. }
  362. updatePassword := updatedUser.Password != ""
  363. if err := updatedUser.Update(updatePassword); err != nil {
  364. c.JSON(http.StatusOK, gin.H{
  365. "success": false,
  366. "message": err.Error(),
  367. })
  368. return
  369. }
  370. if originUser.Quota != updatedUser.Quota {
  371. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota)))
  372. }
  373. c.JSON(http.StatusOK, gin.H{
  374. "success": true,
  375. "message": "",
  376. })
  377. return
  378. }
  379. func UpdateSelf(c *gin.Context) {
  380. var user model.User
  381. err := json.NewDecoder(c.Request.Body).Decode(&user)
  382. if err != nil {
  383. c.JSON(http.StatusOK, gin.H{
  384. "success": false,
  385. "message": "无效的参数",
  386. })
  387. return
  388. }
  389. if user.Password == "" {
  390. user.Password = "$I_LOVE_U" // make Validator happy :)
  391. }
  392. if err := common.Validate.Struct(&user); err != nil {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "输入不合法 " + err.Error(),
  396. })
  397. return
  398. }
  399. cleanUser := model.User{
  400. Id: c.GetInt("id"),
  401. Username: user.Username,
  402. Password: user.Password,
  403. DisplayName: user.DisplayName,
  404. }
  405. if user.Password == "$I_LOVE_U" {
  406. user.Password = "" // rollback to what it should be
  407. cleanUser.Password = ""
  408. }
  409. updatePassword := user.Password != ""
  410. if err := cleanUser.Update(updatePassword); err != nil {
  411. c.JSON(http.StatusOK, gin.H{
  412. "success": false,
  413. "message": err.Error(),
  414. })
  415. return
  416. }
  417. c.JSON(http.StatusOK, gin.H{
  418. "success": true,
  419. "message": "",
  420. })
  421. return
  422. }
  423. func DeleteUser(c *gin.Context) {
  424. id, err := strconv.Atoi(c.Param("id"))
  425. if err != nil {
  426. c.JSON(http.StatusOK, gin.H{
  427. "success": false,
  428. "message": err.Error(),
  429. })
  430. return
  431. }
  432. originUser, 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. myRole := c.GetInt("role")
  441. if myRole <= originUser.Role {
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": false,
  444. "message": "无权删除同权限等级或更高权限等级的用户",
  445. })
  446. return
  447. }
  448. err = model.DeleteUserById(id)
  449. if err != nil {
  450. c.JSON(http.StatusOK, gin.H{
  451. "success": true,
  452. "message": "",
  453. })
  454. return
  455. }
  456. }
  457. func DeleteSelf(c *gin.Context) {
  458. id := c.GetInt("id")
  459. err := model.DeleteUserById(id)
  460. if err != nil {
  461. c.JSON(http.StatusOK, gin.H{
  462. "success": false,
  463. "message": err.Error(),
  464. })
  465. return
  466. }
  467. c.JSON(http.StatusOK, gin.H{
  468. "success": true,
  469. "message": "",
  470. })
  471. return
  472. }
  473. func CreateUser(c *gin.Context) {
  474. var user model.User
  475. err := json.NewDecoder(c.Request.Body).Decode(&user)
  476. if err != nil || user.Username == "" || user.Password == "" {
  477. c.JSON(http.StatusOK, gin.H{
  478. "success": false,
  479. "message": "无效的参数",
  480. })
  481. return
  482. }
  483. if err := common.Validate.Struct(&user); err != nil {
  484. c.JSON(http.StatusOK, gin.H{
  485. "success": false,
  486. "message": "输入不合法 " + err.Error(),
  487. })
  488. return
  489. }
  490. if user.DisplayName == "" {
  491. user.DisplayName = user.Username
  492. }
  493. myRole := c.GetInt("role")
  494. if user.Role >= myRole {
  495. c.JSON(http.StatusOK, gin.H{
  496. "success": false,
  497. "message": "无法创建权限大于等于自己的用户",
  498. })
  499. return
  500. }
  501. // Even for admin users, we cannot fully trust them!
  502. cleanUser := model.User{
  503. Username: user.Username,
  504. Password: user.Password,
  505. DisplayName: user.DisplayName,
  506. }
  507. if err := cleanUser.Insert(0); err != nil {
  508. c.JSON(http.StatusOK, gin.H{
  509. "success": false,
  510. "message": err.Error(),
  511. })
  512. return
  513. }
  514. c.JSON(http.StatusOK, gin.H{
  515. "success": true,
  516. "message": "",
  517. })
  518. return
  519. }
  520. type ManageRequest struct {
  521. Username string `json:"username"`
  522. Action string `json:"action"`
  523. }
  524. // ManageUser Only admin user can do this
  525. func ManageUser(c *gin.Context) {
  526. var req ManageRequest
  527. err := json.NewDecoder(c.Request.Body).Decode(&req)
  528. if err != nil {
  529. c.JSON(http.StatusOK, gin.H{
  530. "success": false,
  531. "message": "无效的参数",
  532. })
  533. return
  534. }
  535. user := model.User{
  536. Username: req.Username,
  537. }
  538. // Fill attributes
  539. model.DB.Where(&user).First(&user)
  540. if user.Id == 0 {
  541. c.JSON(http.StatusOK, gin.H{
  542. "success": false,
  543. "message": "用户不存在",
  544. })
  545. return
  546. }
  547. myRole := c.GetInt("role")
  548. if myRole <= user.Role && myRole != common.RoleRootUser {
  549. c.JSON(http.StatusOK, gin.H{
  550. "success": false,
  551. "message": "无权更新同权限等级或更高权限等级的用户信息",
  552. })
  553. return
  554. }
  555. switch req.Action {
  556. case "disable":
  557. user.Status = common.UserStatusDisabled
  558. if user.Role == common.RoleRootUser {
  559. c.JSON(http.StatusOK, gin.H{
  560. "success": false,
  561. "message": "无法禁用超级管理员用户",
  562. })
  563. return
  564. }
  565. case "enable":
  566. user.Status = common.UserStatusEnabled
  567. case "delete":
  568. if user.Role == common.RoleRootUser {
  569. c.JSON(http.StatusOK, gin.H{
  570. "success": false,
  571. "message": "无法删除超级管理员用户",
  572. })
  573. return
  574. }
  575. if err := user.Delete(); err != nil {
  576. c.JSON(http.StatusOK, gin.H{
  577. "success": false,
  578. "message": err.Error(),
  579. })
  580. return
  581. }
  582. case "promote":
  583. if myRole != common.RoleRootUser {
  584. c.JSON(http.StatusOK, gin.H{
  585. "success": false,
  586. "message": "普通管理员用户无法提升其他用户为管理员",
  587. })
  588. return
  589. }
  590. if user.Role >= common.RoleAdminUser {
  591. c.JSON(http.StatusOK, gin.H{
  592. "success": false,
  593. "message": "该用户已经是管理员",
  594. })
  595. return
  596. }
  597. user.Role = common.RoleAdminUser
  598. case "demote":
  599. if user.Role == common.RoleRootUser {
  600. c.JSON(http.StatusOK, gin.H{
  601. "success": false,
  602. "message": "无法降级超级管理员用户",
  603. })
  604. return
  605. }
  606. if user.Role == common.RoleCommonUser {
  607. c.JSON(http.StatusOK, gin.H{
  608. "success": false,
  609. "message": "该用户已经是普通用户",
  610. })
  611. return
  612. }
  613. user.Role = common.RoleCommonUser
  614. }
  615. if err := user.Update(false); err != nil {
  616. c.JSON(http.StatusOK, gin.H{
  617. "success": false,
  618. "message": err.Error(),
  619. })
  620. return
  621. }
  622. clearUser := model.User{
  623. Role: user.Role,
  624. Status: user.Status,
  625. }
  626. c.JSON(http.StatusOK, gin.H{
  627. "success": true,
  628. "message": "",
  629. "data": clearUser,
  630. })
  631. return
  632. }
  633. func EmailBind(c *gin.Context) {
  634. email := c.Query("email")
  635. code := c.Query("code")
  636. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  637. c.JSON(http.StatusOK, gin.H{
  638. "success": false,
  639. "message": "验证码错误或已过期",
  640. })
  641. return
  642. }
  643. id := c.GetInt("id")
  644. user := model.User{
  645. Id: id,
  646. }
  647. err := user.FillUserById()
  648. if err != nil {
  649. c.JSON(http.StatusOK, gin.H{
  650. "success": false,
  651. "message": err.Error(),
  652. })
  653. return
  654. }
  655. user.Email = email
  656. // no need to check if this email already taken, because we have used verification code to check it
  657. err = user.Update(false)
  658. if err != nil {
  659. c.JSON(http.StatusOK, gin.H{
  660. "success": false,
  661. "message": err.Error(),
  662. })
  663. return
  664. }
  665. if user.Role == common.RoleRootUser {
  666. common.RootUserEmail = email
  667. }
  668. c.JSON(http.StatusOK, gin.H{
  669. "success": true,
  670. "message": "",
  671. })
  672. return
  673. }
  674. type topUpRequest struct {
  675. Key string `json:"key"`
  676. }
  677. func TopUp(c *gin.Context) {
  678. req := topUpRequest{}
  679. err := c.ShouldBindJSON(&req)
  680. if err != nil {
  681. c.JSON(http.StatusOK, gin.H{
  682. "success": false,
  683. "message": err.Error(),
  684. })
  685. return
  686. }
  687. id := c.GetInt("id")
  688. quota, err := model.Redeem(req.Key, id)
  689. if err != nil {
  690. c.JSON(http.StatusOK, gin.H{
  691. "success": false,
  692. "message": err.Error(),
  693. })
  694. return
  695. }
  696. c.JSON(http.StatusOK, gin.H{
  697. "success": true,
  698. "message": "",
  699. "data": quota,
  700. })
  701. return
  702. }