-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgoauth2.go
230 lines (190 loc) · 6.46 KB
/
goauth2.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package goauth2
import (
"context"
"log"
"github.com/inklabs/rangedb"
"github.com/inklabs/rangedb/pkg/clock"
"github.com/inklabs/rangedb/pkg/clock/provider/systemclock"
"github.com/inklabs/rangedb/provider/inmemorystore"
"github.com/inklabs/goauth2/provider/uuidtoken"
)
// Version for Go OAuth2.
const Version = "0.1.0-dev"
// TokenGenerator defines a token generator for refresh tokens and authorization codes.
type TokenGenerator interface {
New() string
}
// App is the OAuth2 CQRS application.
type App struct {
clock clock.Clock
store rangedb.Store
tokenGenerator TokenGenerator
preCommandHandlers map[string][]PreCommandHandler
commandHandlerFactories map[string]CommandHandlerFactory
logger *log.Logger
}
// Option defines functional option parameters for App.
type Option func(*App)
// WithClock is a functional option to inject a clock.
func WithClock(clock clock.Clock) Option {
return func(app *App) {
app.clock = clock
}
}
// WithStore is a functional option to inject a RangeDB Event Store.
func WithStore(store rangedb.Store) Option {
return func(app *App) {
app.store = store
}
}
// WithTokenGenerator is a functional option to inject a token generator.
func WithTokenGenerator(generator TokenGenerator) Option {
return func(app *App) {
app.tokenGenerator = generator
}
}
// WithLogger is a functional option to inject a Logger.
func WithLogger(logger *log.Logger) Option {
return func(app *App) {
app.logger = logger
}
}
// New constructs an OAuth2 CQRS application.
func New(options ...Option) (*App, error) {
app := &App{
store: inmemorystore.New(),
tokenGenerator: uuidtoken.NewGenerator(),
clock: systemclock.New(),
commandHandlerFactories: make(map[string]CommandHandlerFactory),
preCommandHandlers: make(map[string][]PreCommandHandler),
}
for _, option := range options {
option(app)
}
BindEvents(app.store)
app.registerPreCommandHandler(newClientApplicationCommandAuthorization(app.store, app.clock))
app.registerPreCommandHandler(newResourceOwnerCommandAuthorization(app.store, app.tokenGenerator, app.clock))
app.registerCommandHandler(ResourceOwnerCommandTypes(), app.newResourceOwnerAggregate)
app.registerCommandHandler(ClientApplicationCommandTypes(), app.newClientApplicationAggregate)
app.registerCommandHandler(AuthorizationCodeCommandTypes(), app.newAuthorizationCodeAggregate)
app.registerCommandHandler(RefreshTokenCommandTypes(), app.newRefreshTokenAggregate)
authorizationCodeRefreshTokens := NewAuthorizationCodeRefreshTokens()
err := app.SubscribeAndReplay(authorizationCodeRefreshTokens)
if err != nil {
return nil, err
}
ctx := context.Background()
subscribers := newMultipleSubscriber(
newRefreshTokenProcessManager(app.Dispatch, authorizationCodeRefreshTokens),
newAuthorizationCodeProcessManager(app.Dispatch),
)
subscriber := app.store.AllEventsSubscription(ctx, 10, subscribers)
err = subscriber.Start()
if err != nil {
return nil, err
}
return app, nil
}
func (a *App) registerPreCommandHandler(handler PreCommandHandler) {
for _, commandType := range handler.CommandTypes() {
a.preCommandHandlers[commandType] = append(a.preCommandHandlers[commandType], handler)
}
}
func (a *App) registerCommandHandler(commandTypes []string, factory CommandHandlerFactory) {
for _, commandType := range commandTypes {
a.commandHandlerFactories[commandType] = factory
}
}
// Dispatch dispatches a command returning all persisted rangedb.Event's.
func (a *App) Dispatch(command Command) []rangedb.Event {
var preHandlerEvents []rangedb.Event
preCommandHandlers, ok := a.preCommandHandlers[command.CommandType()]
if ok {
for _, handler := range preCommandHandlers {
shouldContinue := handler.Handle(command)
preHandlerEvents = append(preHandlerEvents, a.savePendingEvents(handler)...)
if !shouldContinue {
return preHandlerEvents
}
}
}
newCommandHandler, ok := a.commandHandlerFactories[command.CommandType()]
if !ok {
a.logger.Printf("command handler not found")
return preHandlerEvents
}
handler := newCommandHandler(command)
handler.Handle(command)
handlerEvents := a.savePendingEvents(handler)
return append(preHandlerEvents, handlerEvents...)
}
func (a *App) newClientApplicationAggregate(command Command) CommandHandler {
return newClientApplication(a.eventsByStream(rangedb.GetEventStream(command)), a.clock)
}
func (a *App) newResourceOwnerAggregate(command Command) CommandHandler {
return newResourceOwner(
a.eventsByStream(rangedb.GetEventStream(command)),
a.tokenGenerator,
a.clock,
)
}
func (a *App) newAuthorizationCodeAggregate(command Command) CommandHandler {
return newAuthorizationCode(
a.eventsByStream(rangedb.GetEventStream(command)),
a.tokenGenerator,
a.clock,
)
}
func (a *App) newRefreshTokenAggregate(command Command) CommandHandler {
return newRefreshToken(
a.eventsByStream(rangedb.GetEventStream(command)),
a.tokenGenerator,
a.clock,
)
}
func (a *App) eventsByStream(streamName string) rangedb.RecordIterator {
return a.store.EventsByStream(context.Background(), 0, streamName)
}
func (a *App) savePendingEvents(events PendingEvents) []rangedb.Event {
pendingEvents := events.GetPendingEvents()
ctx := context.Background()
for _, event := range pendingEvents {
_, err := a.store.Save(ctx, &rangedb.EventRecord{
Event: event,
})
if err != nil {
a.logger.Printf("unable to save event: %v", err)
}
}
return pendingEvents
}
// SubscribeAndReplay subscribes and replays all events starting with zero.
func (a *App) SubscribeAndReplay(subscribers ...rangedb.RecordSubscriber) error {
ctx := context.Background()
subscription := a.store.AllEventsSubscription(ctx, 50, newMultipleSubscriber(subscribers...))
err := subscription.StartFrom(0)
if err != nil {
return err
}
return nil
}
func resourceOwnerStream(userID string) string {
return rangedb.GetEventStream(UserWasOnBoarded{UserID: userID})
}
func clientApplicationStream(clientID string) string {
return rangedb.GetEventStream(ClientApplicationWasOnBoarded{ClientID: clientID})
}
type multipleSubscriber struct {
subscribers []rangedb.RecordSubscriber
}
func newMultipleSubscriber(subscribers ...rangedb.RecordSubscriber) *multipleSubscriber {
return &multipleSubscriber{
subscribers: subscribers,
}
}
// Accept receives a rangedb.Record.
func (m multipleSubscriber) Accept(record *rangedb.Record) {
for _, subscriber := range m.subscribers {
subscriber.Accept(record)
}
}