forked from ori-shem-tov/algosearch
/
claims.go
52 lines (43 loc) · 1.13 KB
/
claims.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
package auth
import (
"context"
"errors"
"github.com/golang-jwt/jwt/v4"
)
// These are the expected values for Claims.Roles.
const (
RoleAdmin = "ADMIN"
RoleUser = "USER"
)
// Claims represents the authorization claims transmitted via a JWT.
type Claims struct {
jwt.RegisteredClaims
Roles []string `json:"roles"`
}
// Authorized returns true if the claims has at least one of the provided roles.
func (c Claims) Authorized(roles ...string) bool {
for _, has := range c.Roles {
for _, want := range roles {
if has == want {
return true
}
}
}
return false
}
// ctxKey represents the type of value for the context key.
type ctxKey int
// key is used to store/retrieve a Claims value from a context.Context.
const key ctxKey = 1
// SetClaims stores the claims in the context.
func SetClaims(ctx context.Context, claims Claims) context.Context {
return context.WithValue(ctx, key, claims)
}
// GetClaims returns the claims from the context.
func GetClaims(ctx context.Context) (Claims, error) {
v, ok := ctx.Value(key).(Claims)
if !ok {
return Claims{}, errors.New("claim value missing from context")
}
return v, nil
}