user.go 15 KB

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