Created
July 14, 2020 14:57
-
-
Save magicleon94/faa93e0c2672500adf54d45af073bc75 to your computer and use it in GitHub Desktop.
Auth0 manager - dart side - for medium article
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
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:js' as js; | |
import 'package:my_app/providers/user_provider/model/user.dart'; | |
import 'package:my_app/providers/user_provider/user_provider.dart'; | |
import 'auth_manager.dart'; | |
void _alert(dynamic param) { | |
js.context.callMethod('alert', [param]); | |
} | |
class Auth0ManagerForWeb extends AuthManager { | |
js.JsObject get jsAuthManager { | |
if (js.context['authManager'] == null) { | |
js.context['authManager'] = js.context.callMethod('createAuth0Manager', [ | |
js.JsObject.jsify({ | |
'domain': AuthManager.domain, | |
'clientID': AuthManager.clientID, | |
'responseType': AuthManager.responseType, | |
'redirectUri': AuthManager.redirectUri, | |
'scope': AuthManager.scope, | |
}), | |
//onAuthSuccess | |
_alert, | |
//onError | |
_alert, | |
]); | |
} | |
return js.context['authManager']; | |
} | |
@override | |
Future<User> login([Map<String, String> authResponse]) async { | |
if (authResponse == null) { | |
jsAuthManager.callMethod('login'); | |
return null; | |
} else { | |
return userFromTokens( | |
authResponse['id_token'], authResponse['access_token']); | |
} | |
} | |
@override | |
Future<void> logout() async { | |
jsAuthManager.callMethod('logout', [UserProvider.instance.logout]); | |
} | |
@override | |
Future<User> userFromTokens(String idToken, String accessToken) async { | |
final jsCompleter = Completer<Map<String, dynamic>>(); | |
final onUserInfo = (dynamic err, dynamic info) { | |
final json = | |
jsonDecode(js.context['JSON'].callMethod('stringify', [info])); | |
jsCompleter.complete(json); | |
}; | |
jsAuthManager.callMethod('getUserInfo', [accessToken, onUserInfo]); | |
final info = await jsCompleter.future; | |
if (info == null) { | |
return null; | |
} | |
if (info is Map) { | |
info.addAll({ | |
'id_token': idToken, | |
'access_token': accessToken, | |
}); | |
} | |
final user = User.fromJson(Map<String, dynamic>.from(info)); | |
return user; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment