base_token.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package base
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. "github.com/tiger1103/gfast-token/gftoken"
  7. "golang.org/x/net/context"
  8. "nodeMonitor/internal/consts"
  9. "nodeMonitor/internal/model"
  10. "nodeMonitor/library/liberr"
  11. "sync"
  12. )
  13. type IGfToken interface {
  14. GenerateToken(ctx context.Context, key string, data interface{}) (keys string, err error)
  15. RemoveToken(ctx context.Context, token string) (err error)
  16. GetRequestToken(r *ghttp.Request) (token string)
  17. Middleware(group *ghttp.RouterGroup) error
  18. ParseToken(r *ghttp.Request) (*gftoken.CustomClaims, error)
  19. IsLogin(r *ghttp.Request) (b bool, failed *gftoken.AuthFailed)
  20. }
  21. type gfTokenImpl struct {
  22. *gftoken.GfToken
  23. }
  24. var gT = gfTokenImpl{
  25. GfToken: gftoken.NewGfToken(),
  26. }
  27. func NewGfToken(options *model.TokenOptions) IGfToken {
  28. var fun gftoken.OptionFunc
  29. if options.CacheModel == consts.CacheModelRedis {
  30. fun = gftoken.WithGRedis()
  31. } else {
  32. fun = gftoken.WithGCache()
  33. }
  34. gT.GfToken = gftoken.NewGfToken(
  35. gftoken.WithCacheKey(options.CacheKey),
  36. gftoken.WithTimeout(options.Timeout),
  37. gftoken.WithMaxRefresh(options.MaxRefresh),
  38. gftoken.WithMultiLogin(options.MultiLogin),
  39. gftoken.WithExcludePaths(options.ExcludePaths),
  40. fun,
  41. )
  42. return IGfToken(&gT)
  43. }
  44. type gft struct {
  45. options *model.TokenOptions
  46. gT IGfToken
  47. lock *sync.Mutex
  48. }
  49. var gftService = &gft{
  50. options: nil,
  51. gT: nil,
  52. lock: &sync.Mutex{},
  53. }
  54. func GfToken() IGfToken {
  55. if gftService.gT == nil {
  56. gftService.lock.Lock()
  57. defer gftService.lock.Unlock()
  58. if gftService.gT == nil {
  59. ctx := gctx.New()
  60. err := g.Cfg().MustGet(ctx, "gfToken").Struct(&gftService.options)
  61. liberr.ErrIsNil(ctx, err)
  62. gftService.gT = NewGfToken(gftService.options)
  63. }
  64. }
  65. return gftService.gT
  66. }