面包店
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.0 KiB

9 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package svc
  2. import (
  3. "applet/app/admin/lib/auth"
  4. "applet/app/db"
  5. "applet/app/db/model"
  6. "errors"
  7. "github.com/gin-gonic/gin"
  8. "strings"
  9. )
  10. func GetUser(c *gin.Context) *model.Admin {
  11. user, _ := c.Get("admin")
  12. if user == nil {
  13. return &model.Admin{
  14. AdmId: 0,
  15. Username: "",
  16. Password: "",
  17. State: 0,
  18. CreateAt: "",
  19. UpdateAt: "",
  20. }
  21. }
  22. return user.(*model.Admin)
  23. }
  24. func CheckUser(c *gin.Context) (*model.Admin, 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 := auth.ParseToken(parts[1])
  36. if err != nil {
  37. return nil, err
  38. }
  39. // 获取admin
  40. adminDb := db.AdminDb{}
  41. adminDb.Set()
  42. admin, err := adminDb.GetAdmin(mc.AdmId)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return admin, nil
  47. }