/
fosite_mongo.go
93 lines (76 loc) · 2.12 KB
/
fosite_mongo.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
//go:generate mockgen -destination client_mocks_test.go -package mongo -source=fosite_mongo.go -mock_names mockClientManager=MockClientManager
package mongo
import (
"context"
"time"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/oauth2"
"github.com/ory/fosite/handler/pkce"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/trustbloc/vcs/component/oidc/fosite/dto"
"github.com/trustbloc/vcs/pkg/storage/mongodb"
)
var (
_ fosite.Storage = (*Store)(nil)
_ fosite.PARStorage = (*Store)(nil)
_ pkce.PKCERequestStorage = (*Store)(nil)
_ oauth2.CoreStorage = (*Store)(nil)
_ oauth2.TokenRevocationStorage = (*Store)(nil)
)
const defaultTTL = 24 * time.Hour
type mockClientManager interface { //nolint:unused // used to generate mock
fosite.ClientManager
}
type Store struct {
mongoClient *mongodb.Client
clientManager fosite.ClientManager
}
func NewStore(
ctx context.Context,
mongoClient *mongodb.Client,
clientManager fosite.ClientManager,
) (*Store, error) {
cl := &Store{
mongoClient: mongoClient,
clientManager: clientManager,
}
if err := cl.migrate(ctx); err != nil {
return nil, err
}
return cl, nil
}
func (s *Store) migrate(ctx context.Context) error {
baseSessionIndexes := []mongo.IndexModel{
{
Keys: map[string]interface{}{
"_lookupId": -1,
},
Options: options.Index().SetUnique(true),
},
{
Keys: map[string]interface{}{
"expireAt": 1,
},
Options: options.Index().SetExpireAfterSeconds(0),
},
}
indexes := map[string][]mongo.IndexModel{
dto.ParSegment: baseSessionIndexes,
dto.AuthCodeSegment: baseSessionIndexes,
dto.PkceSessionSegment: baseSessionIndexes,
dto.RefreshTokenSegment: baseSessionIndexes,
dto.AccessTokenSegment: baseSessionIndexes,
}
for collection, targetIndexes := range indexes {
if _, err := s.mongoClient.Database().Collection(collection).Indexes().
CreateMany(ctx, targetIndexes); err != nil {
return err
}
}
return nil
}