forked from qvest-digital/loginsrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_claims.go
107 lines (96 loc) · 2.31 KB
/
user_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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package login
import (
"io/ioutil"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
"github.com/tarent/loginsrv/model"
"gopkg.in/yaml.v2"
)
type customClaims map[string]interface{}
func (custom customClaims) Valid() error {
if exp, ok := custom["exp"]; ok {
if exp, ok := exp.(int64); ok {
if exp < time.Now().Unix() {
return errors.New("token expired")
}
}
}
return nil
}
type userFileEntry struct {
Sub string `yaml:"sub"`
Origin string `yaml:"origin"`
Email string `yaml:"email"`
Domain string `yaml:"domain"`
Groups []string `yaml:"groups"`
Claims map[string]interface{} `yaml:"claims"`
}
type UserClaims struct {
userFile string
userFileEntries []userFileEntry
}
func NewUserClaims(config *Config) (*UserClaims, error) {
c := &UserClaims{
userFile: config.UserFile,
userFileEntries: []userFileEntry{},
}
err := c.parseUserFile()
return c, err
}
func (c *UserClaims) parseUserFile() error {
if c.userFile == "" {
return nil
}
b, err := ioutil.ReadFile(c.userFile)
if err != nil {
return errors.Wrapf(err, "can't read user file %v", c.userFile)
}
err = yaml.Unmarshal(b, &c.userFileEntries)
if err != nil {
return errors.Wrapf(err, "can't parse user file %v", c.userFile)
}
return nil
}
// Claims returns a map of the token claims for a user.
func (c *UserClaims) Claims(userInfo model.UserInfo) (jwt.Claims, error) {
for _, entry := range c.userFileEntries {
if match(userInfo, entry) {
claims := customClaims(userInfo.AsMap())
for k, v := range entry.Claims {
claims[k] = v
}
return claims, nil
}
}
return userInfo, nil
}
func match(userInfo model.UserInfo, entry userFileEntry) bool {
if entry.Sub != "" && entry.Sub != userInfo.Sub {
return false
}
if entry.Domain != "" && entry.Domain != userInfo.Domain {
return false
}
if entry.Email != "" && entry.Email != userInfo.Email {
return false
}
if entry.Origin != "" && entry.Origin != userInfo.Origin {
return false
}
if len(entry.Groups) > 0 {
eligible := false
for _, entryGroup := range entry.Groups {
for _, userGroup := range userInfo.Groups {
if entryGroup == userGroup {
eligible = true
break
}
}
}
if !eligible {
return false
}
}
return true
}