diff --git a/pocloud/Controller/LoginViewController.swift b/pocloud/Controller/LoginViewController.swift index 90ae0e2..f97ff33 100644 --- a/pocloud/Controller/LoginViewController.swift +++ b/pocloud/Controller/LoginViewController.swift @@ -61,31 +61,23 @@ class LoginViewController: UIViewController { let password = passwordField.text! let tokenPart = "\(email):\(password)".toBase64() let authToken = "Basic \(tokenPart)" + var user = User() firstly { appAuth.fetchCurrentUser(authToken: authToken) - }.done { (fetchedUser) in + }.then { (fetchedUser: User) -> Promise in + user = fetchedUser (UIApplication.shared.delegate as! AppDelegate).user = fetchedUser - Auth.auth().signIn(withEmail: email, password: password, completion: { (loginUser, loginError) in - if loginError != nil { - print("Error signing in: \(loginError!)") - Auth.auth().createUser(withEmail: email, password: password, completion: { (createUser, createError) in - if createError != nil { - print("Error creating user: \(createError!)") - SVProgressHUD.dismiss() - SVProgressHUD.showError(withStatus: "Authentication Error in Firebase") - } else { - self.firebaseLoginSuccess(fbUser: createUser!, meshifyUser: fetchedUser) - } - }) - } else { - self.firebaseLoginSuccess(fbUser: loginUser!, meshifyUser: fetchedUser) - } + return self.appAuth.getFirebaseToken(email: email, apiKey: authToken) + }.done { token in + Auth.auth().signIn(withCustomToken: token, completion: { (tokenUser, error) in + self.firebaseLoginSuccess(fbUser: tokenUser!, meshifyUser: user) }) - }.catch { _ in + }.catch { error in SVProgressHUD.dismiss() - SVProgressHUD.showError(withStatus: "Bad Login") + print(error.localizedDescription) + SVProgressHUD.showError(withStatus: error.localizedDescription) } } diff --git a/pocloud/Model/AppAuth.swift b/pocloud/Model/AppAuth.swift index d17e626..b136359 100644 --- a/pocloud/Model/AppAuth.swift +++ b/pocloud/Model/AppAuth.swift @@ -89,4 +89,22 @@ class AppAuth { } + func getFirebaseToken(email : String, apiKey : String) -> Promise{ + let urlApiKey = apiKey.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) + let url = "https://us-central1-pocloud-ff2c9.cloudfunctions.net/getAuthToken?email=\(email)&key=\(urlApiKey!)" + return Promise { promise in + Alamofire.request(url, method: .get) + .validate() + .responseJSON { response in + switch response.result { + case .success(let value): + let tokenJSON : JSON = JSON(value) + promise.fulfill(tokenJSON["token"].stringValue) + + case .failure(let error): + promise.reject(error) + } + } + } + } }