Skip to content

Commit

Permalink
Merge pull request #299 from mohssenfathi/token-manager-migration
Browse files Browse the repository at this point in the history
TokenManager, AccessToken migration
  • Loading branch information
mohssenfathi authored May 28, 2024
2 parents 8f927ed + 1586955 commit 4d4e46d
Show file tree
Hide file tree
Showing 18 changed files with 317 additions and 520 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public class BaseAuthenticator: UberAuthenticating {
public func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) {
if AuthenticationURLUtility.shouldHandleRedirectURL(url) {
do {
let accessToken = try AccessTokenFactory.createAccessToken(fromRedirectURL: url)
let accessToken = try AccessToken(redirectURL: url)

completion?(accessToken, nil)
} catch let error as NSError {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

import UIKit

public typealias AuthenticationCompletionHandler = (_ accessToken: AccessToken_DEPRECATED?, _ error: NSError?) -> Void
public typealias AuthenticationCompletionHandler = (_ accessToken: AccessToken?, _ error: NSError?) -> Void

/**
* Protocol to conform to for defining an authorization flow.
Expand Down
5 changes: 3 additions & 2 deletions Sources/UberCore/Authentication/LoginManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class LoginManager: LoginManaging, Identifiable, Equatable {
var willEnterForegroundCalled: Bool = false
private var postCompletionHandler: AuthenticationCompletionHandler?
private let urlSession = URLSession(configuration: .default)
private let tokenManager = TokenManager()

/**
Create instance of login manager to authenticate user and retreive access token.
Expand Down Expand Up @@ -460,7 +461,7 @@ public class LoginManager: LoginManaging, Identifiable, Equatable {
authenticator = nil
}

func loginCompletion(accessToken: AccessToken_DEPRECATED?, error: NSError?) {
func loginCompletion(accessToken: AccessToken?, error: NSError?) {
loggingIn = false
willEnterForegroundCalled = false
authenticator = nil
Expand All @@ -470,7 +471,7 @@ public class LoginManager: LoginManaging, Identifiable, Equatable {
if let accessToken = accessToken {
let tokenIdentifier = accessTokenIdentifier
let accessGroup = keychainAccessGroup
let success = TokenManager_DEPRECATED.save(accessToken: accessToken, tokenIdentifier: tokenIdentifier, accessGroup: accessGroup)
let success = tokenManager.saveToken(accessToken, identifier: tokenIdentifier)
if !success {
error = UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unableToSaveAccessToken)
print("Error: access token failed to save to keychain")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public protocol LoginManaging {
- parameter prefillValues: Optional values to pre-populate the signin form with.
- parameter completion: The LoginManagerRequestTokenHandler completion handler for login success/failure.
*/
func login(requestedScopes scopes: [UberScope], presentingViewController: UIViewController?, prefillValues: Prefill?, completion: ((_ accessToken: AccessToken_DEPRECATED?, _ error: NSError?) -> Void)?)
func login(requestedScopes scopes: [UberScope], presentingViewController: UIViewController?, prefillValues: Prefill?, completion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?)

/**
Called via the RidesAppDelegate when the application is opened via a URL. Responsible
Expand Down
86 changes: 82 additions & 4 deletions Sources/UberCore/Authentication/Tokens/AccessToken.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,15 @@ public struct AccessToken: Codable, Equatable {
let expiresIn = try container.decodeIfPresent(Int.self, forKey: .expiresIn)
let refreshToken = try container.decodeIfPresent(String.self, forKey: .refreshToken)

let scopeString = try container.decodeIfPresent(String.self, forKey: .scope)
let scope = (scopeString ?? "")
.split(separator: " ")
.map(String.init)
let scope: [String]?
if let scopeString = try? container.decodeIfPresent(String.self, forKey: .scope) {
scope = (scopeString ?? "")
.split(separator: " ")
.map(String.init)
}
else {
scope = try? container.decodeIfPresent([String].self, forKey: .scope)
}

self = AccessToken(
tokenString: tokenString,
Expand All @@ -86,6 +91,79 @@ public struct AccessToken: Codable, Equatable {
}
}

///
/// Initializers to build access tokens from various responses
///
extension AccessToken {

public init(jsonData: Data) throws {
guard let responseDictionary = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String: Any] else {
throw UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .invalidResponse)
}
self = try AccessToken(oAuthDictionary: responseDictionary)
}

/// Builds an AccessToken from the provided JSON data
///
/// - Throws: UberAuthenticationError
/// - Parameter jsonData: The JSON Data to parse the token from
/// - Returns: An initialized AccessToken
public init(oAuthDictionary: [String: Any]) throws {
guard let tokenString = oAuthDictionary["access_token"] as? String else {
throw UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .invalidResponse)
}
self.tokenString = tokenString
self.refreshToken = oAuthDictionary["refresh_token"] as? String
self.tokenType = oAuthDictionary["token_type"] as? String
self.expiresIn = {
if let expiresIn = oAuthDictionary["expires_in"] as? Int { return expiresIn }
if let expiresIn = oAuthDictionary["expires_in"] as? String,
let expiresInInt = Int(expiresIn) {
return expiresInInt
}
return 0
}()
self.scope = ((oAuthDictionary["scope"] as? String) ?? "")
.components(separatedBy: " ")
.flatMap { $0.components(separatedBy: "+") }
}

/// Builds an AccessToken from the provided redirect URL
///
/// - Throws: UberAuthenticationError
/// - Parameter url: The URL to parse the token from
/// - Returns: An initialized AccessToken, or nil if one couldn't be created
public init(redirectURL: URL) throws {
guard var components = URLComponents(url: redirectURL, resolvingAgainstBaseURL: false) else {
throw UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .invalidResponse)
}

var finalQueryArray = [String]()
if let existingQuery = components.query {
finalQueryArray.append(existingQuery)
}
if let existingFragment = components.fragment {
finalQueryArray.append(existingFragment)
}
components.fragment = nil
components.query = finalQueryArray.joined(separator: "&")

guard let queryItems = components.queryItems else {
throw UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .invalidRequest)
}
var queryDictionary = [String: Any]()
for queryItem in queryItems {
guard let value = queryItem.value else {
continue
}
queryDictionary[queryItem.name] = value
}

self = try AccessToken(oAuthDictionary: queryDictionary)
}
}


extension AccessToken: CustomStringConvertible {

public var description: String {
Expand Down
92 changes: 0 additions & 92 deletions Sources/UberCore/Authentication/Tokens/AccessTokenFactory.swift

This file was deleted.

148 changes: 0 additions & 148 deletions Sources/UberCore/Authentication/Tokens/AccessToken_DEPRECATED.swift

This file was deleted.

Loading

0 comments on commit 4d4e46d

Please sign in to comment.