-
Notifications
You must be signed in to change notification settings - Fork 0
/
Token.swift
227 lines (207 loc) · 9.04 KB
/
Token.swift
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
//
// Token.swift
//
//
// Created by Steffen Kötte on 2020-07-12.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// Errors which can happen when getting a Token
public enum TokenError: Error {
/// When no token is found
case noToken
/// When the received data is not valid JSON
case invalidJson(error: String)
/// When the received JSON does not have the right type
case invalidJsonType(json: Any)
/// When the paramters could not be converted to JSON
case invalidParameters(parameters: [String: String])
/// When the received JSON does not have all expected values
case missingResultParamenter(json: [String: Any])
/// When an HTTP error occurs
case httpError(error: String)
/// When no data is received from the HTTP request
case noDataReceived
}
struct Token {
private static let credentialStorageKeyAccessToken = "accessToken"
private static let credentialStorageKeyRefreshToken = "refreshToken"
private static let credentialStorageKeyExpiry = "expiry"
private static var url = URL(string: "https://api.production.wealthsimple.com/v1/oauth/token")!
private static var testUrl = URL(string: "https://api.production.wealthsimple.com/v1/oauth/token/info")!
private static var clientId = "4da53ac2b03225bed1550eba8e4611e086c7b905a3855e6ed12ea08c246758fa" // From the website
private static var scope = "invest.read mfda.read mercer.read trade.read" // the clientId supports some write scopes, but as this library only reads we limit it for safety
private let accessToken: String
private let refreshToken: String
private let expiry: Date
private let credentialStorage: CredentialStorage
private init(accessToken: String, refreshToken: String, expiry: Date, credentialStorage: CredentialStorage) {
self.accessToken = accessToken
self.refreshToken = refreshToken
self.expiry = expiry
self.credentialStorage = credentialStorage
}
private init(json: [String: Any], credentialStorage: CredentialStorage) throws {
guard let accessToken = json["access_token"] as? String,
let expiresIn = json["expires_in"] as? Int,
let createdAt = json["created_at"] as? Int,
let refreshToken = json["refresh_token"] as? String else {
throw TokenError.missingResultParamenter(json: json)
}
self.accessToken = accessToken
self.refreshToken = refreshToken
let expiresAt = createdAt + expiresIn
self.expiry = Date(timeIntervalSince1970: TimeInterval(expiresAt))
self.credentialStorage = credentialStorage
}
static func getToken(username: String, password: String, otp: String, credentialStorage: CredentialStorage, completion: @escaping (Result<Self, TokenError>) -> Void) {
var request = URLRequest(url: url)
request.setValue(otp, forHTTPHeaderField: "x-wealthsimple-otp")
let json = [
"grant_type": "password",
"username": username,
"password": password,
"scope": scope,
"client_id": clientId
]
sendTokenRequest(parameters: json, request: request, credentialStorage: credentialStorage, completion: completion)
}
static func getToken(from credentialStorage: CredentialStorage, completion: @escaping (Self?) -> Void) {
guard let accessToken = credentialStorage.read(credentialStorageKeyAccessToken),
let refreshToken = credentialStorage.read(credentialStorageKeyRefreshToken),
let expiryString = credentialStorage.read(credentialStorageKeyExpiry),
let expiryDouble = Double(expiryString) else {
completion(nil)
return
}
let token = Self(accessToken: accessToken, refreshToken: refreshToken, expiry: Date(timeIntervalSince1970: expiryDouble), credentialStorage: credentialStorage)
token.refreshIfNeeded {
switch $0 {
case .failure:
completion(nil)
case let .success(newToken):
newToken.testIfValid {
if $0 {
completion(newToken)
} else {
completion(nil)
}
}
}
}
}
private static func sendTokenRequest(
parameters json: [String: String],
request urlRequest: URLRequest,
credentialStorage: CredentialStorage,
completion: @escaping (Result<Self, TokenError>) -> Void
) {
var request = urlRequest
let session = URLSession.shared
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []) else {
completion(.failure(TokenError.invalidParameters(parameters: json)))
return
}
let task = session.uploadTask(with: request, from: jsonData) { data, response, error in
handleTokenResponse(data: data, response: response, error: error, credentialStorage: credentialStorage, completion: completion)
}
task.resume()
}
private static func handleTokenResponse(
data: Data?,
response: URLResponse?,
error: Error?,
credentialStorage: CredentialStorage,
completion: @escaping (Result<Self, TokenError>) -> Void
) {
guard let data = data else {
if let error = error {
completion(.failure(TokenError.httpError(error: error.localizedDescription)))
} else {
completion(.failure(TokenError.noDataReceived))
}
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(TokenError.httpError(error: "No HTTPURLResponse")))
return
}
guard httpResponse.statusCode == 200 else {
completion(.failure(TokenError.httpError(error: "Status code \(httpResponse.statusCode)")))
return
}
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
completion(.failure(TokenError.invalidJsonType(json: try JSONSerialization.jsonObject(with: data, options: []))))
return
}
do {
let token = try Token(json: json, credentialStorage: credentialStorage)
token.saveToken()
completion(.success(token))
} catch {
completion(.failure(error as! TokenError)) // swiftlint:disable:this force_cast
}
} catch {
completion(.failure(TokenError.invalidJson(error: error.localizedDescription)))
return
}
}
private func testIfValid(completion: @escaping (Bool) -> Void) {
var request = URLRequest(url: Self.testUrl)
let session = URLSession.shared
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
authenticateRequest(request) {
switch $0 {
case .failure:
completion(false)
case let .success(request):
let task = session.dataTask(with: request) { _, response, error in
guard error == nil else {
completion(false)
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(false)
return
}
completion(httpResponse.statusCode == 200)
}
task.resume()
}
}
}
func authenticateRequest(_ request: URLRequest, completion: @escaping (Result<URLRequest, TokenError>) -> Void) {
var requestCopy = request
requestCopy.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
completion(.success(requestCopy))
}
func refreshIfNeeded(completion: @escaping (Result<Self, TokenError>) -> Void) {
if needsRefresh() {
refresh(completion: completion)
} else {
completion(.success(self))
}
}
private func needsRefresh() -> Bool {
expiry < Date()
}
private func refresh(completion: @escaping (Result<Self, TokenError>) -> Void) {
let request = URLRequest(url: Self.url)
let json = [
"grant_type": "refresh_token",
"refresh_token": refreshToken,
"client_id": Self.clientId
]
Self.sendTokenRequest(parameters: json, request: request, credentialStorage: credentialStorage, completion: completion)
}
private func saveToken() {
credentialStorage.save(accessToken, for: Self.credentialStorageKeyAccessToken)
credentialStorage.save(refreshToken, for: Self.credentialStorageKeyRefreshToken)
credentialStorage.save(String(expiry.timeIntervalSince1970), for: Self.credentialStorageKeyExpiry)
}
}