node-api/auth.go

40 lines
796 B
Go
Raw Normal View History

2020-07-13 22:01:42 +00:00
package main
import (
"strings"
"github.com/labstack/echo"
)
2021-04-20 16:34:53 +00:00
var skipPaths []string = []string{"/metrics"}
2020-07-13 22:01:42 +00:00
// TokenMiddleware handles authentication
func TokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
2021-04-20 16:34:53 +00:00
// Skip selected paths
var skip bool
for _, path := range skipPaths {
if path == c.Request().URL.Path {
skip = true
}
}
2020-07-13 22:01:42 +00:00
tokenHeader := c.Request().Header.Get("Authorization")
token := strings.Replace(tokenHeader, "Token ", "", -1)
2021-04-20 16:34:53 +00:00
if token == "" && !skip {
token = c.QueryParam("token")
}
2021-04-25 22:57:05 +00:00
if (token != config.Token || config.Token == "") && !skip {
2020-07-13 22:01:42 +00:00
return c.JSONPretty(403, map[string]string{"message": "access denied"}, " ")
}
if err := next(c); err != nil {
c.Error(err)
}
return nil
}
}