|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | +import 'dart:html'; |
| 4 | +import 'dart:js'; |
| 5 | + |
| 6 | +import 'package:flutter/services.dart'; |
| 7 | +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; |
| 8 | + |
| 9 | +class FlutterWebAuthPlugin { |
| 10 | + static void registerWith(Registrar registrar) { |
| 11 | + final MethodChannel channel = MethodChannel( |
| 12 | + 'flutter_web_auth', const StandardMethodCodec(), registrar.messenger); |
| 13 | + final FlutterWebAuthPlugin instance = FlutterWebAuthPlugin(); |
| 14 | + channel.setMethodCallHandler(instance.handleMethodCall); |
| 15 | + } |
| 16 | + |
| 17 | + Future<dynamic> handleMethodCall(MethodCall call) async { |
| 18 | + switch (call.method) { |
| 19 | + case 'authenticate': |
| 20 | + final String url = call.arguments['url']; |
| 21 | + return _authenticate(url); |
| 22 | + default: |
| 23 | + throw PlatformException( |
| 24 | + code: 'Unimplemented', |
| 25 | + details: "The flutter_web_auth plugin for web doesn't implement " |
| 26 | + "the method '${call.method}'"); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + static Future<String> _authenticate(String url) async { |
| 31 | + context.callMethod('open', [url]); |
| 32 | + await for (MessageEvent messageEvent in window.onMessage) { |
| 33 | + if (messageEvent.origin == Uri.base.origin) { |
| 34 | + final flutterWebAuthMessage = messageEvent.data['flutter-web-auth']; |
| 35 | + if (flutterWebAuthMessage is String) { |
| 36 | + return flutterWebAuthMessage; |
| 37 | + } |
| 38 | + } |
| 39 | + var appleOrigin = Uri(scheme: 'https', host: 'appleid.apple.com'); |
| 40 | + if (messageEvent.origin == appleOrigin.toString()) { |
| 41 | + try { |
| 42 | + Map<String, dynamic> data = jsonDecode(messageEvent.data); |
| 43 | + if (data['method'] == 'oauthDone') { |
| 44 | + final appleAuth = data['data']['authorization']; |
| 45 | + if (appleAuth != null) { |
| 46 | + final appleAuthQuery = Uri(queryParameters: appleAuth).query; |
| 47 | + return appleOrigin.replace(fragment: appleAuthQuery).toString(); |
| 48 | + } |
| 49 | + } |
| 50 | + } on FormatException {} |
| 51 | + } |
| 52 | + } |
| 53 | + throw new PlatformException( |
| 54 | + code: 'error', message: 'Iterable window.onMessage is empty'); |
| 55 | + } |
| 56 | +} |
0 commit comments