<commit_before>
import Foundation
import UIKit
import Alamofire
import KeychainAccess

let kOAuth2AccessTokenService: String = "OAuth2AccessToken"
let kOAuth2RefreshTokenService: String = "OAuth2RefreshToken"
let kOAuth2ExpiresInService: String = "OAuth2ExpiresIn"
let kOAuth2CreationDateService: String = "OAuth2CreationDate"

class OAuth2Client : NSObject {
    
    var oauth2Settings:Oauth2Settings
    var sourceViewController:UIViewController?
    let keychain:  Keychain
    
    init(outh2Settings: Oauth2Settings) {
        self.oauth2Settings = outh2Settings
        self.keychain = Keychain(service: outh2Settings.baseURL)
    }
    
    private func postRequestHandler(jsonResponse:AnyObject?, error:ErrorType?, token:((accessToken:String?) -> Void)) -> Void {
        if let err = error {
            print(err)
            token(accessToken: nil)
        } else {
            let accessToken:String = self.retrieveAccessTokenFromJSONResponse(jsonResponse!)
            token(accessToken: accessToken)
        }
    }
    
    func retrieveAuthToken(token:((accessToken:String?) -> Void)) -> Void {
        
        // We found a token in the keychain, we need to check if it is not expired            
        if let optionalStoredAccessToken:String = self.retrieveAccessTokenFromKeychain() {
            if (self.isAccessTokenExpired()) {
                if let refreshToken = self.retrieveRefreshTokenFromKeychain() {
                    self.refreshToken(refreshToken, newToken: token)
                    return
                }
                print("WARNING: Access token is expired but no refresh token in keychain!")
            } else {
                token(accessToken: optionalStoredAccessToken)
                return
            }
        }
        
        // First, let's retrieve the autorization_code by login the user in.
        self.retrieveAuthorizationCode ({ (authorizationCode) -> Void in
            if let optionalAuthCode = authorizationCode {
                // We have the authorization_code, we now need to exchange it for the accessToken by doind a POST request
                let url:String = self.oauth2Settings.tokenURL
                
                let parameters: [String:String] = ["client_id" : self.oauth2Settings.clientID,
                    "grant_type" : "authorization_code",
                    "client_secret" : self.oauth2Settings.clientSecret,
                    "redirect_uri" : self.oauth2Settings.redirectURL,
                    "code" : optionalAuthCode]
                
                Alamofire.request(.POST,
                    url, 
                    parameters: parameters,
                    encoding: Alamofire.ParameterEncoding.URL)
                    .responseJSON(completionHandler: { (response) -> Void in
                        switch response.result {
                        case .Success(let json):
                            self.postRequestHandler(json, error: nil, token: token)
                        case .Failure(let error):
                            self.postRequestHandler(nil, error: error, token: token)
                        }
                    })
                
                    
//                    .responseJSON { (request, response, result ) -> Void in
//                        self.postRequestHandler(result.value, error: result.error, token: token)
//                }
            }
        })
    }
    
    // MARK: - Private helper methods
    
    var activeController: UIViewController {
        get {
            if self.sourceViewController == nil {
                self.sourceViewController = UIApplication.topViewController()
            }
            if self.sourceViewController != nil {
                return self.sourceViewController!
            }
            print("WARNING: You should have an active UIViewController! ")
            return UIViewController()
        }
    }

    // Retrieves the autorization code by presenting a webView that will let the user login
    private func retrieveAuthorizationCode(authoCode:((authorizationCode:String?) -> Void)) -> Void{
        
        func success(code:String) -> Void {
            activeController.dismissViewControllerAnimated(true, completion: nil)
            authoCode(authorizationCode:code)
        }
        
        func failure(error:NSError) -> Void {<commit_msg>Fix to manage a nil access token callback error. This for example happens when in the Linkedin login form the user insert a mail and add a space at the end. The oauth fails, the token is null, but the OAuth2Client class don't call the error clousure, so the error couldn't be managed from the app usign this lib.<commit_after>
import Foundation
import UIKit
import Alamofire
import KeychainAccess

let kOAuth2AccessTokenService: String = "OAuth2AccessToken"
let kOAuth2RefreshTokenService: String = "OAuth2RefreshToken"
let kOAuth2ExpiresInService: String = "OAuth2ExpiresIn"
let kOAuth2CreationDateService: String = "OAuth2CreationDate"

class OAuth2Client : NSObject {
    
    var oauth2Settings:Oauth2Settings
    var sourceViewController:UIViewController?
    let keychain:  Keychain
    
    init(outh2Settings: Oauth2Settings) {
        self.oauth2Settings = outh2Settings
        self.keychain = Keychain(service: outh2Settings.baseURL)
    }
    
    private func postRequestHandler(jsonResponse:AnyObject?, error:ErrorType?, token:((accessToken:String?) -> Void)) -> Void {
        if let err = error {
            print(err)
            token(accessToken: nil)
        } else {
            let accessToken:String = self.retrieveAccessTokenFromJSONResponse(jsonResponse!)
            token(accessToken: accessToken)
        }
    }
    
    func retrieveAuthToken(token:((accessToken:String?) -> Void)) -> Void {
        
        // We found a token in the keychain, we need to check if it is not expired            
        if let optionalStoredAccessToken:String = self.retrieveAccessTokenFromKeychain() {
            if (self.isAccessTokenExpired()) {
                if let refreshToken = self.retrieveRefreshTokenFromKeychain() {
                    self.refreshToken(refreshToken, newToken: token)
                    return
                }
                print("WARNING: Access token is expired but no refresh token in keychain!")
            } else {
                token(accessToken: optionalStoredAccessToken)
                return
            }
        }
        
        // First, let's retrieve the autorization_code by login the user in.
        self.retrieveAuthorizationCode ({ (authorizationCode) -> Void in
            if let optionalAuthCode = authorizationCode {
                // We have the authorization_code, we now need to exchange it for the accessToken by doind a POST request
                let url:String = self.oauth2Settings.tokenURL
                
                let parameters: [String:String] = ["client_id" : self.oauth2Settings.clientID,
                    "grant_type" : "authorization_code",
                    "client_secret" : self.oauth2Settings.clientSecret,
                    "redirect_uri" : self.oauth2Settings.redirectURL,
                    "code" : optionalAuthCode]
                
                Alamofire.request(.POST,
                    url, 
                    parameters: parameters,
                    encoding: Alamofire.ParameterEncoding.URL)
                    .responseJSON(completionHandler: { (response) -> Void in
                        switch response.result {
                        case .Success(let json):
                            self.postRequestHandler(json, error: nil, token: token)
                        case .Failure(let error):
                            self.postRequestHandler(nil, error: error, token: token)
                        }
                    })
                
                    
//                    .responseJSON { (request, response, result ) -> Void in
//                        self.postRequestHandler(result.value, error: result.error, token: token)
//                }
            }
            else {
                token(accessToken: nil)
            }
        })
    }
    
    // MARK: - Private helper methods
    
    var activeController: UIViewController {
        get {
            if self.sourceViewController == nil {
                self.sourceViewController = UIApplication.topViewController()
            }
            if self.sourceViewController != nil {
                return self.sourceViewController!
            }
            print("WARNING: You should have an active UIViewController! ")
            return UIViewController()
        }
    }

    // Retrieves the autorization code by presenting a webView that will let the user login
    private func retrieveAuthorizationCode(authoCode:((authorizationCode:String?) -> Void)) -> Void{
        
        func success(code:String) -> Void {
            activeController.dismissViewControllerAnimated(true, completion: nil)
            authoCode(authorizationCode:code)
        }
        
        func failure(error:NSError) -> Void {
{'fraction_non_alphanumeric': 0.07404563405002194, 'fraction_numerical': 0.004497586660816147, 'mean_word_length': 1.8340068386695678, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4208388', 'n_tokens_mistral': 2293, 'n_tokens_neox': 2161, 'n_words': 577}