Social Login (OAuth)
Create a script with the following code and bind it to an object.
The SDK exports a method called AuthenticateWithOAuth
that implements the pooling OAuth flow. The method takes an OAuthInitRequest
object as a parameter. The object contains the provider, the redirect URL, and the pooling option.
func continueWithGoogle() {
startOAuth(provider: .google, successMessage: "Signed in with Google!")
}
func startOAuth(provider: OFAuthProvider) {
do {
if let result = try await openfort.initOAuth(
params: OFInitOAuthParams(
provider: provider.rawValue,
options: ["redirectTo": AnyCodable(RedirectManager.makeLink(path: "login")?.absoluteString ?? "")]
)
), let urlString = result.url, let url = URL(string: urlString) {
await UIApplication.shared.open(url)
}
} catch {
print("\(error.localizedDescription)"
}
}
Handle onOpenUrl
// Handle OAuth redirect carrying access/refresh tokens and player id
if url.host == "login", let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let qp: [String: String] = comps.queryItems?.reduce(into: [:]) { dict, item in
if let v = item.value { dict[item.name] = v }
} ?? [:]
if let accessToken = qp["access_token"],
let refreshToken = qp["refresh_token"],
let playerId = qp["player_id"],
!accessToken.isEmpty, !refreshToken.isEmpty, !playerId.isEmpty {
Task {
do {
// Store credentials into Openfort SDK
try await openfort.storeCredentials(params: OFStoreCredentialsParams(player: playerId, accessToken: accessToken, refreshToken: refreshToken))
} catch {
print("Failed to store credentials: \(error.localizedDescription)")
}
}
}
}