authorization.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package authorization
  2. import (
  3. "strings"
  4. "time"
  5. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  6. context "github.com/kataras/iris/v12/context"
  7. "github.com/pascaldekloe/jwt"
  8. )
  9. var (
  10. SECRET = []byte{}
  11. PREFIX_AUTHORIZATION_TOKEN = "Bearer "
  12. )
  13. type JwtChk func(ctx context.Context, resourceID string, claims *jwt.Claims) (err *errs.Error)
  14. func Handler(resource string, fn JwtChk) func(ctx context.Context) (resp interface{}, err *errs.Error) {
  15. return func(ctx context.Context) (resp interface{}, err *errs.Error) {
  16. var (
  17. claims *jwt.Claims
  18. )
  19. if claims, err = ParseToken(ctx.GetHeader("Authorization")); err != nil {
  20. return
  21. }
  22. if err = fn(ctx, resource, claims); err != nil {
  23. return
  24. }
  25. ctx.Next()
  26. return
  27. }
  28. }
  29. func ParseToken(token string) (claims *jwt.Claims, err *errs.Error) {
  30. var (
  31. _err error
  32. )
  33. token = strings.Replace(token, PREFIX_AUTHORIZATION_TOKEN, "", -1)
  34. if claims, _err = jwt.HMACCheck([]byte(token), SECRET); _err != nil {
  35. err = errs.Unauthenticated().Details(&errs.Detail{
  36. Message: "Login required",
  37. Location: "Authorization",
  38. LocationType: "header",
  39. Reason: "InvalidAuthorizationToken",
  40. })
  41. } else if !claims.Valid(time.Now()) {
  42. err = errs.Unauthenticated().Details(&errs.Detail{
  43. Message: "Login required",
  44. Location: "Authorization",
  45. LocationType: "header",
  46. Reason: "TokenExpired",
  47. })
  48. }
  49. return
  50. }