github.com/seeker-insurance/kit@v0.0.13/web/authed_config.go (about) 1 package web 2 3 import ( 4 "regexp" 5 "strings" 6 7 "github.com/labstack/echo" 8 emw "github.com/labstack/echo/middleware" 9 "github.com/spf13/viper" 10 ) 11 12 type ( 13 AuthedContextLookup interface { 14 Lookup(echo.Context) (echo.Context, error) 15 Context(echo.Context) echo.Context 16 } 17 // AuthedConfig config for Authed middleware. 18 AuthedConfig struct { 19 // Skipper defines a function to skip middleware. 20 Skipper emw.Skipper 21 } 22 ) 23 24 var ( 25 // DefaultAuthedConfig default Authed middleware config. 26 DefaultAuthedConfig = AuthedConfig{ 27 Skipper: AuthedSkipper(), 28 } 29 ) 30 31 type authSkipperConfig map[string]*regexp.Regexp 32 33 func AuthedSkipper() func(echo.Context) bool { 34 config := viper.GetStringMapString("skipjwt") 35 36 if config == nil || len(config) == 0 { 37 return emw.DefaultSkipper 38 } 39 40 skipper := authSkipperConfig{} 41 for method, exp := range config { 42 skipper[strings.ToUpper(method)] = regexp.MustCompile(exp) 43 } 44 45 return func(c echo.Context) bool { 46 if c.Request().Method == echo.OPTIONS { 47 return true 48 } 49 re, ok := skipper[c.Request().Method] 50 if !ok { 51 return false 52 } 53 54 if hasAuthHeader(c) { 55 return false 56 } 57 58 return re.MatchString(c.Request().URL.Path) 59 } 60 } 61 62 // AuthedWithConfig ... 63 func AuthedWithConfig(config AuthedConfig, cl AuthedContextLookup) echo.MiddlewareFunc { 64 if config.Skipper == nil { 65 config.Skipper = DefaultAuthedConfig.Skipper 66 } 67 68 return func(next echo.HandlerFunc) echo.HandlerFunc { 69 return func(c echo.Context) error { 70 if config.Skipper(c) { 71 return next(cl.Context(c)) 72 } 73 ac, err := cl.Lookup(c) 74 if err != nil { 75 return err 76 } 77 78 return next(ac) 79 } 80 } 81 } 82 83 func hasAuthHeader(c echo.Context) bool { 84 return c.Request().Header.Get(echo.HeaderAuthorization) != "" 85 }