-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication.go
71 lines (59 loc) · 1.63 KB
/
authentication.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
package stateful
import (
"context"
"fmt"
"github.com/justdomepaul/toolbox/array"
"github.com/justdomepaul/toolbox/config"
"github.com/justdomepaul/toolbox/errorhandler"
"github.com/justdomepaul/toolbox/jwt"
"github.com/justdomepaul/toolbox/services"
"strings"
)
var (
newToken = jwt.NewCommon
)
func NewAuthorization(id []byte, claim *jwt.Common) *Authorization {
return &Authorization{
ID: id,
Claim: claim,
}
}
type Authorization struct {
ID []byte
Claim *jwt.Common
}
func (a *Authorization) GetID() []byte {
return a.ID
}
func (a *Authorization) GetClaim() interface{} {
return a.Claim
}
func NewAuthentication(gRPC config.GRPC, jwt jwt.IJWT) (*Authentication, error) {
return &Authentication{
allowedList: gRPC.AllowedList,
j: jwt,
}, nil
}
type Authentication struct {
allowedList []string
j jwt.IJWT
}
func (s *Authentication) Authenticate(ctx context.Context, tokenFn func() (string, error), fullMethod string) (authorization services.IAuthorization, err error) {
for _, term := range s.allowedList {
if strings.HasPrefix(fullMethod, term) {
return NewAuthorization(nil, nil), errorhandler.ErrInWhitelist
}
}
token, err := tokenFn()
if err != nil {
return nil, fmt.Errorf("%w: %s", errorhandler.ErrUnauthenticated, err.Error())
}
claim := newToken(jwt.NewClaimsBuilder().Build())
if err := s.j.VerifyToken(token, claim); err != nil {
return nil, fmt.Errorf("%w: %s", errorhandler.ErrUnauthenticated, err.Error())
}
if _, exist := array.Find(claim.Scopes, fullMethod); !exist {
return nil, errorhandler.ErrOutOfScopes
}
return NewAuthorization(claim.ClientID, claim), nil
}