user.go 13 KB

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