附近小店
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

svc_auth.go 1.5 KiB

3 kuukautta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package svc
  2. import (
  3. "applet/app/db"
  4. "applet/app/md"
  5. "applet/app/utils"
  6. "errors"
  7. "github.com/gin-gonic/gin"
  8. "strings"
  9. )
  10. // 因为在mw_auth已经做完所有校验, 因此在此不再做任何校验
  11. // GetUser is get user model
  12. func GetUser(c *gin.Context) *md.User {
  13. user, _ := c.Get("user")
  14. if user == nil {
  15. return nil
  16. }
  17. return user.(*md.User)
  18. }
  19. func GetUid(c *gin.Context) string {
  20. user, _ := c.Get("user")
  21. u := user.(*md.User)
  22. return utils.IntToStr(u.Info.Uid)
  23. }
  24. func CheckUser(c *gin.Context) (*md.User, error) {
  25. token := c.GetHeader("Authorization")
  26. if token == "" {
  27. return nil, errors.New("token not exist")
  28. }
  29. // 按空格分割
  30. parts := strings.SplitN(token, " ", 2)
  31. if !(len(parts) == 2 && parts[0] == "Bearer") {
  32. return nil, errors.New("token format error")
  33. }
  34. // parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
  35. mc, err := utils.ParseToken(parts[1])
  36. if err != nil {
  37. return nil, err
  38. }
  39. // 获取user
  40. u, err := db.UserFindByID(db.DBs[c.GetString("mid")], mc.UID)
  41. if err != nil {
  42. return nil, err
  43. }
  44. if u == nil {
  45. return nil, errors.New("token can not find user")
  46. }
  47. // 获取user profile
  48. up, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], mc.UID)
  49. if err != nil {
  50. return nil, err
  51. }
  52. // 获取user 等级
  53. ul, err := db.UserLevelByID(db.DBs[c.GetString("mid")], u.Level)
  54. if err != nil {
  55. return nil, err
  56. }
  57. user := &md.User{
  58. Info: u,
  59. Profile: up,
  60. Level: ul,
  61. }
  62. return user, nil
  63. }