This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathAtomicAuthenticationServiceRemote.swift
More file actions
82 lines (67 loc) · 2.85 KB
/
Copy pathAtomicAuthenticationServiceRemote.swift
File metadata and controls
82 lines (67 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import Foundation
public class AtomicAuthenticationServiceRemote: ServiceRemoteWordPressComREST {
public enum ResponseError: Error {
case responseIsNotADictionary(response: Any)
case decodingFailure(response: [String: AnyObject])
case couldNotInstantiateCookie(name: String, value: String, domain: String, path: String, expires: Date)
}
public func getAuthCookie(
siteID: Int,
success: @escaping (_ cookie: HTTPCookie) -> Void,
failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/atomic-auth-proxy/read-access-cookies"
let path = self.path(forEndpoint: endpoint, withVersion: ._2_0)
wordPressComRESTAPI.get(path,
parameters: nil,
success: { responseObject, _ in
do {
let settings = try self.cookie(from: responseObject)
success(settings)
} catch {
failure(error)
}
},
failure: { error, _ in
failure(error)
})
}
// MARK: - Result Parsing
private func date(from expiration: Int) -> Date {
return Date(timeIntervalSince1970: TimeInterval(expiration))
}
private func cookie(from responseObject: Any) throws -> HTTPCookie {
guard let response = responseObject as? [String: AnyObject] else {
let error = ResponseError.responseIsNotADictionary(response: responseObject)
WPKitLogError("❗️Error: \(error)")
throw error
}
guard let cookies = response["cookies"] as? [[String: Any]] else {
let error = ResponseError.decodingFailure(response: response)
WPKitLogError("❗️Error: \(error)")
throw error
}
let cookieDictionary = cookies[0]
guard let name = cookieDictionary["name"] as? String,
let value = cookieDictionary["value"] as? String,
let domain = cookieDictionary["domain"] as? String,
let path = cookieDictionary["path"] as? String,
let expires = cookieDictionary["expires"] as? Int else {
let error = ResponseError.decodingFailure(response: response)
WPKitLogError("❗️Error: \(error)")
throw error
}
let expirationDate = date(from: expires)
guard let cookie = HTTPCookie(properties: [
.name: name,
.value: value,
.domain: domain,
.path: path,
.expires: expirationDate
]) else {
let error = ResponseError.couldNotInstantiateCookie(name: name, value: value, domain: domain, path: path, expires: expirationDate)
WPKitLogError("❗️Error: \(error)")
throw error
}
return cookie
}
}