-
Notifications
You must be signed in to change notification settings - Fork 207
/
OAuth.swift
490 lines (405 loc) · 16.1 KB
/
OAuth.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import SystemConfiguration
import Foundation
public protocol SharedApplication {
func presentErrorMessage(_ message: String, title: String)
func presentErrorMessageWithHandlers(_ message: String, title: String, buttonHandlers: Dictionary<String, () -> Void>)
func presentPlatformSpecificAuth(_ authURL: URL) -> Bool
func presentAuthChannel(_ authURL: URL, tryIntercept: @escaping ((URL) -> Bool), cancelHandler: @escaping (() -> Void))
func presentExternalApp(_ url: URL)
func canPresentExternalApp(_ url: URL) -> Bool
}
/// Manages access token storage and authentication
///
/// Use the `DropboxOAuthManager` to authenticate users through OAuth2, save access tokens, and retrieve access tokens.
///
/// @note OAuth flow webviews localize to enviroment locale.
///
open class DropboxOAuthManager {
open let locale: Locale?
let appKey: String
let redirectURL: URL
let host: String
var urls: Array<URL>
// MARK: Shared instance
/// A shared instance of a `DropboxOAuthManager` for convenience
open static var sharedOAuthManager: DropboxOAuthManager!
// MARK: Functions
public init(appKey: String, host: String) {
self.appKey = appKey
self.redirectURL = URL(string: "db-\(self.appKey)://2/token")!
self.host = host
self.urls = [self.redirectURL]
self.locale = nil;
}
///
/// Create an instance
/// parameter appKey: The app key from the developer console that identifies this app.
///
convenience public init(appKey: String) {
self.init(appKey: appKey, host: "www.dropbox.com")
}
///
/// Try to handle a redirect back into the application
///
/// - parameter url: The URL to attempt to handle
///
/// - returns `nil` if SwiftyDropbox cannot handle the redirect URL, otherwise returns the `DropboxOAuthResult`.
///
open func handleRedirectURL(_ url: URL) -> DropboxOAuthResult? {
// check if url is a cancel url
if (url.host == "1" && url.path == "/cancel") || (url.host == "2" && url.path == "/cancel") {
return .cancel
}
if !self.canHandleURL(url) {
return nil
}
let result = extractFromUrl(url)
switch result {
case .success(let token):
_ = Keychain.set(token.uid, value: token.accessToken)
return result
default:
return result
}
}
///
/// Present the OAuth2 authorization request page by presenting a web view controller modally
///
/// - parameter controller: The controller to present from
///
open func authorizeFromSharedApplication(_ sharedApplication: SharedApplication) {
let cancelHandler: (() -> Void) = {
let cancelUrl = URL(string: "db-\(self.appKey)://2/cancel")!
sharedApplication.presentExternalApp(cancelUrl)
}
if !Reachability.connectedToNetwork() {
let message = "Try again once you have an internet connection"
let title = "No internet connection"
let buttonHandlers: [String: () -> Void] = [
"Cancel": { cancelHandler() },
"Retry": { self.authorizeFromSharedApplication(sharedApplication) },
]
sharedApplication.presentErrorMessageWithHandlers(message, title: title, buttonHandlers: buttonHandlers)
return
}
if !self.conformsToAppScheme() {
let message = "DropboxSDK: unable to link; app isn't registered for correct URL scheme (db-\(self.appKey)). Add this scheme to your project Info.plist file, under \"URL types\" > \"URL Schemes\"."
let title = "SwiftyDropbox Error"
sharedApplication.presentErrorMessage(message, title:title)
return
}
let url = self.authURL()
if checkAndPresentPlatformSpecificAuth(sharedApplication) {
return
}
let tryIntercept: ((URL) -> Bool) = { url in
if self.canHandleURL(url) {
sharedApplication.presentExternalApp(url)
return true
} else {
return false
}
}
sharedApplication.presentAuthChannel(url, tryIntercept: tryIntercept, cancelHandler: cancelHandler)
}
fileprivate func conformsToAppScheme() -> Bool {
let appScheme = "db-\(self.appKey)"
let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [ [String: AnyObject] ] ?? []
for urlType in urlTypes {
let schemes = urlType["CFBundleURLSchemes"] as? [String] ?? []
for scheme in schemes {
if scheme == appScheme {
return true
}
}
}
return false
}
func authURL() -> URL {
var components = URLComponents()
components.scheme = "https"
components.host = self.host
components.path = "/oauth2/authorize"
let locale = Bundle.main.preferredLocalizations.first ?? "en"
components.queryItems = [
URLQueryItem(name: "response_type", value: "token"),
URLQueryItem(name: "client_id", value: self.appKey),
URLQueryItem(name: "redirect_uri", value: self.redirectURL.absoluteString),
URLQueryItem(name: "disable_signup", value: "true"),
URLQueryItem(name: "locale", value: self.locale?.identifier ?? locale),
]
return components.url!
}
fileprivate func canHandleURL(_ url: URL) -> Bool {
for known in self.urls {
if url.scheme == known.scheme && url.host == known.host && url.path == known.path {
return true
}
}
return false
}
func extractFromRedirectURL(_ url: URL) -> DropboxOAuthResult {
var results = [String: String]()
let pairs = url.fragment?.components(separatedBy: "&") ?? []
for pair in pairs {
let kv = pair.components(separatedBy: "=")
results.updateValue(kv[1], forKey: kv[0])
}
if let error = results["error"] {
let desc = results["error_description"]?.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
if results["error"]! == "access_denied" {
return .cancel
}
return .error(OAuth2Error(errorCode: error), desc ?? "")
} else {
let accessToken = results["access_token"]!
let uid = results["uid"]!
return .success(DropboxAccessToken(accessToken: accessToken, uid: uid))
}
}
func extractFromUrl(_ url: URL) -> DropboxOAuthResult {
return extractFromRedirectURL(url)
}
func checkAndPresentPlatformSpecificAuth(_ sharedApplication: SharedApplication) -> Bool {
return false
}
///
/// Retrieve all stored access tokens
///
/// - returns: a dictionary mapping users to their access tokens
///
open func getAllAccessTokens() -> [String : DropboxAccessToken] {
let users = Keychain.getAll()
var ret = [String : DropboxAccessToken]()
for user in users {
if let accessToken = Keychain.get(user) {
ret[user] = DropboxAccessToken(accessToken: accessToken, uid: user)
}
}
return ret
}
///
/// Check if there are any stored access tokens
///
/// - returns: Whether there are stored access tokens
///
open func hasStoredAccessTokens() -> Bool {
return self.getAllAccessTokens().count != 0
}
///
/// Retrieve the access token for a particular user
///
/// - parameter user: The user whose token to retrieve
///
/// - returns: An access token if present, otherwise `nil`.
///
open func getAccessToken(_ user: String?) -> DropboxAccessToken? {
if let user = user {
if let accessToken = Keychain.get(user) {
return DropboxAccessToken(accessToken: accessToken, uid: user)
}
}
return nil
}
///
/// Delete a specific access token
///
/// - parameter token: The access token to delete
///
/// - returns: whether the operation succeeded
///
open func clearStoredAccessToken(_ token: DropboxAccessToken) -> Bool {
return Keychain.delete(token.uid)
}
///
/// Delete all stored access tokens
///
/// - returns: whether the operation succeeded
///
open func clearStoredAccessTokens() -> Bool {
return Keychain.clear()
}
///
/// Save an access token
///
/// - parameter token: The access token to save
///
/// - returns: whether the operation succeeded
///
open func storeAccessToken(_ token: DropboxAccessToken) -> Bool {
return Keychain.set(token.uid, value: token.accessToken)
}
///
/// Utility function to return an arbitrary access token
///
/// - returns: the "first" access token found, if any (otherwise `nil`)
///
open func getFirstAccessToken() -> DropboxAccessToken? {
return self.getAllAccessTokens().values.first
}
}
/// A Dropbox access token
open class DropboxAccessToken: CustomStringConvertible {
/// The access token string
open let accessToken: String
/// The associated user
open let uid: String
public init(accessToken: String, uid: String) {
self.accessToken = accessToken
self.uid = uid
}
open var description: String {
return self.accessToken
}
}
/// A failed authorization.
/// See RFC6749 4.2.2.1
public enum OAuth2Error {
/// The client is not authorized to request an access token using this method.
case unauthorizedClient
/// The resource owner or authorization server denied the request.
case accessDenied
/// The authorization server does not support obtaining an access token using this method.
case unsupportedResponseType
/// The requested scope is invalid, unknown, or malformed.
case invalidScope
/// The authorization server encountered an unexpected condition that prevented it from fulfilling the request.
case serverError
/// The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
case temporarilyUnavailable
/// Some other error (outside of the OAuth2 specification)
case unknown
/// Initializes an error code from the string specced in RFC6749
init(errorCode: String) {
switch errorCode {
case "unauthorized_client": self = .unauthorizedClient
case "access_denied": self = .accessDenied
case "unsupported_response_type": self = .unsupportedResponseType
case "invalid_scope": self = .invalidScope
case "server_error": self = .serverError
case "temporarily_unavailable": self = .temporarilyUnavailable
default: self = .unknown
}
}
}
internal let kDBLinkNonce = "dropbox.sync.nonce"
/// The result of an authorization attempt.
public enum DropboxOAuthResult {
/// The authorization succeeded. Includes a `DropboxAccessToken`.
case success(DropboxAccessToken)
/// The authorization failed. Includes an `OAuth2Error` and a descriptive message.
case error(OAuth2Error, String)
/// The authorization was manually canceled by the user.
case cancel
}
class Keychain {
static let checkAccessibilityMigrationOneTime: () = {
Keychain.checkAccessibilityMigration()
}()
class func queryWithDict(_ query: [String : AnyObject]) -> CFDictionary {
let bundleId = Bundle.main.bundleIdentifier ?? ""
var queryDict = query
queryDict[kSecClass as String] = kSecClassGenericPassword
queryDict[kSecAttrService as String] = "\(bundleId).dropbox.authv2" as AnyObject?
queryDict[kSecAttrService as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
return queryDict as CFDictionary
}
class func set(_ key: String, value: String) -> Bool {
if let data = value.data(using: String.Encoding.utf8) {
return set(key, value: data)
} else {
return false
}
}
class func set(_ key: String, value: Data) -> Bool {
let query = Keychain.queryWithDict([
(kSecAttrAccount as String): key as AnyObject,
( kSecValueData as String): value as AnyObject
])
SecItemDelete(query)
return SecItemAdd(query, nil) == noErr
}
class func getAsData(_ key: String) -> Data? {
let query = Keychain.queryWithDict([
(kSecAttrAccount as String): key as AnyObject,
( kSecReturnData as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitOne
])
var dataResult: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &dataResult)
if status == noErr {
return dataResult as? Data
}
return nil
}
class func getAll() -> [String] {
let query = Keychain.queryWithDict([
( kSecReturnAttributes as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitAll
])
var dataResult: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &dataResult)
if status == noErr {
let results = dataResult as? [[String : AnyObject]] ?? []
return results.map { d in d["acct"] as! String }
}
return []
}
class func get(_ key: String) -> String? {
if let data = getAsData(key) {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String?
} else {
return nil
}
}
class func delete(_ key: String) -> Bool {
let query = Keychain.queryWithDict([
(kSecAttrAccount as String): key as AnyObject
])
return SecItemDelete(query) == noErr
}
class func clear() -> Bool {
let query = Keychain.queryWithDict([:])
return SecItemDelete(query) == noErr
}
class func checkAccessibilityMigration() {
let kAccessibilityMigrationOccurredKey = "KeychainAccessibilityMigration"
let MigrationOccurred = UserDefaults.standard.string(forKey: kAccessibilityMigrationOccurredKey)
if (MigrationOccurred != "true") {
let bundleId = Bundle.main.bundleIdentifier ?? ""
let queryDict = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "\(bundleId).dropbox.authv2" as AnyObject?]
let attributesToUpdateDict = [kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]
SecItemUpdate(queryDict as CFDictionary, attributesToUpdateDict as CFDictionary)
UserDefaults.standard.set("true", forKey: kAccessibilityMigrationOccurredKey)
}
}
}
class Reachability {
/// From http://stackoverflow.com/questions/25623272/how-to-use-scnetworkreachability-in-swift/25623647#25623647.
///
/// This method uses `SCNetworkReachabilityCreateWithAddress` to create a reference to monitor the example host
/// defined by our zeroed `zeroAddress` struct. From this reference, we can extract status flags regarding the
/// reachability of this host, using `SCNetworkReachabilityGetFlags`.
class func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}