-
Notifications
You must be signed in to change notification settings - Fork 0
/
authorization.go
55 lines (48 loc) · 1.27 KB
/
authorization.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
package gapi
import (
"context"
"fmt"
"strings"
"github.com/dbracic21-foi/simplebank/token"
"google.golang.org/grpc/metadata"
)
const (
authoriaztionHeader = "authorization"
authorizationBearer = "bearer"
)
func (server *Server) authorizationUser(ctx context.Context, accesibleRoles []string) (*token.Payload, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, fmt.Errorf("missing metadata")
}
values := md.Get(authoriaztionHeader)
if len(values) == 0 {
return nil, fmt.Errorf("missing authorization header")
}
authHeader := values[0]
fields := strings.Fields(authHeader)
if len(fields) < 2 {
return nil, fmt.Errorf("invalid authorization header format")
}
authType := strings.ToLower(fields[0])
if authType != authorizationBearer {
return nil, fmt.Errorf("unsupported authorization type")
}
accessToken := fields[1]
payload, err := server.tokenMaker.VerifyToken(accessToken)
if err != nil {
return nil, fmt.Errorf("invalid access token : %s", err)
}
if !hasPermission(payload.Role, accesibleRoles) {
return nil, fmt.Errorf("unauthorized")
}
return payload, nil
}
func hasPermission(userRole string, accesibleRoles []string) bool {
for _, role := range accesibleRoles {
if userRole == role {
return true
}
}
return false
}