-
Notifications
You must be signed in to change notification settings - Fork 125
/
authn.go
50 lines (42 loc) · 1.28 KB
/
authn.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
package preshared
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
grpcAuth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"github.com/pkg/errors"
"github.com/Permify/permify/internal/config"
base "github.com/Permify/permify/pkg/pb/base/v1"
)
// KeyAuthenticator - Interface for key authenticator
type KeyAuthenticator interface {
Authenticate(ctx context.Context) error
}
// KeyAuthn - Authentication Keys Structure
type KeyAuthn struct {
keys map[string]struct{}
}
// NewKeyAuthn - Create New Authenticated Keys
func NewKeyAuthn(_ context.Context, cfg config.Preshared) (*KeyAuthn, error) {
if len(cfg.Keys) < 1 {
return nil, errors.New("pre shared key authn must have at least one key")
}
mapKeys := make(map[string]struct{})
for _, k := range cfg.Keys {
mapKeys[k] = struct{}{}
}
return &KeyAuthn{
keys: mapKeys,
}, nil
}
// Authenticate - Checking whether any API request contain keys
func (a *KeyAuthn) Authenticate(ctx context.Context) error {
key, err := grpcAuth.AuthFromMD(ctx, "Bearer")
if err != nil {
return errors.New(base.ErrorCode_ERROR_CODE_MISSING_BEARER_TOKEN.String())
}
if _, found := a.keys[key]; found {
return nil
}
return status.Error(codes.Unauthenticated, base.ErrorCode_ERROR_CODE_INVALID_KEY.String())
}