-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsession.go
217 lines (178 loc) · 5.78 KB
/
session.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
package fornitego
import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// Session holds connection information regarding a successful authentication with an Epic account to Epic's API. Will
// hold a Client to use for interfacing with said API, and retain information about our authenticated session with them.
type Session struct {
client *Client
AccessToken string
ExpiresAt string
RefreshToken string
AccountID string
ClientID string
username string
password string
launcherToken string
gameToken string
mux sync.Mutex
}
// Create opens a new connection to Epic and authenticates into the game to obtain the necessary access tokens.
func Create(username, password, launcherToken, gameToken string) *Session {
// Initialize a new client for this session to make requests with.
c := newClient()
// Prepare form to request access token for launcher.
data := url.Values{}
data.Add("grant_type", "password")
data.Add("username", username)
data.Add("password", password)
data.Add("includePerms", "true")
// Prepare request.
req, err := c.NewRequest(http.MethodPost, oauthTokenURL, strings.NewReader(data.Encode()))
if err != nil {
log.Fatalln(err)
}
// Set authorization header to use launcher token.
req.Header.Set("Authorization", fmt.Sprintf("%v %v", AuthBasic, launcherToken))
// Process request and decode response into tokenResponse.
tr := &tokenResponse{}
resp, err := c.Do(req, tr)
if err != nil {
log.Fatalln(err)
}
resp.Body.Close()
///////////////////
// Prepare new request for OAUTH exchange.
req, err = c.NewRequest(http.MethodGet, oauthExchangeURL, nil)
if err != nil {
log.Fatalln(err)
}
// Set authorization header to use the access token just retrieved.
req.Header.Set("Authorization", fmt.Sprintf("%v %v", AuthBearer, tr.AccessToken))
// Process request and decode response into exchangeResponse.
er := &exchangeResponse{}
resp, err = c.Do(req, er)
if err != nil {
log.Fatalln(err)
}
resp.Body.Close()
////////////////////
// Prepare new form for 2nd OAUTH token request for game client.
data = url.Values{}
data.Add("grant_type", "exchange_code")
data.Add("exchange_code", er.Code)
data.Add("includePerms", "true")
data.Add("token_type", "eg1") // should this be eg1???
req, err = c.NewRequest(http.MethodPost, oauthTokenURL, strings.NewReader(data.Encode()))
if err != nil {
log.Fatalln(err)
}
// Set authorization header to use the game token.
req.Header.Set("Authorization", fmt.Sprintf("%v %v", AuthBasic, gameToken))
// Perform request.
resp, err = c.Do(req, tr)
if err != nil {
log.Fatalln(err)
}
resp.Body.Close()
// Create new session object from data retrieved.
ret := &Session{
client: c,
AccessToken: tr.AccessToken,
ExpiresAt: tr.ExpiresAt,
RefreshToken: tr.RefreshToken,
AccountID: tr.AccountID,
ClientID: tr.ClientID,
username: username,
password: password,
launcherToken: launcherToken,
gameToken: gameToken,
}
// Spawn goroutine to handle automatic renewal of access token.
go ret.renewProcess()
log.Println("Session successfully created.")
return ret
}
// Refresh renews a session by obtaining a new access token, and replacing the hold one. Intended use it for an
// automatic goroutine to handle scheduling of renewal. Previous token is automatically invalidated on Epic's end.
func (s *Session) Refresh() error {
data := url.Values{}
data.Add("grant_type", "refresh_token")
data.Add("refresh_token", s.RefreshToken)
data.Add("includePerms", "true")
// Prepare new request containing encoded body.
req, err := s.client.NewRequest(http.MethodPost, oauthTokenURL, strings.NewReader(data.Encode()))
if err != nil {
return err
}
// Use game token for authorization.
req.Header.Set("Authorization", fmt.Sprintf("%v %v", AuthBasic, s.gameToken))
// Perform request and collect response into response object.
tr := &tokenResponse{}
resp, err := s.client.Do(req, tr)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
// Assign token information to session.
s.mux.Lock()
s.AccessToken = tr.AccessToken
s.RefreshToken = tr.RefreshToken
s.ExpiresAt = tr.ExpiresAt
s.mux.Unlock()
return nil
}
// Kill terminates an existing session by sending a DELETE request to deactivate the session on Epic's servers.
func (s *Session) Kill() error {
s.mux.Lock()
defer s.mux.Unlock()
req, err := s.client.NewRequest(http.MethodDelete, killSessionURL+"/"+s.AccessToken, nil)
if err != nil {
return err
}
// Set authentication header to use access token.
req.Header.Set("Authorization", fmt.Sprintf("%v %v", AuthBearer, s.AccessToken))
_, err = s.client.Do(req, nil)
if err != nil {
return err
}
// Clear session information.
s.AccessToken = ""
s.ExpiresAt = ""
s.RefreshToken = ""
log.Println("Session token successfully deactivated.")
return nil
}
// renewProcess is a goroutine intended to be running during the lifetime of a Session. Its intention is to handle
// automatic renewal of access token within a necessary time for renewal to ensure the API stays connected and
// functional.
func (s *Session) renewProcess() {
// Check every 20 seconds if we need to update access token.
updateChecker := time.NewTimer(time.Second * 20)
// Locks until timer above has passed.
<-updateChecker.C
// Parse expiration time into Time object.
expiresAt, err := time.Parse(time.RFC3339, s.ExpiresAt)
if err != nil {
log.Println(err)
return
}
// If the token expiration time does not expire within the next minute, wait and try again.
if !time.Now().After(expiresAt.Add(-time.Minute - 1)) {
defer s.renewProcess()
return
}
// Token expiry is imminent, renew.
err = s.Refresh()
if err != nil {
log.Println("Token renewal unsuccessful: " + err.Error())
}
log.Println("Token renewed successfully.")
defer s.renewProcess()
}