Files
POCloud-iOS/pocloud/Model/AppAuth.swift
Patrick McDonagh 25f862e1c5 Auth system converted to custom token
This allows for the case of when users change their passwords
2018-06-01 15:33:52 -05:00

111 lines
3.8 KiB
Swift

//
// AuthFunctions.swift
// pocloud
//
// Created by Patrick McDonagh on 6/1/18.
// Copyright © 2018 patrickjmcd. All rights reserved.
//
import Foundation
import FirebaseAuth
import PromiseKit
import Alamofire
import SwiftyJSON
class AppAuth {
let dataFilePath : URL
init() {
dataFilePath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Auth.plist"))!
}
func logOut(){
try? Auth.auth().signOut()
saveAuth(user: User())
}
func saveAuth(user : User){
(UIApplication.shared.delegate as! AppDelegate).user = user
let encoder = PropertyListEncoder()
do{
let data = try encoder.encode(user)
try data.write(to: dataFilePath)
} catch {
print("Error encoding item array, \(error)")
}
}
func loadAuth() -> Promise<User> {
return Promise { promise in
if let data = try? Data(contentsOf: dataFilePath) {
let decoder = PropertyListDecoder()
do {
let storedUser = try decoder.decode(User.self, from: data)
firstly {
fetchCurrentUser(authToken: storedUser.authToken)
}.done { currentUser in
promise.fulfill(currentUser)
}.catch { (error) in
promise.reject(error)
}
} catch {
promise.reject(error)
}
}
}
}
func fetchCurrentUser(authToken: String) -> Promise<User> {
let baseURL = (UIApplication.shared.delegate as! AppDelegate).baseURL
let url = "\(baseURL)/users/me"
let headers : HTTPHeaders = [
"Authorization": authToken
]
return Promise<User> { prom in
Alamofire.request(url, method: .get, headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
let userJSON : JSON = JSON(value)
let thisUser = User()
thisUser.userId = userJSON["userId"].intValue
thisUser.first = userJSON["first"].stringValue
thisUser.last = userJSON["last"].stringValue
thisUser.phone = userJSON["phone"].stringValue
thisUser.addressId = userJSON["addressId"].intValue
thisUser.companyId = userJSON["companyId"].intValue
thisUser.email = userJSON["email"].stringValue
thisUser.authToken = authToken
prom.fulfill(thisUser)
case .failure(let error):
prom.reject(error)
}
}
}
}
func getFirebaseToken(email : String, apiKey : String) -> Promise<String>{
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)
}
}
}
}
}