Advertisement
lcolli98

Untitled

Nov 12th, 2019
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. //
  2. // PasswordManager.swift
  3. // AeroBuddy
  4. //
  5. // Created by Luke Collister on 12/11/2019.
  6. // Copyright © 2019 Luke Collister. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. class ServHandler {
  12. static let shared = ServHandler() // singleton instance
  13. static let connectProtocol = "http"
  14. static let baseURL = "fe01.kilosierracharlie.me"
  15. static let emailValidator = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
  16. private var loggedInUser: String
  17. private lazy var protectionSpace: URLProtectionSpace = {
  18. return URLProtectionSpace(host: ServHandler.baseURL,
  19. port: 0,
  20. protocol: ServHandler.connectProtocol,
  21. realm: nil,
  22. authenticationMethod: nil)
  23. }()
  24. private init() { }
  25.  
  26. func password(for userID: String) -> String? {
  27. guard let credentials = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return nil }
  28. return credentials[userID]?.password
  29. }
  30.  
  31. func set(password: String, for userID: String) {
  32. let credential = URLCredential(user: userID, password: password, persistence: .permanent)
  33. URLCredentialStorage.shared.set(credential, for: protectionSpace)
  34. loggedInUser = userID
  35. }
  36.  
  37. func checkCredentials( password: String, for userID: String, completion: @escaping (Bool) -> Bool ) {
  38. let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", ServHandler.emailValidator)
  39. if( password.count > 3 && emailTest.evaluate(with: userID) ){
  40. set(password: password, for: userID)
  41. let url = URL(string: "\(ServHandler.connectProtocol)://\(ServHandler.baseURL)/user")!
  42.  
  43. let config = URLSessionConfiguration.default
  44. let session = URLSession(configuration: config)
  45. let task = session.dataTask(with: url) { (data, response, error) in
  46. guard error == nil else {
  47. completion(false)
  48. return
  49. }
  50. if let httpStatus = response as? HTTPURLResponse {
  51. if httpStatus.statusCode == 200 {
  52. completion(true)
  53. }
  54. completion(false)
  55. }
  56. }
  57. task.resume()
  58. }
  59. }
  60.  
  61. func clear(for userID: String) {
  62. guard let creds = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return }
  63. guard let cred = creds[userID] else { return }
  64. URLCredentialStorage.shared.remove(cred, for: protectionSpace)
  65. }
  66.  
  67. func logout() {
  68. if(loggedInUser == nil){ return }
  69. clear(for: loggedInUser)
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement