-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
84 lines (67 loc) · 1.75 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package goautowp
import (
"context"
"fmt"
"strings"
"github.com/Nerzal/gocloak/v13"
"github.com/autowp/goautowp/config"
"github.com/autowp/goautowp/users"
"github.com/doug-martin/goqu/v9"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type Auth struct {
db *goqu.Database
keycloak *gocloak.GoCloak
keycloakCfg config.KeycloakConfig
repository *users.Repository
}
func NewAuth(
db *goqu.Database,
keycloak *gocloak.GoCloak,
keycloakCfg config.KeycloakConfig,
repository *users.Repository,
) *Auth {
return &Auth{
db: db,
keycloak: keycloak,
keycloakCfg: keycloakCfg,
repository: repository,
}
}
func (s *Auth) ValidateGRPC(ctx context.Context) (int64, string, error) {
const bearerSchema = "Bearer"
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return 0, "", status.Errorf(codes.InvalidArgument, "missing metadata")
}
lines := md["authorization"]
if len(lines) < 1 {
return 0, "", nil
}
tokenString := strings.TrimPrefix(lines[0], bearerSchema+" ")
return s.ValidateToken(ctx, tokenString)
}
func (s *Auth) ValidateToken(ctx context.Context, tokenString string) (int64, string, error) {
if len(tokenString) == 0 {
return 0, "", fmt.Errorf("authorization token is invalid")
}
var claims users.Claims
_, err := s.keycloak.DecodeAccessTokenCustomClaims(ctx, tokenString, s.keycloakCfg.Realm, &claims)
if err != nil {
return 0, "", err
}
id, role, err := s.repository.EnsureUserImported(ctx, claims)
if err != nil {
return 0, "", err
}
if role == "" {
return 0, "", fmt.Errorf("failed role detection for `%v`", claims.Subject)
}
err = s.repository.RegisterVisit(ctx, id)
if role == "" {
return 0, "", err
}
return id, role, nil
}