auth.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "time"
  7. //"strings"
  8. "github.com/go-kit/kit/endpoint"
  9. )
  10. type jwtKey string
  11. const (
  12. // JWTToken jwt access token
  13. JWTToken jwtKey = `jwt_access_token`
  14. )
  15. func checkAuth(accessToken AccessToken) (CacheAccessToken, error) {
  16. var (
  17. id, uid []byte
  18. err error
  19. token CacheAccessToken
  20. )
  21. id, err = base64.StdEncoding.DecodeString(accessToken.ID)
  22. if err != nil {
  23. return token, err
  24. }
  25. aes := NewAesCrypto()
  26. uid, err = aes.Decrypt(id)
  27. if err != nil {
  28. return token, err
  29. }
  30. token, err = AccessTokenGetCache(string(uid))
  31. t := time.Now()
  32. if token.Expires <= t.Unix() {
  33. err = errors.New(`Authentication information expired`)
  34. }
  35. return token, err
  36. }
  37. // AuthMiddleware auth
  38. func AuthMiddleware() endpoint.Middleware {
  39. return func(next endpoint.Endpoint) endpoint.Endpoint {
  40. return func(
  41. ctx context.Context,
  42. request interface{}) (interface{}, error) {
  43. if token, ok := ctx.Value(ContextKeyAccessToken).(string); ok {
  44. var (
  45. tok AccessToken
  46. ctoken CacheAccessToken
  47. err error
  48. )
  49. if token == "" {
  50. return NewReplyData(ErrUnAuthorized), nil
  51. }
  52. if tok, err = ParseAccessToken(token); err != nil {
  53. return ErrReplyData(ErrUnAuthorized, err.Error()), nil
  54. }
  55. if ctoken, err = checkAuth(tok); err != nil {
  56. return ErrReplyData(ErrUnAuthorized, err.Error()), nil
  57. }
  58. ctx = context.WithValue(ctx, JWTToken, ctoken)
  59. return next(ctx, request)
  60. }
  61. return NewReplyData(ErrUnAuthorized), nil
  62. }
  63. }
  64. }