-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.go
43 lines (32 loc) · 895 Bytes
/
middleware.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
package main
import (
"net/http"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
)
type CustomValidator struct {
validator *validator.Validate
}
func (cv *CustomValidator) Validate(i interface{}) error {
return cv.validator.Struct(i)
}
func KeyAuthMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
key := c.Request().Header.Get("Authorization")
if key == "" {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing Key")
}
var auth Auth
db.First(&auth, "key = ?", key)
if auth.ID == 0 {
return echo.NewHTTPError(http.StatusForbidden, "Invalid Key")
}
if auth.RemainingPoints <= 0 {
return echo.NewHTTPError(http.StatusForbidden, "You do not have permission to access this resource")
}
c.Set("auth", auth)
return next(c)
}
}
}