### Quick Setup for BetterAuthClient with MagicLinkPlugin Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/MagicLink/Documentation.docc/Resources/GettingStarted.md This code demonstrates the quick setup for initializing the BetterAuthClient with the MagicLinkPlugin. It requires importing both BetterAuth and BetterAuthMagicLink. The client is initialized with a base URL and the MagicLinkPlugin instance. ```swift import BetterAuth // Import the plugin import BetterAuthMagicLink let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [MagicLinkPlugin()] ) ``` -------------------------------- ### Quick Setup with UsernamePlugin Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/Username/Documentation.docc/Resources/GettingStarted.md Demonstrates the basic initialization of BetterAuthClient with the UsernamePlugin. This involves importing the necessary modules and providing the API's base URL and the plugin instance. ```swift import BetterAuth // Import the plugin import BetterAuthUsername let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [UsernamePlugin()] ) ``` -------------------------------- ### Quick Setup for BetterAuthPhoneNumber Plugin Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/PhoneNumber/Documentation.docc/Resources/GettingStarted.md This Swift code demonstrates the quick setup for integrating the PhoneNumberPlugin with BetterAuthClient. It shows how to initialize the client with a base URL and include the PhoneNumberPlugin in the plugins array. ```swift import BetterAuth // Import the plugin import BetterAuthPhoneNumber let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [PhoneNumberPlugin()] ) ``` -------------------------------- ### Install Better Auth Swift via SPM Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Core/Documentation.docc/Resources/GettingStarted.md Add Better Auth Swift to your project using Swift Package Manager. This can be done directly in Xcode or by updating your project's Package.swift file. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ] ``` -------------------------------- ### Initialize BetterAuthClient Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Core/Documentation.docc/Resources/GettingStarted.md Instantiate the BetterAuthClient with the base URL of your API. This client will be used for all authentication operations. ```swift import BetterAuth let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")! ) ``` -------------------------------- ### Add BetterAuthSwift to Package.swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/MagicLink/Documentation.docc/Resources/GettingStarted.md This snippet shows how to add the BetterAuthSwift library, specifically the MagicLink plugin, to your project's Package.swift file. It defines dependencies for a target named 'MyApp'. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthMagicLink", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Swift Quick Setup for Two Factor Plugin Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/TwoFactor/Documentation.docc/Resources/GettingStarted.md Demonstrates the quick setup for initializing the BetterAuthClient with the TwoFactorPlugin in Swift. This involves importing necessary modules and configuring the client with your API's base URL. It's a prerequisite for utilizing 2FA functionalities. ```swift import BetterAuth // Import the plugin import BetterAuthTwoFactor let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [TwoFactorPlugin()] ) ``` -------------------------------- ### Integrate BetterAuthClient in SwiftUI Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Core/Documentation.docc/Resources/GettingStarted.md Set up your SwiftUI application to use BetterAuthClient by initializing it as an @StateObject and injecting it into the environment using .environmentObject(). This makes the client accessible throughout your SwiftUI views. ```swift import SwiftUI import BetterAuth @main struct MyApp: App { @StateObject private var authClient = BetterAuthClient( baseURL: URL(string: "https://your-api.com")! ) var body: some Scene { WindowGroup { ContentView() .environmentObject(authClient) } } } ``` -------------------------------- ### Add BetterAuthSwift to Package.swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/PhoneNumber/Documentation.docc/Resources/GettingStarted.md This code snippet demonstrates how to add the BetterAuthSwift library, including the BetterAuth and BetterAuthPhoneNumber products, to your project's Package.swift file for integration via Swift Package Manager. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthPhoneNumber", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Add BetterAuthSwift to Package.swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/Username/Documentation.docc/Resources/GettingStarted.md Integrates the BetterAuthSwift library and its Username plugin into your Swift project's Package.swift file. This involves specifying the repository URL and the desired products for your application target. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthUsername", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Basic SwiftUI App Setup with BetterAuth Source: https://context7.com/ouwargui/betterauthswift/llms.txt Demonstrates integrating BetterAuth into a SwiftUI application. It shows how to initialize BetterAuthClient with plugins and manage authentication states (logged in/out) within the UI. This setup uses environment objects to pass the auth client throughout the app. ```swift import SwiftUI import BetterAuth import BetterAuthTwoFactor import BetterAuthUsername @main struct MyApp: App { @StateObject private var authClient = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [TwoFactorPlugin(), UsernamePlugin()] ) var body: some Scene { WindowGroup { ContentView() .environmentObject(authClient) } } } struct ContentView: View { @EnvironmentObject private var authClient: BetterAuthClient @State private var email = "" @State private var password = "" @State private var errorMessage: String? var body: some View { Group { if let user = authClient.user { // Authenticated view VStack(spacing: 20) { Text("Welcome, \(user.name)") .font(.title) if let session = authClient.session { Text("Session expires: \(session.expiresAt, style: .relative)") .font(.caption) } Button("Sign Out") { Task { do { try await authClient.signOut() } catch { errorMessage = error.localizedDescription } } } .buttonStyle(.borderedProminent) } } else { // Sign in view VStack(spacing: 15) { TextField("Email", text: $email) .textFieldStyle(.roundedBorder) .textInputAutocapitalization(.never) .keyboardType(.emailAddress) SecureField("Password", text: $password) .textFieldStyle(.roundedBorder) if let error = errorMessage { Text(error) .foregroundColor(.red) .font(.caption) } Button("Sign In") { Task { do { try await authClient.signIn.email(with: .init( email: email, password: password )) } catch let error as BetterAuthError { errorMessage = error.coreError.message } catch { errorMessage = error.localizedDescription } } } .buttonStyle(.borderedProminent) .disabled(email.isEmpty || password.isEmpty) } .padding() } } } } ``` -------------------------------- ### Quick Setup for Anonymous Authentication in Swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/Anonymous/Documentation.docc/Resources/GettingStarted.md Initializes the BetterAuthClient with the Anonymous plugin for seamless anonymous authentication. This setup requires the base URL of your API and the AnonymousPlugin. ```swift import BetterAuth // Import the plugin import BetterAuthAnonymous let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [AnonymousPlugin()] ) ``` -------------------------------- ### Sign In with Email using BetterAuthClient Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Core/Documentation.docc/Resources/GettingStarted.md Perform email sign-in using the BetterAuthClient. This asynchronous method takes an EmailPassword struct containing the user's email and password, and returns user information upon success. Access session and user data from the client. ```swift let response = try? await client.signIn.email(with: .init( email: "user@example.com", password: "securepassword" )) print(response.user.name) // Session is a @Published variable print(client.session?.token) // So is user print(client.user?.name) ``` -------------------------------- ### Initialize BetterAuth Client with EmailOTPPlugin Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/EmailOTP/Documentation.docc/Resources/GettingStarted.md This Swift code demonstrates how to initialize the BetterAuthClient, including the EmailOTPPlugin. Ensure you replace 'https://your-api.com' with your actual API base URL. This setup is crucial for using email-based OTP functionalities. ```swift import BetterAuth // Import the plugin import BetterAuthEmailOTP let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [EmailOTPPlugin()] ) ``` -------------------------------- ### Install BetterAuthSwift with Swift Package Manager Source: https://github.com/ouwargui/betterauthswift/blob/main/README.md Instructions for adding the BetterAuthSwift library to your Xcode project or Package.swift file. It is recommended to use tag versions for stability. ```swift dependencies: [ .package( url: "https://github.com/ouwargui/BetterAuthSwift.git", .upToNextMajor(from: "1.0.0") // always use a tag version instead of main, since main is not stable ) ] ``` -------------------------------- ### Use BetterAuth Swift Plugins Source: https://github.com/ouwargui/betterauthswift/blob/main/README.md Example of using a BetterAuth Swift plugin, specifically checking the two-factor authentication status for a logged-in user. It imports the necessary plugin module and accesses user properties. ```swift import BetterAuth import BetterAuthTwoFactor let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")! ) if let user = client.user, let twoFactorEnabled = user.twoFactorEnabled { print(twoFactorEnabled) // true or false } ``` -------------------------------- ### Integrate BetterAuth Swift Client with SwiftUI Source: https://github.com/ouwargui/betterauthswift/blob/main/README.md Provides an example of integrating the BetterAuthClient into a SwiftUI application using @StateObject and @EnvironmentObject. It demonstrates conditional UI rendering based on user authentication status and sign-out functionality. ```swift import SwiftUI import BetterAuth @main struct MyApp: App { @StateObject private var authClient = BetterAuthClient( baseURL: URL(string: "https://your-api.com")! ) var body: some Scene { WindowGroup { ContentView() .environmentObject(authClient) } } } struct ContentView: View { @EnvironmentObject private var authClient: BetterAuthClient var body: some View { if let user = authClient.user { Text("Hello, \(user.name)") } if let session = authClient.session { Button { Task { try await authClient.signOut() } } label: { Text("Sign out") } } else { Button { Task { try await client.signIn.email(with: .init(email: "user@example.com", password: "securepassword")) } } label: { Text("Sign in") } } } } ``` -------------------------------- ### Revoke Session Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Revokes a specific user session using its token. This example first lists all sessions and then revokes the first one found. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let sessions = try await client.listSessions() if let sessionToRevoke = sessions.data.first { let response = try await client.revokeSession(with: .init( token: sessionToRevoke.token )) if response.data.status { print("Session revoked successfully") } } } catch { print("Failed to revoke session: (error.localizedDescription)") } ``` -------------------------------- ### Get Current Session (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Retrieves the current active session information from the server. This function requires the BetterAuth library and returns session details including user information, session ID, and expiration time. The client's session is automatically updated upon successful retrieval. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.getSession() if let session = response.data { print("Active session found") print("User: (session.user.name)") print("Session ID: (session.session.id)") print("Expires: (session.session.expiresAt)") // Session is automatically updated in client print("Client user: (client.user?.name ?? "none")") } else { print("No active session") } } catch { print("Error: (error.localizedDescription)") } ``` -------------------------------- ### Initialize BetterAuth Client with Plugins (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Initializes the BetterAuth client with a backend URL and an array of authentication plugins. It also demonstrates how to access the current session and user information after initialization. No external dependencies are required beyond the BetterAuth library itself. ```swift import BetterAuth import BetterAuthTwoFactor import BetterAuthUsername import BetterAuthPhoneNumber import BetterAuthMagicLink import BetterAuthEmailOTP let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [ TwoFactorPlugin(), UsernamePlugin(), PhoneNumberPlugin(), MagicLinkPlugin(), EmailOTPPlugin() ] ) // Access current session if let session = client.session { print("Session token: (session.token)") print("Expires at: (session.expiresAt)") } // Access current user if let user = client.user { print("User: (user.name) (\(user.email))") print("Email verified: (user.emailVerified)") } ``` -------------------------------- ### Sign In with Email using BetterAuth Swift Source: https://github.com/ouwargui/betterauthswift/blob/main/README.md Shows how to perform an email and password sign-in using the BetterAuth Swift client. It accesses user information and session tokens from the response and client properties. ```swift let response = try? await client.signIn.email(with: .init( email: "user@example.com", password: "securepassword" )) print(response.data.user.name) // Session is a @Published variable print(client.session?.token) // So is user print(client.user?.name) ``` -------------------------------- ### Add BetterAuth Swift via SPM to Package.swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/EmailOTP/Documentation.docc/Resources/GettingStarted.md This snippet shows how to add the BetterAuth Swift library and the EmailOTP plugin as a dependency in your project's `Package.swift` file. It specifies the repository URL and the versions to be used. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthEmailOTP", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Swift Package Manager Dependency Declaration Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/TwoFactor/Documentation.docc/Resources/GettingStarted.md Declares the BetterAuthSwift package as a dependency in your Swift project's Package.swift file. This ensures that the BetterAuth and BetterAuthTwoFactor products are available for use in your application targets. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthTwoFactor", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Sign Up with Email (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Creates a new user account using email and password authentication. This function requires the BetterAuth library and handles potential BetterAuthError exceptions, providing details about the error message and status code. It automatically updates the client's session upon successful creation. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.signUp.email(with: .init( email: "user@example.com", password: "SecurePassword123!", name: "John Doe", image: "https://example.com/avatar.jpg", callbackURL: nil, rememberMe: true )) print("User created: (response.data.user.name)") print("Token: (response.data.token)") // Session is automatically set in the client print("Current user: (client.user?.email ?? "none")") } catch let error as BetterAuthError { print("Auth error: (error.coreError.message)") print("Status code: (error.response.statusCode)") } catch { print("Error: (error.localizedDescription)") } ``` -------------------------------- ### Add BetterAuthSwift Plugins to Target Source: https://github.com/ouwargui/betterauthswift/blob/main/README.md Instructions on how to link BetterAuthSwift plugins to your application target, either through Xcode's Package Dependencies or by modifying your Package.swift file. ```swift dependencies: [ .package( url: "https://github.com/ouwargui/BetterAuthSwift.git", .upToNextMajor(from: "1.0.0") ) ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthTwoFactor", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Add BetterAuthSwift Dependency to Package.swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/Anonymous/Documentation.docc/Resources/GettingStarted.md Integrates the BetterAuthSwift library and its Anonymous plugin into your Swift project by adding the dependency to your Package.swift file. This allows your application to use the authentication functionalities provided by the library. ```swift dependencies: [ .package(url: "https://github.com/ouwargui/BetterAuthSwift.git", from: "1.0.0") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "BetterAuth", package: "BetterAuthSwift"), .product(name: "BetterAuthAnonymous", package: "BetterAuthSwift"), ] ) ] ``` -------------------------------- ### Sign Up with Username (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Allows users to sign up using a username instead of an email address. This utilizes the BetterAuth and BetterAuthUsername plugins. The process includes checking username availability before proceeding with the sign-up, which requires email, password, name, and username. ```swift import BetterAuth import BetterAuthUsername let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [UsernamePlugin()] ) do { // Check username availability first let availabilityCheck = try await client.isUsernameAvailable(with: .init( username: "johndoe2024" )) if availabilityCheck.data.available { let response = try await client.signUp.email(with: .init( email: "user@example.com", password: "SecurePassword123!", name: "John Doe", username: "johndoe2024", image: nil, callbackURL: nil, rememberMe: true )) print("User created: (response.data.user.name)") // Access username from plugin data if let username = client.user?.username { print("Username: (username)") } } else { print("Username not available") } } catch { print("Sign up failed: (error.localizedDescription)") } ``` -------------------------------- ### Swift Sign in with Apple using idToken Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Core/Documentation.docc/Resources/LoginWithApple.md This Swift code snippet demonstrates how to use the SignInWithAppleButton to obtain the idToken from Apple and subsequently sign in the user using BetterAuth. It handles success and failure cases for the Apple sign-in process. Dependencies include AuthenticationServices, BetterAuth, and SwiftUI. ```swift import AuthenticationServices import BetterAuth import SwiftUI struct ContentView: View { @StateObject private var client = BetterAuthClient( baseURL: URL(string: "http://your-api-url.com")! ) var body: some View { VStack { if let user = client.user { Text("Hello, \(user.name)") } Spacer() if client.session != nil { SignInWithAppleButton(.signIn) { request in request.requestedScopes = [.email, .fullName] } onCompletion: { result in Task { switch result { case .success(let authorization): guard let appleIdCredential = authorization.credential as? ASAuthorizationAppleIDCredential, let identityTokenData = appleIdCredential.identityToken, let identityToken = String( data: identityTokenData, encoding: .utf8 ) else { print("failed to get idtoken") return } let res = try await client.signIn.social( with: .init( provider: "apple", idToken: .init(token: identityToken) ) ) case .failure(let error): print( "sign in with apple failed \(error.localizedDescription)" ) } } } .frame(height: 50) } } .padding() } } ``` -------------------------------- ### Enable Two-Factor Authentication (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Enables two-factor authentication for the current user. This process involves first obtaining a TOTP URI, displaying it as a QR code, and then verifying a code provided by the user. Requires BetterAuth and BetterAuthTwoFactor plugins. It takes the user's password and the TOTP code as input. ```swift import BetterAuth import BetterAuthTwoFactor let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [TwoFactorPlugin()] ) do { // First, get TOTP URI let uriResponse = try await client.twoFactor.getTotpURI(with: .init( password: "UserPassword123!" )) print("TOTP URI: (uriResponse.data.totpUri)") print("Display URI in QR code for authenticator app") // User scans QR code and enters the code from their authenticator let code = "123456" // Enable 2FA with the code let response = try await client.twoFactor.enable(with: .init( password: "UserPassword123!", code: code )) if response.data.status { print("Two-factor authentication enabled") // Store backup codes securely let backupCodes = response.data.backupCodes print("Backup codes: (backupCodes)") } } catch { print("2FA setup failed: (error.localizedDescription)") } ``` -------------------------------- ### List Sessions Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Retrieves a list of all active sessions for the current user. It iterates through the sessions and prints details like ID, user agent, IP address, and timestamps. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.listSessions() print("Active sessions: (response.data.count)") for session in response.data { print("Session ID: (session.id)") print("User Agent: (session.userAgent)") print("IP Address: (session.ipAddress)") print("Created: (session.createdAt)") print("Expires: (session.expiresAt)") print("---") } } catch { print("Failed to list sessions: (error.localizedDescription)") } ``` -------------------------------- ### Phone Number Authentication (Sign In) in Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Handles user sign-in using a phone number and OTP verification. The process involves sending an OTP, receiving it, and then signing in with the phone number and OTP. Requires BetterAuth and BetterAuthPhoneNumber libraries. ```swift import BetterAuth import BetterAuthPhoneNumber let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [PhoneNumberPlugin()] ) do { // Step 1: Send OTP to phone number let sendResponse = try await client.phoneNumber.sendOtp(with: .init( phoneNumber: "+1234567890" )) if sendResponse.data.status { print("OTP sent successfully") } // Step 2: User enters OTP code received via SMS let otpCode = "123456" // Step 3: Sign in with phone number and OTP let signInResponse = try await client.signIn.phoneNumber(with: .init( phoneNumber: "+1234567890", password: otpCode )) print("Signed in as: (signInResponse.data.user.name)") // Access phone number from plugin data if let phoneNumber = client.user?.phoneNumber { print("Phone: (phoneNumber)") } } catch { print("Phone sign in failed: (error.localizedDescription)") } ``` -------------------------------- ### Sign In with Username (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Enables users to sign in using their username and password, leveraging the BetterAuth and BetterAuthUsername plugins. This method requires the username and password as input and returns user details upon successful authentication. ```swift import BetterAuth import BetterAuthUsername let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [UsernamePlugin()] ) do { let response = try await client.signIn.username(with: .init( username: "johndoe2024", password: "SecurePassword123!", callbackURL: nil, rememberMe: true )) if let user = response.data?.user { print("Signed in as: (user.name)") // Access username from plugin data if let username = client.user?.username { print("Username: (username)") } } } catch { print("Sign in failed: (error.localizedDescription)") } ``` -------------------------------- ### Anonymous Authentication in Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Creates an anonymous user session without requiring any credentials. This is useful for guest users or initial sign-ups. It requires the BetterAuth and BetterAuthAnonymous libraries. ```swift import BetterAuth import BetterAuthAnonymous let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [AnonymousPlugin()] ) do { let response = try await client.signIn.anonymous() print("Anonymous session created") print("User ID: (response.data.user.id)") print("Session token: (response.data.session.token)") // Check if user is anonymous if let isAnonymous = client.user?.isAnonymous { print("Is anonymous: (isAnonymous)") // true } } catch { print("Anonymous sign in failed: (error.localizedDescription)") } ``` -------------------------------- ### Handle 2FA Sign-in Response in Swift Source: https://github.com/ouwargui/betterauthswift/blob/main/Sources/Plugins/TwoFactor/Documentation.docc/Resources/LoginWith2FA.md Demonstrates how to detect and handle a 2FA redirect during user sign-in using the BetterAuthSwift library. It shows two approaches: directly checking the `twoFactorRedirect` flag in the response context and utilizing the `twoFactorResponse` enum for a more structured handling of success or redirect cases. This code assumes you have a `client` object configured for BetterAuthSwift. ```swift let res = client.signIn.email(with: body) // 1. Manually check the context guard let twoFactorRedirect = res.context.twoFactorRedirect else { print("User does not need 2FA") return } print(twoFactorRedirect) // Bool // 2. Use the twoFactorResponse helper property switch res.twoFactorResponse { case .twoFactorRedirect(let twoFA): print(twoFA) // Bool case .success(let res): print(res) // SignInEmailResponse } ``` -------------------------------- ### Sign In with Email (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Authenticates an existing user with their email and password. This function returns user details and token upon success. It also checks for required redirects (e.g., for two-factor authentication) and updates the client's session. Error handling for BetterAuthError is included. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.signIn.email(with: .init( email: "user@example.com", password: "SecurePassword123!", callbackURL: nil, rememberMe: true )) if let user = response.data?.user { print("Signed in as: (user.name)") print("Email verified: (user.emailVerified)") } // Check if redirect is needed (for two-factor, etc.) if let data = response.data, data.redirect, let url = data.url { print("Redirect required to: (url)") } // Access session via client if let session = client.session { print("Session expires: (session.expiresAt)") } } catch let error as BetterAuthError { print("Login failed: (error.coreError.message)") } catch { print("Error: (error.localizedDescription)") } ``` -------------------------------- ### OAuth Social Sign In with BetterAuth (iOS/macOS) Source: https://context7.com/ouwargui/betterauthswift/llms.txt This snippet shows how to implement social sign-in using OAuth providers like Google and GitHub within a SwiftUI application. It utilizes `ASWebAuthenticationSession` for handling the authentication flow and requires the `BetterAuth` library. Note that this functionality is not available on watchOS. ```swift import BetterAuth import SwiftUI let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) struct SocialSignInView: View { @EnvironmentObject private var authClient: BetterAuthClient @State private var errorMessage: String? var body: some View { VStack(spacing: 15) { Button("Sign In with Google") { Task { await signInWithProvider("google") } } Button("Sign In with GitHub") { await signInWithProvider("github") } if let error = errorMessage { Text(error) .foregroundColor(.red) .font(.caption) } } } func signInWithProvider(_ provider: String) async { do { // Note: OAuth sign in not available on watchOS #if !os(watchOS) let response = try await authClient.signIn.social(with: .init( provider: provider, callbackURL: "myapp://auth-callback", newUserCallbackURL: nil, errorCallbackURL: nil, idToken: nil, disableRedirect: false, scopes: ["email", "profile"], requestSignUp: false, loginHint: nil )) print("OAuth successful") print("Session: \(authClient.session?.token ?? "none")") #endif } catch let error as BetterAuthError { errorMessage = error.coreError.message } catch { errorMessage = error.localizedDescription } } } ``` -------------------------------- ### Magic Link Authentication in Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Enables passwordless authentication by sending a magic link to the user's email. The user clicks the link, which opens the app via a deep link to complete the sign-in. Requires BetterAuth and BetterAuthMagicLink libraries. ```swift import BetterAuth import BetterAuthMagicLink let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [MagicLinkPlugin()] ) do { // Step 1: Request magic link let response = try await client.signIn.magicLink(with: .init( email: "user@example.com", callbackURL: "myapp://magic-link" )) if response.data.status { print("Magic link sent to email") } // Step 2: User clicks link in email, app receives deep link // Extract token from URL like: myapp://magic-link?token=abc123 let token = "abc123" // from deep link URL // Step 3: Verify the magic link token let verifyResponse = try await client.magicLink.verify(with: .init( token: token )) print("Signed in as: (verifyResponse.data.user.name)") print("Session created: (client.session != nil)") } catch { print("Magic link authentication failed: (error.localizedDescription)") } ``` -------------------------------- ### Verify Email Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Verifies a user's email address using a provided verification token. It expects a token and a callback URL, and returns the user's email and verification status upon success. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) // Token typically comes from email link let verificationToken = "abc123xyz789" do { let response = try await client.verifyEmail(with: .init( token: verificationToken, callbackURL: "myapp://email-verified" )) if response.data.status { print("Email verified for: (response.data.user.email)") print("Verification status: (response.data.user.emailVerified)") } } catch { print("Verification failed: (error.localizedDescription)") } ``` -------------------------------- ### Email OTP Authentication in Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Facilitates sign-in using an email address and a one-time password (OTP) sent to that email. The flow involves requesting an OTP, receiving it, and then signing in with the email and OTP. Requires BetterAuth and BetterAuthEmailOTP libraries. ```swift import BetterAuth import BetterAuthEmailOTP let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [EmailOTPPlugin()] ) do { // Step 1: Request OTP to be sent to email let sendResponse = try await client.emailOtp.sendVerificationOtp(with: .init( email: "user@example.com", type: "sign-in" )) if sendResponse.data.status { print("OTP sent to email") } // Step 2: User enters OTP from email let otpCode = "123456" // Step 3: Sign in with email and OTP let signInResponse = try await client.signIn.emailOtp(with: .init( email: "user@example.com", otp: otpCode )) print("Signed in as: (signInResponse.data.user.name)") print("Session token: (client.session?.token ?? "none")") } catch { print("Email OTP sign in failed: (error.localizedDescription)") } ``` -------------------------------- ### Delete User Account with Password Confirmation (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Permanently deletes a user account after confirming the user's password. Requires the BetterAuth SDK. It takes password and a callback URL as input and returns a success status or an error. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.deleteUser(with: .init( token: nil, password: "UserPassword123!", callbackURL: "https://yourapp.com/account-deleted" )) if response.data.success { print("Account deleted: (response.data.message)") // User is automatically logged out print("Session cleared: (client.session == nil)") // true } } catch let error as BetterAuthError { print("Deletion failed: (error.coreError.message)") } catch { print("Error: (error.localizedDescription)") } ``` -------------------------------- ### Request Password Reset Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Initiates the password reset process by requesting a password reset email for a given user email. Requires the user's email and a redirect URL for the reset process. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.requestPasswordReset(with: .init( email: "user@example.com", redirectTo: "https://yourapp.com/reset-password" )) if response.data.status { print("Reset email sent: (response.data.message)") } } catch { print("Request failed: (error.localizedDescription)") } ``` -------------------------------- ### Verify Two-Factor Authentication Code (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Verifies a two-factor authentication code, typically during the sign-in process. This function requires the BetterAuth and BetterAuthTwoFactor plugins. It takes the TOTP code from the user's authenticator app as input and returns a success status and verification details. ```swift import BetterAuth import BetterAuthTwoFactor let client = BetterAuthClient( baseURL: URL(string: "https://your-api.com")!, plugins: [TwoFactorPlugin()] ) do { // User enters TOTP code from authenticator app let totpCode = "123456" let response = try await client.twoFactor.verifyTotp(with: .init( code: totpCode )) if response.data.status { print("2FA verification successful") print("Verified: (response.data.verified)") } } catch { print("2FA verification failed: (error.localizedDescription)") } ``` -------------------------------- ### Send Verification Email Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Requests a verification email to be sent to a specified user email address. Requires the user's email and a callback URL for redirection after verification. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.sendVerificationEmail(with: .init( email: "user@example.com", callbackURL: "https://yourapp.com/verify" )) if response.data.status { print("Verification email sent successfully") } } catch { print("Failed to send verification email: (error.localizedDescription)") } ``` -------------------------------- ### Reset Password Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Resets a user's password using a reset token. Requires the reset token and the new password. Returns a success status upon completion. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) // Token from password reset email let resetToken = "reset_abc123" do { let response = try await client.resetPassword(with: .init( token: resetToken, newPassword: "NewSecurePassword789!" )) if response.data.status { print("Password reset successful") } } catch { print("Password reset failed: (error.localizedDescription)") } ``` -------------------------------- ### Update User Profile Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Updates the current user's profile information, such as name and image. Requires an authenticated client and returns a success status or an error. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.updateUser(with: .init( image: "https://example.com/new-avatar.jpg", name: "Jane Smith" )) if response.data.status { print("Profile updated successfully") } // Refresh session to get updated user data _ = try await client.getSession() print("Updated name: (client.user?.name ?? \"unknown\")") } catch { print("Update failed: (error.localizedDescription)") } ``` -------------------------------- ### Sign Out (Swift) Source: https://context7.com/ouwargui/betterauthswift/llms.txt Ends the current user session and clears authentication cookies. This function requires the BetterAuth library and returns a success status upon completion. It automatically clears the session from the client, resulting in nil values for user and session properties. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.signOut() if response.data.success { print("Successfully signed out") } // Session is automatically cleared print("User is nil: (client.user == nil)") // true print("Session is nil: (client.session == nil)") // true } catch { print("Sign out error: (error.localizedDescription)") } ``` -------------------------------- ### Change Password Swift Source: https://context7.com/ouwargui/betterauthswift/llms.txt Changes the current user's password. It requires the current password, the new password, and an option to revoke other sessions. Handles BetterAuthError specifically. ```swift import BetterAuth let client = BetterAuthClient(baseURL: URL(string: "https://your-api.com")!) do { let response = try await client.changePassword(with: .init( currentPassword: "OldPassword123!", newPassword: "NewSecurePassword456!", revokeOtherSessions: true )) print("Password changed for user: (response.data.user.email)") if let token = response.data.token { print("New session token: (token)") } } catch let error as BetterAuthError { print("Password change failed: (error.coreError.message)") } catch { print("Error: (error.localizedDescription)") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.