-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
63 lines (55 loc) · 1.83 KB
/
auth.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
package api
import (
"fmt"
"strings"
"github.com/Sirupsen/logrus"
"github.com/cad/ovpm"
"github.com/cad/ovpm/permset"
gcontext "golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
func authRequired(ctx gcontext.Context, req interface{}, handler grpc.UnaryHandler) (resp interface{}, err error) {
logrus.Debugln("rpc: auth applied")
token, err := authzTokenFromContext(ctx)
if err != nil {
logrus.Debugln("rpc: auth denied because token can not be gathered from header contest")
return nil, grpc.Errorf(codes.Unauthenticated, err.Error())
}
user, err := ovpm.GetUserByToken(token)
if err != nil {
logrus.Debugln("rpc: auth denied because user with this token can not be found")
return nil, grpc.Errorf(codes.Unauthenticated, "access denied")
}
// Set user's permissions according to it's criterias.
var permissions permset.Permset
if user.IsAdmin() {
permissions = permset.New(ovpm.AdminPerms()...)
} else {
permissions = permset.New(ovpm.UserPerms()...)
}
newCtx := NewUsernameContext(ctx, user.GetUsername())
newCtx = permset.NewContext(newCtx, permissions)
return handler(newCtx, req)
}
func authzTokenFromContext(ctx gcontext.Context) (string, error) {
// retrieve metadata from context
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", fmt.Errorf("authentication required")
}
if len(md["authorization"]) != 1 {
return "", fmt.Errorf("authentication required (length)")
}
authHeader := md["authorization"][0]
// split authorization header into two
splitToken := strings.Split(authHeader, "Bearer")
if len(splitToken) != 2 {
return "", fmt.Errorf("invalid Authorization header. it should be in the form of 'Bearer <token>': %s", authHeader)
}
// get token
token := splitToken[1]
token = strings.TrimSpace(token)
return token, nil
}