user.go 15 KB

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