Skip to content
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

Fix #15 always terminate 'authenticate' callbacks on Android #28

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ import android.app.Activity
import android.net.Uri
import android.os.Bundle

public class CallbackActivity: Activity() {
class CallbackActivity: Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

val url = getIntent()?.getData() as? Uri
val scheme = url?.getScheme()
val url = intent?.data
val scheme = url?.scheme

if (scheme != null) {
FlutterWebAuthPlugin.callbacks.remove(scheme)?.success(url.toString())
}

this.finish()
finish()
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.linusu.flutter_web_auth

import java.util.HashMap

import android.content.Context
import android.content.Intent
import android.net.Uri
Expand All @@ -16,7 +14,7 @@ import io.flutter.plugin.common.PluginRegistry.Registrar

class FlutterWebAuthPlugin(private val context: Context): MethodCallHandler {
companion object {
public val callbacks = HashMap<String, Result>()
val callbacks = mutableMapOf<String, Result>()

@JvmStatic
fun registerWith(registrar: Registrar) {
Expand All @@ -25,22 +23,30 @@ class FlutterWebAuthPlugin(private val context: Context): MethodCallHandler {
}
}

override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "authenticate") {
val url = Uri.parse(call.argument<String>("url"))
val callbackUrlScheme = call.argument<String>("callbackUrlScheme")!!

callbacks.put(callbackUrlScheme, result)

val intent = CustomTabsIntent.Builder().build()
val keepAliveIntent = Intent().setClassName(context.getPackageName(), KeepAliveService::class.java.canonicalName)

intent.intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_NEW_TASK)
intent.intent.putExtra("android.support.customtabs.extra.KEEP_ALIVE", keepAliveIntent)

intent.launchUrl(context, url)
} else {
result.notImplemented()
override fun onMethodCall(call: MethodCall, resultCallback: Result) {
when (call.method) {
"authenticate" -> {
val url = Uri.parse(call.argument("url"))
val callbackUrlScheme = call.argument<String>("callbackUrlScheme")!!

callbacks[callbackUrlScheme] = resultCallback

val intent = CustomTabsIntent.Builder().build()
val keepAliveIntent = Intent(context, KeepAliveService::class.java)

intent.intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_NEW_TASK)
intent.intent.putExtra("android.support.customtabs.extra.KEEP_ALIVE", keepAliveIntent)

intent.launchUrl(context, url)
}
"cleanUpDanglingCalls" -> {
callbacks.forEach{ (_, danglingResultCallback) ->
danglingResultCallback.error("CANCELED", "User canceled login", null)
}
callbacks.clear()
resultCallback.success(null)
}
else -> resultCallback.notImplemented()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import android.content.Intent
import android.os.Binder
import android.os.IBinder

public class KeepAliveService: Service() {
class KeepAliveService: Service() {
companion object {
val sBinder = Binder()
val binder = Binder()
}

override fun onBind(intent: Intent): IBinder {
return sBinder
return binder
}
}
10 changes: 7 additions & 3 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:io' show HttpServer;

Expand Down Expand Up @@ -93,9 +94,12 @@ class _MyAppState extends State<MyApp> {
final url = 'http://localtest.me:43823/';
final callbackUrlScheme = 'foobar';

final result = await FlutterWebAuth.authenticate(url: url, callbackUrlScheme: callbackUrlScheme);

setState(() { _status = 'Got result: $result'; });
try {
final result = await FlutterWebAuth.authenticate(url: url, callbackUrlScheme: callbackUrlScheme);
setState(() { _status = 'Got result: $result'; });
} on PlatformException catch (e) {
setState(() { _status = 'Got error: $e'; });
}
}

@override
Expand Down
11 changes: 7 additions & 4 deletions ios/Classes/SwiftFlutterWebAuthPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ public class SwiftFlutterWebAuthPlugin: NSObject, FlutterPlugin {
let url = URL(string: (call.arguments as! Dictionary<String, AnyObject>)["url"] as! String)!
let callbackURLScheme = (call.arguments as! Dictionary<String, AnyObject>)["callbackUrlScheme"] as! String

var keepMe: Any? = nil
var sessionToKeepAlive: Any? = nil // if we do not keep the session alive, it will get closed immediately while showing the dialog
let completionHandler = { (url: URL?, err: Error?) in
keepMe = nil
sessionToKeepAlive = nil

if let err = err {
if #available(iOS 12, *) {
Expand Down Expand Up @@ -52,12 +52,15 @@ public class SwiftFlutterWebAuthPlugin: NSObject, FlutterPlugin {
}

session.start()
keepMe = session
sessionToKeepAlive = session
} else {
let session = SFAuthenticationSession(url: url, callbackURLScheme: callbackURLScheme, completionHandler: completionHandler)
session.start()
keepMe = session
sessionToKeepAlive = session
}
} else if (call.method == "cleanUpDanglingCalls") {
// we do not keep track of old callbacks on iOS, so nothing to do here
result(nil)
} else {
result(FlutterMethodNotImplemented)
}
Expand Down
33 changes: 32 additions & 1 deletion lib/flutter_web_auth.dart
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show required;
import 'package:flutter/services.dart' show MethodChannel;

class _OnAppLifecycleResumeObserver extends WidgetsBindingObserver {
final Function onResumed;

_OnAppLifecycleResumeObserver(this.onResumed);

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
onResumed();
}
}
}

class FlutterWebAuth {
static const MethodChannel _channel = const MethodChannel('flutter_web_auth');

static final _OnAppLifecycleResumeObserver _resumedObserver = _OnAppLifecycleResumeObserver(() {
_cleanUpDanglingCalls(); // unawaited
});

/// Ask the user to authenticate to the specified web service.
///
/// The page pointed to by [url] will be loaded and displayed to the user. From the page, the user can authenticate herself and grant access to the app. On completion, the service will send a callback URL with an authentication token, and this URL will be result of the returned [Future].
///
/// [callbackUrlScheme] should be a string specifying the scheme of the url that the page will redirect to upon successful authentication.
static Future<String> authenticate({@required String url, @required String callbackUrlScheme}) async {
return await _channel.invokeMethod('authenticate', <String, dynamic>{'url': url, 'callbackUrlScheme': callbackUrlScheme}) as String;
WidgetsBinding.instance.removeObserver(_resumedObserver); // safety measure so we never add this observer twice
WidgetsBinding.instance.addObserver(_resumedObserver);
return await _channel.invokeMethod('authenticate', <String, dynamic>{
'url': url,
'callbackUrlScheme': callbackUrlScheme,
}) as String;
}

/// On Android, the plugin has to store the Result callbacks in order to pass the result back to the caller of
/// `authenticate`. But if that result never comes the callback will dangle around forever. This can be called to
/// terminate all `authenticate` calls with an error.
static Future<void> _cleanUpDanglingCalls() async {
await _channel.invokeMethod('cleanUpDanglingCalls');
WidgetsBinding.instance.removeObserver(_resumedObserver);
}
}