forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
76 lines (62 loc) · 1.66 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
package auth
import (
"context"
"time"
"github.com/r00mz/go-zero/core/collection"
"github.com/r00mz/go-zero/core/stores/redis"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const defaultExpiration = 5 * time.Minute
// An Authenticator is used to authenticate the rpc requests.
type Authenticator struct {
store *redis.Redis
key string
cache *collection.Cache
strict bool
}
// NewAuthenticator returns an Authenticator.
func NewAuthenticator(store *redis.Redis, key string, strict bool) (*Authenticator, error) {
cache, err := collection.NewCache(defaultExpiration)
if err != nil {
return nil, err
}
return &Authenticator{
store: store,
key: key,
cache: cache,
strict: strict,
}, nil
}
// Authenticate authenticates the given ctx.
func (a *Authenticator) Authenticate(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Error(codes.Unauthenticated, missingMetadata)
}
apps, tokens := md[appKey], md[tokenKey]
if len(apps) == 0 || len(tokens) == 0 {
return status.Error(codes.Unauthenticated, missingMetadata)
}
app, token := apps[0], tokens[0]
if len(app) == 0 || len(token) == 0 {
return status.Error(codes.Unauthenticated, missingMetadata)
}
return a.validate(app, token)
}
func (a *Authenticator) validate(app, token string) error {
expect, err := a.cache.Take(app, func() (interface{}, error) {
return a.store.Hget(a.key, app)
})
if err != nil {
if a.strict {
return status.Error(codes.Internal, err.Error())
}
return nil
}
if token != expect {
return status.Error(codes.Unauthenticated, accessDenied)
}
return nil
}