forked from inklabs/goauth2
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthorization_code.go
111 lines (90 loc) · 2.65 KB
/
authorization_code.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
package goauth2
import (
"github.com/inklabs/rangedb"
"github.com/inklabs/rangedb/pkg/clock"
)
type authorizationCode struct {
tokenGenerator TokenGenerator
clock clock.Clock
IsLoaded bool
ExpiresAt int64
UserID string
HasBeenPreviouslyUsed bool
PendingEvents []rangedb.Event
}
func newAuthorizationCode(records <-chan *rangedb.Record, generator TokenGenerator, clock clock.Clock) *authorizationCode {
aggregate := &authorizationCode{
tokenGenerator: generator,
clock: clock,
}
for record := range records {
if event, ok := record.Data.(rangedb.Event); ok {
aggregate.apply(event)
}
}
return aggregate
}
func (a *authorizationCode) apply(event rangedb.Event) {
switch e := event.(type) {
case *AuthorizationCodeWasIssuedToUser:
a.IsLoaded = true
a.ExpiresAt = e.ExpiresAt
a.UserID = e.UserID
case *AccessTokenWasIssuedToUserViaAuthorizationCodeGrant:
a.HasBeenPreviouslyUsed = true
case *RefreshTokenWasIssuedToUserViaAuthorizationCodeGrant:
a.HasBeenPreviouslyUsed = true
}
}
func (a *authorizationCode) Handle(command Command) {
switch c := command.(type) {
case RequestAccessTokenViaAuthorizationCodeGrant:
if !a.IsLoaded {
a.emit(RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToInvalidAuthorizationCode{
AuthorizationCode: c.AuthorizationCode,
ClientID: c.ClientID,
})
return
}
if a.HasBeenPreviouslyUsed {
a.emit(RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToPreviouslyUsedAuthorizationCode{
AuthorizationCode: c.AuthorizationCode,
ClientID: c.ClientID,
})
return
}
if a.isExpired() {
a.emit(RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToExpiredAuthorizationCode{
AuthorizationCode: c.AuthorizationCode,
ClientID: c.ClientID,
})
return
}
refreshToken := a.tokenGenerator.New()
a.emit(
AccessTokenWasIssuedToUserViaAuthorizationCodeGrant{
AuthorizationCode: c.AuthorizationCode,
UserID: a.UserID,
ClientID: c.ClientID,
},
RefreshTokenWasIssuedToUserViaAuthorizationCodeGrant{
AuthorizationCode: c.AuthorizationCode,
UserID: a.UserID,
ClientID: c.ClientID,
RefreshToken: refreshToken,
},
)
}
}
func (a *authorizationCode) emit(events ...rangedb.Event) {
for _, event := range events {
a.apply(event)
}
a.PendingEvents = append(a.PendingEvents, events...)
}
func (a *authorizationCode) GetPendingEvents() []rangedb.Event {
return a.PendingEvents
}
func (a *authorizationCode) isExpired() bool {
return a.clock.Now().Unix() > a.ExpiresAt
}