Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // PasswordManager.swift
- // AeroBuddy
- //
- // Created by Luke Collister on 12/11/2019.
- // Copyright © 2019 Luke Collister. All rights reserved.
- //
- import Foundation
- class ServHandler {
- static let shared = ServHandler() // singleton instance
- static let connectProtocol = "http"
- static let baseURL = "fe01.kilosierracharlie.me"
- static let emailValidator = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
- private var loggedInUser: String
- private lazy var protectionSpace: URLProtectionSpace = {
- return URLProtectionSpace(host: ServHandler.baseURL,
- port: 0,
- protocol: ServHandler.connectProtocol,
- realm: nil,
- authenticationMethod: nil)
- }()
- private init() { }
- func password(for userID: String) -> String? {
- guard let credentials = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return nil }
- return credentials[userID]?.password
- }
- func set(password: String, for userID: String) {
- let credential = URLCredential(user: userID, password: password, persistence: .permanent)
- URLCredentialStorage.shared.set(credential, for: protectionSpace)
- loggedInUser = userID
- }
- func checkCredentials( password: String, for userID: String, completion: @escaping (Bool) -> Bool ) {
- let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", ServHandler.emailValidator)
- if( password.count > 3 && emailTest.evaluate(with: userID) ){
- set(password: password, for: userID)
- let url = URL(string: "\(ServHandler.connectProtocol)://\(ServHandler.baseURL)/user")!
- let config = URLSessionConfiguration.default
- let session = URLSession(configuration: config)
- let task = session.dataTask(with: url) { (data, response, error) in
- guard error == nil else {
- completion(false)
- return
- }
- if let httpStatus = response as? HTTPURLResponse {
- if httpStatus.statusCode == 200 {
- completion(true)
- }
- completion(false)
- }
- }
- task.resume()
- }
- }
- func clear(for userID: String) {
- guard let creds = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return }
- guard let cred = creds[userID] else { return }
- URLCredentialStorage.shared.remove(cred, for: protectionSpace)
- }
- func logout() {
- if(loggedInUser == nil){ return }
- clear(for: loggedInUser)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement