Refactor/login (#4583)
diff --git a/lib/src/command/login.dart b/lib/src/command/login.dart index 0a505b6..695c638 100644 --- a/lib/src/command/login.dart +++ b/lib/src/command/login.dart
@@ -24,30 +24,28 @@ @override Future<void> runProtected() async { final credentials = oauth2.loadCredentials(); + final userInfo = await _retrieveUserInfo(); + if (credentials == null) { - final userInfo = await _retrieveUserInfo(); if (userInfo == null) { log.warning( - 'Could not retrieve your user-details.\n' - 'You might have to run `$topLevelProgram pub logout` ' - 'to delete your credentials and try again.', + 'Could not retrieve your user details.\n' + 'Run `$topLevelProgram pub logout` to delete credentials and try ' + 'again.', ); } else { log.message('You are now logged in as $userInfo'); } } else { - final userInfo = await _retrieveUserInfo(); if (userInfo == null) { log.warning( - 'Your credentials seems broken.\n' - 'Run `$topLevelProgram pub logout` ' - 'to delete your credentials and try again.', + 'Your credentials seem to be broken.\n' + 'Run `$topLevelProgram pub logout` to delete credentials and try ' + 'again.', ); + } else { + log.message('You are already logged in as $userInfo'); } - log.warning( - 'You are already logged in as $userInfo\n' - 'Run `$topLevelProgram pub logout` to log out and try again.', - ); } } @@ -55,12 +53,23 @@ return await oauth2.withClient((client) async { final discovery = await oauth2.fetchOidcDiscoveryDocument(); final userInfoEndpoint = discovery['userinfo_endpoint']; + if (userInfoEndpoint is! String) { - log.fine('Bad discovery document. userinfo_endpoint not a String'); + log.fine(''' + Invalid discovery document: userinfo_endpoint is not a String + '''); + return null; } + final userInfoRequest = await client.get(Uri.parse(userInfoEndpoint)); - if (userInfoRequest.statusCode != 200) return null; + if (userInfoRequest.statusCode != 200) { + log.fine(''' + Failed to fetch user info: HTTP ${userInfoRequest.statusCode} + '''); + return null; + } + try { switch (json.decode(userInfoRequest.body)) { case {'name': final String? name, 'email': final String email}: @@ -68,15 +77,15 @@ case {'email': final String email}: return _UserInfo(name: null, email: email); default: - log.fine( - 'Bad response from $userInfoEndpoint: ${userInfoRequest.body}', - ); + log.fine(''' + Bad response from $userInfoEndpoint: ${userInfoRequest.body} + '''); return null; } } on FormatException catch (e) { - log.fine( - 'Bad response from $userInfoEndpoint ($e): ${userInfoRequest.body}', - ); + log.fine(''' + Failed to decode user info: $e\nResponse: ${userInfoRequest.body} + '''); return null; } });