This repository has been archived by the owner on Apr 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenHandler.swift
190 lines (174 loc) · 8.74 KB
/
TokenHandler.swift
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//
// TokenHandler.swift
// mobile
//
// Created by cb on 06.09.23.
//
import Foundation
class TokenHandler {
// TODO: SWITCH TO APINET
/// Fetches a refresh token using an email and password.
///
/// This function initiates a network request to obtain a refresh token using the provided email and password.
/// It constructs the request URL with the refresh token endpoint, sends the email and password in the request body,
/// and processes the response to extract the refresh token.
///
/// - Parameters:
/// - email: The user's email for authentication.
/// - password: The user's password for authentication.
/// - completion: A closure that receives a `Result` containing either an `APIResponse` with the refresh token or an API error.
///
/// Example usage:
///
/// let email = "[email protected]"
/// let password = "secret_password"
///
/// TokenHandler.fetchRefreshToken(email: email, password: password) { result in
/// switch result {
/// case .success(let response):
/// // Handle successful refresh token retrieval (e.g., store the refresh token securely)
/// print("Refresh Token: \(response.message)")
/// case .failure(let error):
/// // Handle API error (e.g., display error message to the user)
/// print("API Error: \(error)")
/// }
/// }
///
/// - SeeAlso: `APIResponse` for the response data structure.
/// - SeeAlso: `APIError` for the possible API error types.
/// - SeeAlso: `Result` for the result type that contains either the decoded response data or an API error.
static func fetchRefreshToken(email: String, password: String, completion: @escaping (Result<APIResponse, APIError>) -> Void) {
print("Started fetchRefreshToken")
guard let url = URL(string: Routes.ROOT_URL + Routes.RT_PATH) else {
completion(.failure(.invalidURL))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let requestBody = ["refresh_token": ["email": email, "password": password]]
do {
let jsonData = try JSONSerialization.data(withJSONObject: requestBody)
request.httpBody = jsonData
} catch {
print("Error serializing JSON: \(error)")
}
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error fetching data: \(error)")
completion(.failure(.networkError(error)))
return
}
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
print("HTTP Response Code: \(statusCode)")
if statusCode == 200 { // Check if the response code is 200 (OK)
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print("json = \(json)")
if let jsonDict = json as? [String: Any],
let refreshTokenValue = jsonDict["refresh_token"] as? String {
// Successfully extracted refresh token value
completion(.success(APIResponse(message: refreshTokenValue)))
} else {
completion(.failure(.jsonParsingError(NSError(domain: "JSON Parsing Error", code: 0, userInfo: nil))))
}
} catch { // JSON parsing error
completion(.failure(.jsonParsingError(error)))
}
}
} else { // Handle non-200 response codes
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print("Error JSON = \(json)")
RequestHandler.handleApiErrors(json: json, errorKeys: ["error", "validity", "email|password", "email||password", "user"], statusCode: statusCode, completion: completion)
} catch {
completion(.failure(.jsonParsingError(error)))
}
} else {
completion(.failure(APIError.unknownError))
}
}
}
}.resume()
}
// TODO: SWITCH TO APINET
/// Fetches a new access token using a refresh token.
///
/// This function initiates a network request to obtain a new access token using a provided refresh token.
/// It constructs the request URL with the access token endpoint and sends the refresh token in the request header.
/// The response is processed, and the result is returned in the completion closure.
///
/// - Parameters:
/// - refreshToken: The refresh token used to obtain a new access token.
/// - completion: A closure that receives a `Result` containing either an `APIResponse` with the new access token or an API error.
///
/// Example usage:
///
/// let refreshToken = "your_refresh_token"
///
/// TokenHandler.fetchAccessToken(refreshToken: refreshToken) { result in
/// switch result {
/// case .success(let response):
/// // Handle successful token retrieval (e.g., update user's access token)
/// print("New Access Token: \(response.message)")
/// case .failure(let error):
/// // Handle API error (e.g., display error message to the user)
/// print("API Error: \(error)")
/// }
/// }
///
/// - SeeAlso: `APIResponse` for the response data structure.
/// - SeeAlso: `APIError` for the possible API error types.
/// - SeeAlso: `Result` for the result type that contains either the decoded response data or an API error.
static func fetchAccessToken(refreshToken: String, completion: @escaping (Result<APIResponse, APIError>) -> Void) {
print("Started fetchAccessToken with: \nrefreshToken: \(refreshToken)")
guard let url = URL(string: Routes.ROOT_URL + Routes.AT_PATH) else {
completion(.failure(.invalidURL))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue(refreshToken, forHTTPHeaderField: "refresh_token")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error fetching data: \(error)")
completion(.failure(.networkError(error)))
return
}
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
print("HTTP Response Code: \(statusCode)")
if statusCode == 200 { // Check if the response code is 200 (OK)
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print("json = \(json)")
if let jsonDict = json as? [String: Any],
let accessTokenValue = jsonDict["access_token"] as? String {
// Successfully extracted access token value
completion(.success(APIResponse(message: accessTokenValue)))
}
} catch { // JSON parsing error
completion(.failure(.jsonParsingError(error)))
}
}
} else { // Handle non-200 response codes
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print("Error JSON = \(json)")
RequestHandler.handleApiErrors(json: json, errorKeys: ["error", "token", "user"], statusCode: statusCode, completion: completion)
} catch {
completion(.failure(.jsonParsingError(error)))
}
} else {
completion(.failure(APIError.unknownError))
}
}
}
}.resume()
}
}