智慧食堂-队列消费项目
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.1 KiB

2 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package svc
  2. import (
  3. "applet/app/customer/lib/auth"
  4. "applet/app/db"
  5. "applet/app/db/model"
  6. "errors"
  7. "github.com/gin-gonic/gin"
  8. "strings"
  9. "time"
  10. )
  11. func GetUser(c *gin.Context) *model.User {
  12. user, _ := c.Get("user")
  13. if user == nil {
  14. return &model.User{
  15. Id: 0,
  16. UserId: "",
  17. Nickname: "",
  18. Avatar: "",
  19. Phone: "",
  20. Memo: "",
  21. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  22. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  23. }
  24. }
  25. return user.(*model.User)
  26. }
  27. func CheckUser(c *gin.Context) (*model.User, error) {
  28. token := c.GetHeader("Authorization")
  29. if token == "" {
  30. return nil, errors.New("token not exist")
  31. }
  32. // 按空格分割
  33. parts := strings.SplitN(token, " ", 2)
  34. if !(len(parts) == 2 && parts[0] == "Bearer") {
  35. return nil, errors.New("token format error")
  36. }
  37. // parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
  38. mc, err := auth.ParseToken(parts[1])
  39. if err != nil {
  40. return nil, err
  41. }
  42. // 获取user
  43. userDb := db.UserDb{}
  44. userDb.Set()
  45. user, err := userDb.GetUser(mc.UserId)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return user, nil
  50. }