Skip to content

Commit

Permalink
Fix OAuthSwift#262 don't crash if OAuthSwift object not retain. Inste…
Browse files Browse the repository at this point in the history
…ad call failure callback

Cleaning on NSError creation
  • Loading branch information
phimage committed Aug 19, 2016
1 parent 1240f6b commit 33c8ba1
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 41 deletions.
28 changes: 15 additions & 13 deletions OAuthSwift/OAuth1Swift.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public class OAuth1Swift: OAuthSwift {
credential, response, _ in

self.observeCallback { [weak self] url in
guard let this = self else {return }
guard let this = self else { OAuthSwift.retainError(failure); return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString()
Expand All @@ -78,8 +78,8 @@ public class OAuth1Swift: OAuthSwift {
}
this.postOAuthAccessTokenWithRequestToken(success, failure: failure)
} else {
let userInfo = [NSLocalizedDescriptionKey: "Oauth problem. oauth_token or oauth_verifier not returned"]
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: userInfo))
let message = this.allowMissingOauthVerifier ? "Oauth problem. oauth_token not returned" : "Oauth problem. oauth_token or oauth_verifier not returned"
failure?(error: NSError(code: .MissingTokenOrVerifier, message: message))
return
}
}
Expand All @@ -89,8 +89,8 @@ public class OAuth1Swift: OAuthSwift {
self.authorize_url_handler.handle(queryURL)
}
else {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Failed to create URL", comment: "\(urlString) not convertible to URL, please encode.")]
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: errorInfo))
let message = NSLocalizedString("Failed to create URL", comment: "\(urlString) not convertible to URL, please encode.")
failure?(error: NSError(code: .EncodingError, message: message))
}
}, failure: failure)
}
Expand All @@ -102,16 +102,17 @@ public class OAuth1Swift: OAuthSwift {
parameters["oauth_callback"] = callbackURLString
}
self.client.post(self.request_token_url, parameters: parameters, success: {
[unowned self] data, response in
[weak self] data, response in
guard let this = self else { OAuthSwift.retainError(failure); return }
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String!
let parameters = responseString.parametersFromQueryString()
if let oauthToken=parameters["oauth_token"] {
self.client.credential.oauth_token = oauthToken.safeStringByRemovingPercentEncoding
this.client.credential.oauth_token = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret=parameters["oauth_token_secret"] {
self.client.credential.oauth_token_secret = oauthTokenSecret.safeStringByRemovingPercentEncoding
this.client.credential.oauth_token_secret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
success(credential: self.client.credential, response: response, parameters: parameters)
success(credential: this.client.credential, response: response, parameters: parameters)
}, failure: failure)
}

Expand All @@ -121,16 +122,17 @@ public class OAuth1Swift: OAuthSwift {
parameters["oauth_token"] = self.client.credential.oauth_token
parameters["oauth_verifier"] = self.client.credential.oauth_verifier
self.client.post(self.access_token_url, parameters: parameters, success: {
[unowned self] data, response in
[weak self] data, response in
guard let this = self else { OAuthSwift.retainError(failure); return }
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String!
let parameters = responseString.parametersFromQueryString()
if let oauthToken=parameters["oauth_token"] {
self.client.credential.oauth_token = oauthToken.safeStringByRemovingPercentEncoding
this.client.credential.oauth_token = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret=parameters["oauth_token_secret"] {
self.client.credential.oauth_token_secret = oauthTokenSecret.safeStringByRemovingPercentEncoding
this.client.credential.oauth_token_secret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
success(credential: self.client.credential, response: response, parameters: parameters)
success(credential: this.client.credential, response: response, parameters: parameters)
}, failure: failure)
}

Expand Down
37 changes: 16 additions & 21 deletions OAuthSwift/OAuth2Swift.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ public class OAuth2Swift: OAuthSwift {
}

// MARK: functions
public func authorizeWithCallbackURL(callbackURL: NSURL, scope: String, state: String, params: [String: String] = [String: String](), headers: [String:String]? = nil, success: TokenSuccessHandler, failure: ((error: NSError) -> Void)) {
public func authorizeWithCallbackURL(callbackURL: NSURL, scope: String, state: String, params: [String: String] = [String: String](), headers: [String:String]? = nil, success: TokenSuccessHandler, failure: FailureHandler) {

self.observeCallback { [weak self] url in
guard let this = self else {return }
self.observeCallback { [weak self] url in
guard let this = self else { OAuthSwift.retainError(failure); return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString()
Expand All @@ -91,26 +91,24 @@ public class OAuth2Swift: OAuthSwift {
else if let code = responseParameters["code"] {
if !this.allowMissingStateCheck {
guard let responseState = responseParameters["state"] else {
let errorInfo = [NSLocalizedDescriptionKey: "Missing state"]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.MissingStateError.rawValue, userInfo: errorInfo))
failure(error: NSError(code: .MissingStateError, message: "Missing state", errorKey: NSLocalizedDescriptionKey))
return
}
if responseState != state {
let errorInfo = [NSLocalizedDescriptionKey: "state not equals"]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.StateNotEqualError.rawValue, userInfo: errorInfo))
failure(error: NSError(code: .StateNotEqualError, message: "state not equals", errorKey: NSLocalizedDescriptionKey))
return
}
}
this.postOAuthAccessTokenWithRequestTokenByCode(code.safeStringByRemovingPercentEncoding,
callbackURL:callbackURL, headers: headers , success: success, failure: failure)
}
else if let error = responseParameters["error"], error_description = responseParameters["error_description"] {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString(error, comment: error_description)]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.GeneralError.rawValue, userInfo: errorInfo))
let message = NSLocalizedString(error, comment: error_description)
failure(error: NSError(code: .GeneralError, message: message))
}
else {
let errorInfo = [NSLocalizedDescriptionKey: "No access_token, no code and no error provided by server"]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.ServerError.rawValue, userInfo: errorInfo))
let message = "No access_token, no code and no error provided by server"
failure(error: NSError(code: .ServerError, message: message, errorKey: NSLocalizedDescriptionKey))
}
}

Expand All @@ -135,8 +133,8 @@ public class OAuth2Swift: OAuthSwift {
self.authorize_url_handler.handle(queryURL)
}
else {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Failed to create URL", comment: "\(urlString) or \(queryString) not convertible to URL, please check encoding")]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.EncodingError.rawValue, userInfo: errorInfo))
let message = NSLocalizedString("Failed to create URL", comment: "\(urlString) or \(queryString) not convertible to URL, please check encoding")
failure(error: NSError(code: .EncodingError, message: message))
}
}

Expand Down Expand Up @@ -176,10 +174,8 @@ public class OAuth2Swift: OAuthSwift {
}

guard let accessToken = responseParameters["access_token"] as? String else {
if let failure = failure {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.ServerError.rawValue, userInfo: errorInfo))
}
let message = NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")
failure?(error: NSError(code: .ServerError, message: message))
return
}
if let refreshToken = responseParameters["refresh_token"] as? String {
Expand All @@ -204,8 +200,7 @@ public class OAuth2Swift: OAuthSwift {
var headers: [String:String]? = nil
if accessTokenBasicAuthentification {
let authentification = "\(self.consumer_key):\(self.consumer_secret)".dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded = authentification?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
if let base64Encoded = authentification?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) {
headers = ["Authorization": "Basic \(base64Encoded)"]
}
}
Expand All @@ -214,8 +209,8 @@ public class OAuth2Swift: OAuthSwift {
self.client.request(access_token_url, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, success: successHandler, failure: failure)
}
else {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth")]
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.GeneralError.rawValue, userInfo: errorInfo))
let message = NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth")
failure?(error: NSError(code: .GeneralError, message: message))
}
}
}
Expand Down
19 changes: 19 additions & 0 deletions OAuthSwift/OAuthSwift.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,23 @@ public enum OAuthSwiftErrorCode: Int {
case EncodingError = -6
case AuthorizationPending = -7
case RequestCreationError = -8
case MissingTokenOrVerifier = -9
case RetainError = -10
}

extension NSError {
convenience init(code: OAuthSwiftErrorCode, message: String, errorKey: String = NSLocalizedFailureReasonErrorKey) {
let userInfo = [errorKey: message]
self.init(domain: OAuthSwiftErrorDomain, code: code.rawValue, userInfo: userInfo)
}
}

extension OAuthSwift {

static func retainError(failureHandler: FailureHandler?) {
#if !OAUTH_NO_RETAIN_ERROR
failureHandler?(error: NSError(code: .RetainError, message: "Please retain OAuthSwift object", errorKey: NSLocalizedDescriptionKey))
#endif
}

}
10 changes: 3 additions & 7 deletions OAuthSwift/OAuthSwiftClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,13 @@ public class OAuthSwiftClient: NSObject {
public func request(urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, body: NSData? = nil, checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {

if checkTokenExpiration && self.credential.isTokenExpired() {
let errorInfo = [NSLocalizedDescriptionKey: NSLocalizedString("The provided token is expired.", comment:"Token expired, retrieve new token by using the refresh token")]

if let failureHandler = failure {
failureHandler(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.TokenExpiredError.rawValue, userInfo: errorInfo))
}

let message = NSLocalizedString("The provided token is expired.", comment:"Token expired, retrieve new token by using the refresh token")
failure?(error: NSError(code: .TokenExpiredError, message: message, errorKey: NSLocalizedDescriptionKey))
return nil
}

guard let _ = NSURL(string: urlString) else {
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.RequestCreationError.rawValue, userInfo: nil))
failure?(error: NSError(code: .RequestCreationError, message: "Failed to create request with url \(urlString)"))
return nil
}

Expand Down

0 comments on commit 33c8ba1

Please sign in to comment.