/
provider.go
117 lines (97 loc) · 2.62 KB
/
provider.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
108
109
110
111
112
113
114
115
116
117
package oauth
import (
"sort"
"github.com/authgear/authgear-server/pkg/lib/authn/identity"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/util/clock"
"github.com/authgear/authgear-server/pkg/util/uuid"
)
type Provider struct {
Store *Store
Clock clock.Clock
IdentityConfig *config.IdentityConfig
}
func (p *Provider) List(userID string) ([]*identity.OAuth, error) {
is, err := p.Store.List(userID)
if err != nil {
return nil, err
}
sortIdentities(is)
return is, nil
}
func (p *Provider) ListByClaim(name string, value string) ([]*identity.OAuth, error) {
is, err := p.Store.ListByClaim(name, value)
if err != nil {
return nil, err
}
sortIdentities(is)
return is, nil
}
func (p *Provider) Get(userID, id string) (*identity.OAuth, error) {
return p.Store.Get(userID, id)
}
func (p *Provider) GetByProviderSubject(provider config.ProviderID, subjectID string) (*identity.OAuth, error) {
return p.Store.GetByProviderSubject(provider, subjectID)
}
func (p *Provider) GetByUserProvider(userID string, provider config.ProviderID) (*identity.OAuth, error) {
return p.Store.GetByUserProvider(userID, provider)
}
func (p *Provider) GetMany(ids []string) ([]*identity.OAuth, error) {
return p.Store.GetMany(ids)
}
func (p *Provider) New(
userID string,
provider config.ProviderID,
subjectID string,
profile map[string]interface{},
claims map[string]interface{},
) *identity.OAuth {
i := &identity.OAuth{
ID: uuid.New(),
UserID: userID,
ProviderID: provider,
ProviderSubjectID: subjectID,
UserProfile: profile,
Claims: claims,
}
alias := ""
for _, providerConfig := range p.IdentityConfig.OAuth.Providers {
providerID := providerConfig.ProviderID()
if providerID.Equal(&i.ProviderID) {
alias = providerConfig.Alias
}
}
if alias != "" {
i.ProviderAlias = alias
}
return i
}
func (p *Provider) WithUpdate(
iden *identity.OAuth,
rawProfile map[string]interface{},
claims map[string]interface{},
) *identity.OAuth {
newIden := *iden
newIden.UserProfile = rawProfile
newIden.Claims = claims
return &newIden
}
func (p *Provider) Create(i *identity.OAuth) error {
now := p.Clock.NowUTC()
i.CreatedAt = now
i.UpdatedAt = now
return p.Store.Create(i)
}
func (p *Provider) Update(i *identity.OAuth) error {
now := p.Clock.NowUTC()
i.UpdatedAt = now
return p.Store.Update(i)
}
func (p *Provider) Delete(i *identity.OAuth) error {
return p.Store.Delete(i)
}
func sortIdentities(is []*identity.OAuth) {
sort.Slice(is, func(i, j int) bool {
return is[i].CreatedAt.Before(is[j].CreatedAt)
})
}