-
Notifications
You must be signed in to change notification settings - Fork 31
Handle https callback url #524
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 4 commits
3bf1c55
d7557fb
5b30563
29a89f4
bb4f427
6c24b1f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,8 @@ | ||
| import AuthenticationServices | ||
|
|
||
| public struct OAuthSession: Sendable { | ||
| private static let shared = OAuthSession() | ||
| static let shared = OAuthSession() | ||
| private var emailStorage = SessionEmailStorage() | ||
|
|
||
| private let storage: SecureStorage | ||
| private let authenticationSession: AuthenticationSession | ||
|
|
@@ -54,25 +55,41 @@ public struct OAuthSession: Sendable { | |
| try? storage.secret(with: email.rawValue) | ||
| } | ||
|
|
||
| @discardableResult | ||
| func retrieveAccessToken(with email: Email) async throws -> KeychainToken { | ||
| func retrieveAccessToken(with email: Email) async throws { | ||
| guard let secrets = await Configuration.shared.oauthSecrets else { | ||
| assertionFailure("Trying to retrieve access token without configuring oauth secrets.") | ||
| throw OAuthError.notConfigured | ||
| } | ||
|
|
||
| await emailStorage.save(email) | ||
| do { | ||
| let url = try oauthURL(with: email, secrets: secrets) | ||
| let callbackURL = try await authenticationSession.authenticate(using: url, callbackURLScheme: secrets.callbackScheme) | ||
| let tokenText = try tokenResponse(from: callbackURL).token | ||
| _ = await Self.handleCallback(callbackURL) | ||
| } catch { | ||
| throw OAuthError.from(error: error) | ||
| } | ||
| } | ||
|
|
||
| public static func handleCallback(_ callbackURL: URL) async -> Bool { | ||
| guard let email = await shared.emailStorage.restore() else { return false } | ||
|
|
||
| do { | ||
| let tokenText = try shared.tokenResponse(from: callbackURL).token | ||
| guard try await CheckTokenAuthorizationService().isToken(tokenText, authorizedFor: email) else { | ||
| throw OAuthError.loggedInWithWrongEmail(email: email.rawValue) | ||
| } | ||
| let newToken = KeychainToken(token: tokenText) | ||
| overrideToken(newToken, for: email) | ||
| return newToken | ||
| shared.overrideToken(newToken, for: email) | ||
| await shared.authenticationSession.cancel() | ||
| NotificationCenter.default.post(name: .authorizationFinished, object: nil) | ||
| return true | ||
| } catch OAuthError.couldNotParseAccessCode(email.rawValue) { | ||
| return false // The URL was not a Gravatar callback URL with a token. | ||
| } catch { | ||
| throw OAuthError.from(error: error) | ||
| NotificationCenter.default.post(name: .authorizationError, object: error) | ||
| await shared.authenticationSession.cancel() | ||
|
||
| return true | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -216,6 +233,26 @@ extension [URLQueryItem] { | |
|
|
||
| protocol AuthenticationSession: Sendable { | ||
| func authenticate(using url: URL, callbackURLScheme: String) async throws -> URL | ||
| func cancel() async | ||
| } | ||
|
|
||
| extension OldAuthenticationSession: AuthenticationSession {} | ||
|
|
||
| // Stores the email used for the current OAuth flow | ||
| private actor SessionEmailStorage { | ||
| var current: Email? | ||
|
|
||
| func save(_ email: Email) { | ||
| current = email | ||
| } | ||
|
|
||
| func restore() -> Email? { | ||
| let currentEmail = current | ||
| return currentEmail | ||
| } | ||
| } | ||
|
|
||
| extension Notification.Name { | ||
| static let authorizationFinished = Notification.Name("com.GravatarSDK.AuthorizationFinished") | ||
| static let authorizationError = Notification.Name("com.GravatarSDK.AuthorizationFinishedWithError") | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -63,6 +63,19 @@ struct QuickEditor<ImageEditor: ImageEditorView>: View { | |
| noticeView() | ||
| .accumulateIntrinsicHeight() | ||
| } | ||
| }.onAppear { | ||
| NotificationCenter.default.addObserver(forName: .authorizationFinished, object: nil, queue: nil) { _ in | ||
| Task { @MainActor in | ||
| onAuthenticationFinished() | ||
| } | ||
| } | ||
| NotificationCenter.default.addObserver(forName: .authorizationError, object: nil, queue: nil) { notification in | ||
| guard let error = notification.object as? OAuthError else { return } | ||
| Task { @MainActor in | ||
| oauthError = error | ||
| onAuthenticationFinished() | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -131,8 +144,7 @@ struct QuickEditor<ImageEditor: ImageEditorView>: View { | |
| isAuthenticating = true | ||
| if !oauthSession.hasValidSession(with: email) { | ||
| do { | ||
| _ = try await oauthSession.retrieveAccessToken(with: email) | ||
| oauthError = nil | ||
| try await oauthSession.retrieveAccessToken(with: email) | ||
| } catch OAuthError.oauthResponseError(_, let code) where code == .canceledLogin { | ||
| // ignore the error if the user has cancelled the operation. | ||
| } catch let error as OAuthError { | ||
|
|
@@ -141,9 +153,16 @@ struct QuickEditor<ImageEditor: ImageEditorView>: View { | |
| oauthError = nil | ||
| } | ||
| } | ||
| fetchedToken = oauthSession.sessionToken(with: email)?.token | ||
| isAuthenticating = false | ||
| onAuthenticationFinished() | ||
| } | ||
| } | ||
|
|
||
| func onAuthenticationFinished() { | ||
| if let fetchedToken = oauthSession.sessionToken(with: email)?.token { | ||
| self.fetchedToken = fetchedToken | ||
| oauthError = nil | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When ❓ Since we're already setting
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think the problem here, is that when the Maybe what you described will handle all cases properly, but I'd be extra careful testing every success and error case (also a success after an error screen), if there's any change here. |
||
| } | ||
| isAuthenticating = false | ||
| } | ||
| } | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Question: Just wondering why the manual cancel() is necessary? Doesn't the oauth session end itself once it's successful?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the callback URL comes from universal links, the oauth session never returns, so it's never a "success", and the OAuth web view won't dismiss.
As every real scenario will use
httpsand universal link, it will always need this manual cancelling, so I think it safer to call it always, though is not necessary for our particular case of the demo app with the custom scheme exclusion.Testing the demo app, it didn't seem to be a problem, so I decided to keep the logic simple.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Without the canceling, the web view stays like this without dismissing:

So the canceling is basically the simplest way I found to dismiss it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see, interesting. Thanks!