@@ -2,8 +2,8 @@ import AsyncHTTPClient
2
2
import Foundation
3
3
import NIO
4
4
5
- #if canImport(SwiftUI )
6
- import SwiftUI
5
+ #if canImport(AuthenticationServices )
6
+ import AuthenticationServices
7
7
#endif
8
8
9
9
///
@@ -13,12 +13,10 @@ import SwiftUI
13
13
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, visionOS 1.0, *)
14
14
public class WebAuthComponent {
15
15
16
- #if canImport(SwiftUI)
17
- @Environment(\.openURL)
18
- private static var openURL
19
- #endif
20
-
21
16
private static var callbacks = [String: (Result<String , {{ spec .title | caseUcfirst }}Error >) -> Void]()
17
+ #if canImport(AuthenticationServices)
18
+ private static var currentAuthSession: ASWebAuthenticationSession?
19
+ #endif
22
20
23
21
///
24
22
/// Authenticate Session with OAuth2
@@ -41,9 +39,29 @@ public class WebAuthComponent {
41
39
) {
42
40
callbacks[callbackScheme] = onComplete
43
41
44
- #if canImport(SwiftUI)
45
- openURL(url)
46
- #endif
42
+ #if canImport(AuthenticationServices)
43
+ currentAuthSession = ASWebAuthenticationSession(
44
+ url: url,
45
+ callbackURLScheme: callbackScheme
46
+ ) { callbackURL, error in
47
+ if let error = error {
48
+ cleanUp()
49
+ } else if let callbackURL = callbackURL {
50
+ // handle cookies here itself!
51
+ WebAuthComponent.handleIncomingCookie(from: callbackURL)
52
+ cleanUp()
53
+ }
54
+ }
55
+
56
+ if let session = currentAuthSession {
57
+ /// Indicates that the session should be a private session.
58
+ session.prefersEphemeralWebBrowserSession = true
59
+ session.presentationContextProvider = PresentationContextProvider.shared
60
+ session.start()
61
+ } else {
62
+ print("Failed to create ASWebAuthenticationSession")
63
+ }
64
+ #endif
47
65
}
48
66
49
67
///
@@ -130,5 +148,24 @@ public class WebAuthComponent {
130
148
callbacks.forEach { (_, callback) in
131
149
callback(.failure({{ spec .title | caseUcfirst }}Error(message: "User cancelled login.")))
132
150
}
151
+
152
+ #if canImport(AuthenticationServices)
153
+ currentAuthSession = nil
154
+ #endif
155
+ }
156
+ }
157
+
158
+ #if canImport(AuthenticationServices)
159
+ /// Presentation context for the ASWebAuthenticationSession.
160
+ class PresentationContextProvider: NSObject, ASWebAuthenticationPresentationContextProviding {
161
+ static let shared = PresentationContextProvider()
162
+
163
+ func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
164
+ if let mainWindow = OSApplication.shared.windows.first { $0.isKeyWindow } {
165
+ return mainWindow
166
+ }
167
+
168
+ return ASPresentationAnchor()
133
169
}
134
170
}
171
+ #endif
0 commit comments