-
Notifications
You must be signed in to change notification settings - Fork 5
feat: generic oauth plugin #13
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
Open
newtondotcom
wants to merge
6
commits into
ouwargui:main
Choose a base branch
from
newtondotcom:generic-oauth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a3276c4
feat: add GenericOAuth plugin for OAuth2 sign-in and linking function…
newtondotcom 4e662a9
chore: add BetterAuthGenericOAuth to packages target
newtondotcom 82929e2
fix: update `OAuthHandler` class to make it public
newtondotcom 46cbf8d
feat: integrate GenericOAuthPlugin in Example app
newtondotcom 89b052d
Update Sources/Core/Session/OAuthHandler.swift
newtondotcom 0543ef6
Update Example/BetterAuthSwiftExample/Plugins/GenericOAuthView.swift
newtondotcom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
Example/BetterAuthSwiftExample/Plugins/GenericOAuthView.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| // | ||
| // genericOAuthView.swift | ||
| // BetterAuthSwift | ||
| // | ||
| // Created by Robin Augereau on 07/11/2025. | ||
| // | ||
|
|
||
| import SwiftUI | ||
| import BetterAuth | ||
| import BetterAuthGenericOAuth | ||
|
|
||
| struct GenericOAuthView: View { | ||
| @EnvironmentObject var client: BetterAuthClient | ||
|
|
||
| @State private var providerId = "" | ||
| @State private var isSigningIn = false | ||
| @State private var errorMessage: String? | ||
|
|
||
| #if !os(watchOS) | ||
| var body: some View { | ||
| VStack(spacing: 24) { | ||
| if let user = client.session.data?.user { | ||
| // MARK: - Logged-in User | ||
| HStack(alignment: .center, spacing: 16) { | ||
| AsyncImage(url: URL(string: user.image ?? "")) { image in | ||
| image.resizable() | ||
| } placeholder: { | ||
| Circle() | ||
| .fill(Color.gray.opacity(0.3)) | ||
| .overlay( | ||
| Image(systemName: "person.fill") | ||
| .foregroundColor(.gray) | ||
| ) | ||
| } | ||
| .frame(width: 60, height: 60) | ||
| .clipShape(Circle()) | ||
| .shadow(radius: 2) | ||
|
|
||
| VStack(alignment: .leading, spacing: 4) { | ||
| Text(user.name) | ||
| .font(.headline) | ||
| .foregroundColor(.primary) | ||
| Text(user.email) | ||
| .font(.subheadline) | ||
| .foregroundColor(.secondary) | ||
| } | ||
|
|
||
| Spacer() | ||
|
|
||
| Button { | ||
| Task { try? await client.signOut() } | ||
| } label: { | ||
| Label("Logout", systemImage: "rectangle.portrait.and.arrow.right") | ||
| .font(.subheadline.bold()) | ||
| .foregroundColor(.white) | ||
| .padding(.horizontal, 12) | ||
| .padding(.vertical, 8) | ||
| .background(Capsule().fill(Color.red.gradient)) | ||
| } | ||
| .buttonStyle(.plain) | ||
| } | ||
| .padding() | ||
| .background( | ||
| RoundedRectangle(cornerRadius: 16) | ||
| .fill(Color(.secondarySystemFill)) | ||
| .shadow(color: .black.opacity(0.05), radius: 3, x: 0, y: 2) | ||
| ) | ||
|
|
||
| Text("Welcome back, \(user.name)!") | ||
| .font(.title3) | ||
| .fontWeight(.semibold) | ||
| } else { | ||
| // MARK: - OAuth2 Form | ||
| VStack(spacing: 16) { | ||
| Image(systemName: "person.badge.key.fill") | ||
| .resizable() | ||
| .scaledToFit() | ||
| .frame(width: 64, height: 64) | ||
| .foregroundStyle(.tint) | ||
| .padding(.bottom, 6) | ||
|
|
||
| Text("Sign in with OAuth2") | ||
| .font(.headline) | ||
|
|
||
| TextField("Provider ID", text: $providerId) | ||
| .textInputAutocapitalization(.never) | ||
| .autocorrectionDisabled() | ||
| .padding(12) | ||
| .background(Color(.secondarySystemFill)) | ||
| .cornerRadius(8) | ||
|
|
||
| Button { | ||
| signInWithOAuth2() | ||
| } label: { | ||
| Label("Sign In", systemImage: "arrow.right.circle.fill") | ||
| .font(.headline) | ||
| .foregroundColor(.white) | ||
| .padding(.horizontal, 40) | ||
| .padding(.vertical, 10) | ||
| .background(Capsule().fill(Color.accentColor.gradient)) | ||
| } | ||
| .disabled(providerId.isEmpty || isSigningIn) | ||
|
|
||
| if let errorMessage = errorMessage { | ||
| Text(errorMessage) | ||
| .foregroundColor(.red) | ||
| .font(.footnote) | ||
| .padding(.top, 4) | ||
| } | ||
| } | ||
| .padding() | ||
| .frame(maxWidth: 380) | ||
| .background( | ||
| RoundedRectangle(cornerRadius: 16) | ||
| .fill(Color(.tertiarySystemFill)) | ||
| .shadow(color: .black.opacity(0.05), radius: 4, x: 0, y: 2) | ||
| ) | ||
| .overlay(alignment: .center) { | ||
| if isSigningIn { | ||
| ProgressView() | ||
| .progressViewStyle(.circular) | ||
| .scaleEffect(1.3) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| .padding() | ||
| .animation(.spring(duration: 0.35), value: client.session.data?.user.id) | ||
| } | ||
|
|
||
| // MARK: - Logic | ||
| private func signInWithOAuth2() { | ||
| Task { | ||
| isSigningIn = true | ||
| errorMessage = nil | ||
| do { | ||
| _ = try await client.signIn.oauth2( | ||
| with: .init( | ||
| providerId: providerId, | ||
| callbackURL: "betterauthswiftexample://" | ||
| ) | ||
| ) | ||
| } catch { | ||
| errorMessage = "Failed to sign in: \(error.localizedDescription)" | ||
| } | ||
| isSigningIn = false | ||
| } | ||
| } | ||
| #else | ||
| var body: some View { | ||
| Text("OAuth2 is not supported on watchOS") | ||
| .foregroundColor(.secondary) | ||
| .padding() | ||
| } | ||
| #endif | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import BetterAuth | ||
| import Foundation | ||
|
|
||
| #if !os(watchOS) | ||
| extension BetterAuthClient.SignIn { | ||
| public typealias GenericOAuthSignInOAuth2 = APIResource< | ||
| GenericOAuthSignInResponse, EmptyContext | ||
| > | ||
|
|
||
| /// Make a request to **/sign-in/oauth2**. | ||
| /// - Parameter body: ``GenericOAuthSignInRequest`` | ||
| /// - Returns: ``GenericOAuthSignInOAuth2`` | ||
| /// - Throws: ``/BetterAuth/BetterAuthApiError`` - ``/BetterAuth/BetterAuthSwiftError`` | ||
| public func oauth2(with body: GenericOAuthSignInRequest) async throws | ||
| -> GenericOAuthSignInOAuth2 | ||
| { | ||
| guard let client = client else { | ||
| throw BetterAuthSwiftError(message: "Client deallocated") | ||
| } | ||
|
|
||
| return try await SignalBus.shared.emittingSignal(.signIn) { | ||
| let response: GenericOAuthSignInOAuth2 = try await client.httpClient.perform( | ||
| route: BetterAuthGenericOAuthRoute.signInOAuth2, | ||
| body: body, | ||
| responseType: GenericOAuthSignInResponse.self | ||
| ) | ||
|
|
||
| guard response.data.redirect, let authURL = response.data.url else { | ||
| return response | ||
| } | ||
|
|
||
| guard let callbackURL = body.callbackURL else { | ||
| throw BetterAuthSwiftError( | ||
| message: | ||
| "callbackURL is required to handle the OAuth redirect when redirect is enabled." | ||
| ) | ||
| } | ||
|
|
||
| let proxyURL = try client.genericOAuth.makeAuthorizationProxyURL( | ||
| for: authURL | ||
| ) | ||
|
|
||
| let handler = OAuthHandler() | ||
| let sessionCookie = try await handler.authenticate( | ||
| authURL: proxyURL.absoluteString, | ||
| callbackURLScheme: try handler.extractScheme(from: callbackURL) | ||
| ) | ||
|
|
||
| try client.httpClient.cookieStorage.setCookie( | ||
| sessionCookie, | ||
| for: client.baseUrl | ||
| ) | ||
|
|
||
| return response | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
|
|
||
| extension BetterAuthClient { | ||
| public var genericOAuth: GenericOAuth { | ||
| self.pluginRegistry.get(id: GenericOAuthPlugin.id) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import BetterAuth | ||
| import Foundation | ||
|
|
||
| public final class GenericOAuthPlugin: PluginFactory { | ||
| public static let id: String = "genericOAuth" | ||
|
|
||
| public static func create(client: BetterAuthClient) -> Pluggable { | ||
| GenericOAuth(client: client) | ||
| } | ||
|
|
||
| public init() {} | ||
| } | ||
|
|
||
| @MainActor | ||
| public final class GenericOAuth: Pluggable { | ||
| private weak var client: BetterAuthClient? | ||
|
|
||
| public init(client: BetterAuthClient) { | ||
| self.client = client | ||
| } | ||
|
|
||
| public typealias GenericOAuthLink = APIResource< | ||
| GenericOAuthLinkResponse, EmptyContext | ||
| > | ||
|
|
||
| /// Make a request to **/oauth2/link**. | ||
| /// - Parameter body: ``GenericOAuthLinkRequest`` | ||
| /// - Returns: ``GenericOAuthLink`` | ||
| /// - Throws: ``/BetterAuth/BetterAuthApiError`` - ``/BetterAuth/BetterAuthSwiftError`` | ||
| public func link(with body: GenericOAuthLinkRequest) async throws | ||
| -> GenericOAuthLink | ||
| { | ||
| guard let client = client else { | ||
| throw BetterAuthSwiftError(message: "Client deallocated") | ||
| } | ||
|
|
||
| return try await client.httpClient.perform( | ||
| route: BetterAuthGenericOAuthRoute.oauth2Link, | ||
| body: body, | ||
| responseType: GenericOAuthLinkResponse.self | ||
| ) | ||
| } | ||
|
|
||
| public func makeAuthorizationProxyURL(for authorizationURL: String) throws -> URL { | ||
| guard let client = client else { | ||
| throw BetterAuthSwiftError(message: "Client deallocated") | ||
| } | ||
|
|
||
| var components = URLComponents( | ||
| url: client.baseUrl, | ||
| resolvingAgainstBaseURL: false | ||
| ) | ||
| components?.path.append(BetterAuthRoute.expoAuthorizationProxy.path) | ||
| components?.queryItems = [ | ||
| URLQueryItem( | ||
| name: "authorizationURL", | ||
| value: authorizationURL | ||
| ) | ||
| ] | ||
|
|
||
| guard let url = components?.url else { | ||
| throw BetterAuthSwiftError(message: "Failed to create proxy URL") | ||
| } | ||
|
|
||
| return url | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Potential path construction issue with trailing slashes.
Using
path.append()may not correctly handle cases whereclient.baseUrl.pathorexpoAuthorizationProxy.pathcontain leading/trailing slashes, potentially resulting in malformed URLs (e.g., double slashes or missing separators).Apply this diff for more robust path handling:
var components = URLComponents( url: client.baseUrl, resolvingAgainstBaseURL: false ) - components?.path.append(BetterAuthRoute.expoAuthorizationProxy.path) + if let path = components?.path { + let separator = path.hasSuffix("/") ? "" : "/" + let routePath = BetterAuthRoute.expoAuthorizationProxy.path.hasPrefix("/") + ? String(BetterAuthRoute.expoAuthorizationProxy.path.dropFirst()) + : BetterAuthRoute.expoAuthorizationProxy.path + components?.path = path + separator + routePath + } components?.queryItems = [Alternatively, consider using
URL(fileURLWithPath:relativeTo:)orappendingPathComponent()ifbaseUrlsupports it.📝 Committable suggestion
🤖 Prompt for AI Agents