user.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. LarkWebhookURL: user.LarkWebhookURL,
  397. LarkWebhookSecret: user.LarkWebhookSecret,
  398. DingWebhookURL: user.DingWebhookURL,
  399. DingWebhookSecret: user.DingWebhookSecret,
  400. }
  401. channel.TokenStoreUpdateUser(&cleanUser, originUser)
  402. if user.Password == "$I_LOVE_U" {
  403. user.Password = "" // rollback to what it should be
  404. cleanUser.Password = ""
  405. }
  406. updatePassword := user.Password != ""
  407. if err := cleanUser.Update(updatePassword); err != nil {
  408. c.JSON(http.StatusOK, gin.H{
  409. "success": false,
  410. "message": err.Error(),
  411. })
  412. return
  413. }
  414. c.JSON(http.StatusOK, gin.H{
  415. "success": true,
  416. "message": "",
  417. })
  418. return
  419. }
  420. func DeleteUser(c *gin.Context) {
  421. id, err := strconv.Atoi(c.Param("id"))
  422. if err != nil {
  423. c.JSON(http.StatusOK, gin.H{
  424. "success": false,
  425. "message": err.Error(),
  426. })
  427. return
  428. }
  429. originUser, err := model.GetUserById(id, false)
  430. if err != nil {
  431. c.JSON(http.StatusOK, gin.H{
  432. "success": false,
  433. "message": err.Error(),
  434. })
  435. return
  436. }
  437. myRole := c.GetInt("role")
  438. if myRole <= originUser.Role {
  439. c.JSON(http.StatusOK, gin.H{
  440. "success": false,
  441. "message": "无权删除同权限等级或更高权限等级的用户",
  442. })
  443. return
  444. }
  445. channel.TokenStoreRemoveUser(originUser)
  446. err = model.DeleteUserById(id)
  447. if err != nil {
  448. c.JSON(http.StatusOK, gin.H{
  449. "success": true,
  450. "message": "",
  451. })
  452. return
  453. }
  454. }
  455. func DeleteSelf(c *gin.Context) {
  456. id := c.GetInt("id")
  457. user := model.User{Id: id}
  458. user.FillUserById()
  459. channel.TokenStoreRemoveUser(&user)
  460. err := model.DeleteUserById(id)
  461. if err != nil {
  462. c.JSON(http.StatusOK, gin.H{
  463. "success": false,
  464. "message": err.Error(),
  465. })
  466. return
  467. }
  468. c.JSON(http.StatusOK, gin.H{
  469. "success": true,
  470. "message": "",
  471. })
  472. return
  473. }
  474. func CreateUser(c *gin.Context) {
  475. var user model.User
  476. err := json.NewDecoder(c.Request.Body).Decode(&user)
  477. if err != nil || user.Username == "" || user.Password == "" {
  478. c.JSON(http.StatusOK, gin.H{
  479. "success": false,
  480. "message": "无效的参数",
  481. })
  482. return
  483. }
  484. if user.DisplayName == "" {
  485. user.DisplayName = user.Username
  486. }
  487. myRole := c.GetInt("role")
  488. if user.Role >= myRole {
  489. c.JSON(http.StatusOK, gin.H{
  490. "success": false,
  491. "message": "无法创建权限大于等于自己的用户",
  492. })
  493. return
  494. }
  495. // Even for admin users, we cannot fully trust them!
  496. cleanUser := model.User{
  497. Username: user.Username,
  498. Password: user.Password,
  499. DisplayName: user.DisplayName,
  500. }
  501. if err := cleanUser.Insert(); err != nil {
  502. c.JSON(http.StatusOK, gin.H{
  503. "success": false,
  504. "message": err.Error(),
  505. })
  506. return
  507. }
  508. c.JSON(http.StatusOK, gin.H{
  509. "success": true,
  510. "message": "",
  511. })
  512. return
  513. }
  514. type ManageRequest struct {
  515. Username string `json:"username"`
  516. Action string `json:"action"`
  517. }
  518. // ManageUser Only admin user can do this
  519. func ManageUser(c *gin.Context) {
  520. var req ManageRequest
  521. err := json.NewDecoder(c.Request.Body).Decode(&req)
  522. if err != nil {
  523. c.JSON(http.StatusOK, gin.H{
  524. "success": false,
  525. "message": "无效的参数",
  526. })
  527. return
  528. }
  529. user := model.User{
  530. Username: req.Username,
  531. }
  532. // Fill attributes
  533. model.DB.Where(&user).First(&user)
  534. if user.Id == 0 {
  535. c.JSON(http.StatusOK, gin.H{
  536. "success": false,
  537. "message": "用户不存在",
  538. })
  539. return
  540. }
  541. myRole := c.GetInt("role")
  542. if myRole <= user.Role {
  543. c.JSON(http.StatusOK, gin.H{
  544. "success": false,
  545. "message": "无权更新同权限等级或更高权限等级的用户信息",
  546. })
  547. return
  548. }
  549. switch req.Action {
  550. case "disable":
  551. user.Status = common.UserStatusDisabled
  552. case "enable":
  553. user.Status = common.UserStatusEnabled
  554. case "delete":
  555. if err := user.Delete(); err != nil {
  556. c.JSON(http.StatusOK, gin.H{
  557. "success": false,
  558. "message": err.Error(),
  559. })
  560. return
  561. }
  562. case "promote":
  563. if myRole != common.RoleRootUser {
  564. c.JSON(http.StatusOK, gin.H{
  565. "success": false,
  566. "message": "普通管理员用户无法提升其他用户为管理员",
  567. })
  568. return
  569. }
  570. user.Role = common.RoleAdminUser
  571. case "demote":
  572. user.Role = common.RoleCommonUser
  573. }
  574. if err := user.Update(false); err != nil {
  575. c.JSON(http.StatusOK, gin.H{
  576. "success": false,
  577. "message": err.Error(),
  578. })
  579. return
  580. }
  581. clearUser := model.User{
  582. Role: user.Role,
  583. Status: user.Status,
  584. }
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": true,
  587. "message": "",
  588. "data": clearUser,
  589. })
  590. return
  591. }
  592. func EmailBind(c *gin.Context) {
  593. email := c.Query("email")
  594. code := c.Query("code")
  595. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  596. c.JSON(http.StatusOK, gin.H{
  597. "success": false,
  598. "message": "验证码错误或已过期",
  599. })
  600. return
  601. }
  602. id := c.GetInt("id")
  603. user := model.User{
  604. Id: id,
  605. }
  606. user.FillUserById()
  607. user.Email = email
  608. // no need to check if this email already taken, because we have used verification code to check it
  609. err := user.Update(false)
  610. if err != nil {
  611. c.JSON(http.StatusOK, gin.H{
  612. "success": false,
  613. "message": err.Error(),
  614. })
  615. return
  616. }
  617. c.JSON(http.StatusOK, gin.H{
  618. "success": true,
  619. "message": "",
  620. })
  621. return
  622. }