-
Notifications
You must be signed in to change notification settings - Fork 1
/
dynamicUserAuth.go
76 lines (66 loc) · 2.19 KB
/
dynamicUserAuth.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
69
70
71
72
73
74
75
76
package dynamicUserAuth
import (
"net/http"
"reflect"
"github.com/labstack/echo"
)
// Stragegies is the map of pointer for strategies.
// key: host, value: strategy
type Stragegies map[string]Strategy
// DynamicUserAuth holds all stragegies for different products.
// Expand this for new products.
type DynamicUserAuth struct {
// Stragegies holds host to strategy
Stragegies Stragegies
}
// StrategyField describes a field for input or output of a strategie
type StrategyField struct {
reflect.Type
Description string
Required bool
}
// StrategyFunction can be for example "newUser"
type StrategyFunction struct {
Description string
Input map[string]StrategyField
Output map[string]StrategyField
Resolve func(echo.Context, map[string]interface{}) (interface{}, error)
}
// Strategy represent a strategy for one product.
// Implement a new strategy for a new product
type Strategy struct {
Functions map[string]StrategyFunction
AuthorizeUser echo.HandlerFunc
Exception func(echo.Context) bool
}
// AuthMiddleware is the middleare for all auth-stuff.
type AuthMiddleware struct {
dynamicUserAuth *DynamicUserAuth
IgnoreLocalhost bool
}
// NewAuthMiddleware creates a new authMiddleware.
// this function is here to force to get all requirements
func NewAuthMiddleware(dynamicUserAuth *DynamicUserAuth) *AuthMiddleware {
return &AuthMiddleware{dynamicUserAuth: dynamicUserAuth, IgnoreLocalhost: false}
}
// Handle handles the auth-process.
// Use this for all save-endpoints.
func (authMiddleware *AuthMiddleware) Handle(next echo.HandlerFunc) echo.HandlerFunc {
return func(context echo.Context) error {
// check host
host := context.Request().Host
// Check first if strategy for this host exist.
// If-else-construct is confused (`return next(context)` should be at the end).
// - If you find a better way, plz go for it!
if strategy, ok := authMiddleware.dynamicUserAuth.Stragegies[host]; ok {
if !(strategy.Exception == nil || !strategy.Exception(context)) {
return next(context)
}
if err := strategy.AuthorizeUser(context); err != nil {
return err
}
return next(context)
}
return context.JSON(http.StatusUnauthorized, "can't find strategy")
}
}