@@ -223,6 +223,22 @@ struct DFAPI {
223
223
selectedServer. token = token
224
224
}
225
225
226
+ @MainActor
227
+ private func handleAuthResponse( response: HTTPURLResponse , url: URL , selectedServer: DjangoFilesSession , token: String ) {
228
+ // Extract cookies from response
229
+ if let headerFields = response. allHeaderFields as? [ String : String ] {
230
+ let cookies = HTTPCookie . cookies ( withResponseHeaderFields: headerFields, for: url)
231
+ // Store cookies in the shared cookie storage
232
+ cookies. forEach { cookie in
233
+ HTTPCookieStorage . shared. setCookie ( cookie)
234
+ }
235
+ selectedServer. cookies = cookies
236
+ }
237
+
238
+ // Update the token in the server object
239
+ selectedServer. token = token
240
+ }
241
+
226
242
public func localLogin( username: String , password: String , selectedServer: DjangoFilesSession ) async -> Bool {
227
243
let request = DFLocalLoginRequest ( username: username, password: password)
228
244
do {
@@ -244,20 +260,11 @@ struct DFAPI {
244
260
throw URLError ( . badServerResponse)
245
261
}
246
262
247
- // Extract cookies from response
248
- if let headerFields = httpResponse. allHeaderFields as? [ String : String ] {
249
- let cookies = HTTPCookie . cookies ( withResponseHeaderFields: headerFields, for: urlRequest. url!)
250
- // Store cookies in the shared cookie storage
251
- cookies. forEach { cookie in
252
- HTTPCookieStorage . shared. setCookie ( cookie)
253
- }
254
- await updateSessionCookies ( selectedServer, cookies)
255
- }
263
+ let userToken = try decoder. decode ( UserToken . self, from: data)
256
264
257
- let userToken = try JSONDecoder ( ) . decode ( UserToken . self, from: data)
265
+ // Use shared function to handle cookies and token
266
+ await handleAuthResponse ( response: httpResponse, url: urlRequest. url!, selectedServer: selectedServer, token: userToken. token)
258
267
259
- // Update the token in the server object
260
- await updateSessionToken ( selectedServer, userToken. token)
261
268
return true
262
269
} catch {
263
270
print ( " Local login request failed \( error) " )
@@ -284,7 +291,6 @@ struct DFAPI {
284
291
if let url = urlRequest. url {
285
292
// Set the cookie directly in the request header
286
293
urlRequest. setValue ( " sessionid= \( sessionKey) " , forHTTPHeaderField: " Cookie " )
287
- //print("Using session key cookie: \(sessionKey) on \(url)")
288
294
289
295
// Also set it in the cookie storage
290
296
let cookieProperties : [ HTTPCookiePropertyKey : Any ] = [
@@ -298,7 +304,6 @@ struct DFAPI {
298
304
299
305
if let cookie = HTTPCookie ( properties: cookieProperties) {
300
306
HTTPCookieStorage . shared. setCookie ( cookie)
301
- // print("Set cookie: \(cookie)")
302
307
}
303
308
}
304
309
@@ -307,48 +312,17 @@ struct DFAPI {
307
312
configuration. httpCookieStorage = . shared
308
313
configuration. httpCookieAcceptPolicy = . always
309
314
310
- // Print all cookies before making the request
311
- // print("Cookies before request:")
312
- // HTTPCookieStorage.shared.cookies?.forEach { cookie in
313
- // print(" - \(cookie.name): \(cookie.value)")
314
- // }
315
-
316
315
let session = URLSession ( configuration: configuration)
317
316
let ( _, response) = try await session. data ( for: urlRequest)
318
317
319
- // print("response: \(response)")
320
-
321
318
guard let httpResponse = response as? HTTPURLResponse ,
322
319
httpResponse. statusCode == 200 else {
323
320
print ( " Request failed with status: \( ( response as? HTTPURLResponse ) ? . statusCode ?? - 1 ) " )
324
321
throw URLError ( . badServerResponse)
325
322
}
326
323
327
- // Print request headers for debugging
328
- // print("Request headers:")
329
- // urlRequest.allHTTPHeaderFields?.forEach { key, value in
330
- // print(" - \(key): \(value)")
331
- // }
332
-
333
- // Print response headers for debugging
334
- // print("Response headers:")
335
- // (response as? HTTPURLResponse)?.allHeaderFields.forEach { key, value in
336
- // print(" - \(key): \(value)")
337
- // }
338
-
339
- // Extract cookies from response
340
- if let headerFields = httpResponse. allHeaderFields as? [ String : String ] {
341
- let cookies = HTTPCookie . cookies ( withResponseHeaderFields: headerFields, for: urlRequest. url!)
342
- // Store cookies in the shared cookie storage
343
- cookies. forEach { cookie in
344
- HTTPCookieStorage . shared. setCookie ( cookie)
345
- // print("Received cookie from response: \(cookie)")
346
- }
347
- await updateSessionCookies ( selectedServer, cookies)
348
- }
349
-
350
- // Update the token in the server object using the MainActor method
351
- await updateSessionToken ( selectedServer, token)
324
+ // Use shared function to handle cookies and token
325
+ await handleAuthResponse ( response: httpResponse, url: urlRequest. url!, selectedServer: selectedServer, token: token)
352
326
353
327
return true
354
328
} catch {
@@ -396,21 +370,35 @@ struct DFAPI {
396
370
let token : String
397
371
}
398
372
399
- public func applicationAuth( signature: String ) async -> String ? {
373
+ public func applicationAuth( signature: String , selectedServer : DjangoFilesSession ? = nil ) async -> String ? {
400
374
let request = DFApplicationAuthRequest ( signature: signature)
401
375
do {
402
376
let json = try JSONEncoder ( ) . encode ( request)
403
- print ( json)
404
- print ( " JSON Data: \( String ( data: json, encoding: . utf8) ?? " invalid json " ) " )
405
- let responseBody = try await makeAPIRequest (
406
- body: json,
407
- path: getAPIPath ( . auth_application) ,
408
- parameters: [ : ] ,
409
- method: . post,
410
- headerFields: [ . contentType: " application/json " ]
411
- )
412
- let response = try decoder. decode ( DFApplicationAuthResponse . self, from: responseBody)
413
- return response. token
377
+
378
+ // Create URL request manually to access response headers
379
+ var urlRequest = URLRequest ( url: encodeParametersIntoURL ( path: getAPIPath ( . auth_application) , parameters: [ : ] ) )
380
+ urlRequest. httpMethod = " POST "
381
+ urlRequest. setValue ( " application/json " , forHTTPHeaderField: " Content-Type " )
382
+ urlRequest. httpBody = json
383
+
384
+ // Use default session configuration which persists cookies
385
+ let configuration = URLSessionConfiguration . default
386
+ let session = URLSession ( configuration: configuration)
387
+ let ( data, response) = try await session. data ( for: urlRequest)
388
+
389
+ guard let httpResponse = response as? HTTPURLResponse ,
390
+ httpResponse. statusCode == 200 else {
391
+ throw URLError ( . badServerResponse)
392
+ }
393
+
394
+ let auth_response = try decoder. decode ( DFApplicationAuthResponse . self, from: data)
395
+
396
+ // Use shared function to handle cookies and token if server is provided
397
+ if let selectedServer = selectedServer {
398
+ await handleAuthResponse ( response: httpResponse, url: urlRequest. url!, selectedServer: selectedServer, token: auth_response. token)
399
+ }
400
+
401
+ return auth_response. token
414
402
} catch {
415
403
print ( " Application auth request failed \( error) " )
416
404
return nil
0 commit comments