-
Notifications
You must be signed in to change notification settings - Fork 179
/
jwt.go
68 lines (58 loc) · 2.1 KB
/
jwt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package middleware
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/actiontech/sqle/sqle/model"
"github.com/actiontech/sqle/sqle/utils"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// JWTTokenAdapter is a `echo` middleware, by rewriting the header, the jwt token support header
// "Authorization: {token}" and "Authorization: Bearer {token}".
func JWTTokenAdapter() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
auth := c.Request().Header.Get(echo.HeaderAuthorization)
if auth != "" && !strings.HasPrefix(auth, middleware.DefaultJWTConfig.AuthScheme) {
c.Request().Header.Set(echo.HeaderAuthorization,
fmt.Sprintf("%s %s", middleware.DefaultJWTConfig.AuthScheme, auth))
}
return next(c)
}
}
}
var errAuditPlanMisMatch = errors.New("audit plan name don't match the token or audit plan not found")
// ScannerVerifier is a `echo` middleware. Every audit plan should be
// scanner-scoped which means that scanner-A should not push SQL to scanner-B.
func ScannerVerifier() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// JWT parser expect no 'Bearer' ahead of token, so
// we cut the leading auth schema.
auth := c.Request().Header.Get(echo.HeaderAuthorization)
parts := strings.Split(auth, " ")
token := parts[0]
if len(parts) == 2 {
token = parts[1]
}
apnInToken, err := utils.ParseAuditPlanName(token)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
apnInParam := c.Param("audit_plan_name")
if apnInToken != apnInParam {
return echo.NewHTTPError(http.StatusInternalServerError, errAuditPlanMisMatch.Error())
}
apn, apnExist, err := model.GetStorage().GetAuditPlanByName(apnInParam)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
if !apnExist || apn.Token != token {
return echo.NewHTTPError(http.StatusInternalServerError, errAuditPlanMisMatch.Error())
}
return next(c)
}
}
}