97 lines
3.0 KiB
Swift
97 lines
3.0 KiB
Swift
//
|
|
// ViewController.swift
|
|
// pocloud
|
|
//
|
|
// Created by Patrick McDonagh on 5/22/18.
|
|
// Copyright © 2018 patrickjmcd. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
import Alamofire
|
|
import SwiftyJSON
|
|
import SVProgressHUD
|
|
import PromiseKit
|
|
import FirebaseAuth
|
|
|
|
extension String {
|
|
func fromBase64() -> String? {
|
|
guard let data = Data(base64Encoded: self) else {
|
|
return nil
|
|
}
|
|
return String(data: data, encoding: .utf8)
|
|
}
|
|
|
|
func toBase64() -> String {
|
|
return Data(self.utf8).base64EncodedString()
|
|
}
|
|
}
|
|
|
|
class LoginViewController: UIViewController {
|
|
|
|
let baseURL = (UIApplication.shared.delegate as! AppDelegate).baseURL
|
|
let user = (UIApplication.shared.delegate as! AppDelegate).user
|
|
|
|
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Auth.plist")
|
|
|
|
let appAuth = AppAuth()
|
|
|
|
@IBOutlet weak var emailField: UITextField!
|
|
@IBOutlet weak var passwordField: UITextField!
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
SVProgressHUD.show()
|
|
firstly {
|
|
appAuth.loadAuth()
|
|
}.done { loadedUser in
|
|
(UIApplication.shared.delegate as! AppDelegate).user = loadedUser
|
|
SVProgressHUD.dismiss()
|
|
SVProgressHUD.showSuccess(withStatus: "Found User!")
|
|
self.performSegue(withIdentifier: "logInSegue", sender: self)
|
|
}.catch { error in
|
|
SVProgressHUD.dismiss()
|
|
print("No stored user. \(error)")
|
|
}
|
|
|
|
}
|
|
|
|
@IBAction func signInButtonPressed(_ sender: UIButton) {
|
|
SVProgressHUD.show()
|
|
let email = emailField.text!
|
|
let password = passwordField.text!
|
|
let tokenPart = "\(email):\(password)".toBase64()
|
|
let authToken = "Basic \(tokenPart)"
|
|
var user = User()
|
|
|
|
|
|
firstly {
|
|
appAuth.fetchCurrentUser(authToken: authToken)
|
|
}.then { (fetchedUser: User) -> Promise<String> in
|
|
user = fetchedUser
|
|
(UIApplication.shared.delegate as! AppDelegate).user = 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 { error in
|
|
SVProgressHUD.dismiss()
|
|
print(error.localizedDescription)
|
|
SVProgressHUD.showError(withStatus: error.localizedDescription)
|
|
}
|
|
}
|
|
|
|
|
|
func firebaseLoginSuccess(fbUser : AuthDataResult, meshifyUser: User){
|
|
passwordField.text = ""
|
|
print("Successful login with \(fbUser)")
|
|
meshifyUser.fbUid = fbUser.user.uid
|
|
appAuth.saveAuth(user: meshifyUser)
|
|
SVProgressHUD.dismiss()
|
|
SVProgressHUD.showSuccess(withStatus: "Login Success")
|
|
self.performSegue(withIdentifier: "logInSegue", sender: self)
|
|
}
|
|
|
|
}
|
|
|