-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault_validator.go
49 lines (39 loc) · 1.15 KB
/
default_validator.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
package jwt
import (
"errors"
"time"
)
type DefaultValidator struct {
now func() time.Time
audiences map[string]struct{}
}
func NewDefaultValidator(audiences ...string) DefaultValidator {
allowed := make(map[string]struct{}, len(audiences))
for _, audience := range audiences {
allowed[audience] = struct{}{}
}
return DefaultValidator{now: time.Now, audiences: allowed}
}
func (this DefaultValidator) Validate(claim interface{}) error {
if expiration, ok := claim.(TokenExpiration); !this.isCurrent(expiration, ok) {
return TokenExpiredErr
}
if audience, ok := claim.(TokenAudience); !this.hasAllowedAudience(audience, ok) {
return InvalidAudienceErr
}
return nil
}
func (this DefaultValidator) hasAllowedAudience(claim TokenAudience, hasAudience bool) bool {
if !hasAudience {
return true
}
_, ok := this.audiences[claim.TokenAudience()]
return ok
}
func (this DefaultValidator) isCurrent(claim TokenExpiration, hasExpiration bool) bool {
return !hasExpiration || claim.TokenExpiration().After(this.now())
}
var (
TokenExpiredErr = errors.New("the token is expired")
InvalidAudienceErr = errors.New("the audience is invalid")
)