fetchAccountDetails method

Future<MicrosoftAccountDetails> fetchAccountDetails(
  1. Session session, {
  2. required String accessToken,
})

Returns the account details for the given accessToken.

This method calls Microsoft Graph API to get user information. If MicrosoftIdpConfig.fetchProfilePhoto is enabled, it also fetches the user's profile photo.

Throws MicrosoftAccessTokenVerificationException if the user info retrieval fails.

Implementation

Future<MicrosoftAccountDetails> fetchAccountDetails(
  final Session session, {
  required final String accessToken,
}) async {
  final response = await http.get(
    Uri.https('graph.microsoft.com', '/v1.0/me'),
    headers: {
      'Authorization': 'Bearer $accessToken',
      'Accept': 'application/json',
    },
  );

  if (response.statusCode != 200) {
    session.logAndThrow(
      'Failed to verify access token from Microsoft: ${response.statusCode}',
    );
  }

  Map<String, dynamic> data;
  try {
    data = jsonDecode(response.body) as Map<String, dynamic>;
  } catch (e) {
    session.logAndThrow('Invalid user info from Microsoft: $e');
  }

  MicrosoftAccountDetails details;
  try {
    details = _parseAccountDetails(data);
  } catch (e) {
    session.logAndThrow('Invalid user info from Microsoft: $e');
  }

  Uint8List? imageBytes;
  if (config.fetchProfilePhoto) {
    try {
      imageBytes = await _fetchProfilePhoto(
        session,
        accessToken: accessToken,
      );
    } catch (e) {
      session.log(
        'Failed to fetch Microsoft profile photo: $e',
        level: LogLevel.debug,
      );
    }
  }

  details = (
    userIdentifier: details.userIdentifier,
    email: details.email,
    name: details.name,
    imageBytes: imageBytes,
  );

  try {
    final getExtraInfoCallback = config.getExtraMicrosoftInfoCallback;
    if (getExtraInfoCallback != null) {
      await getExtraInfoCallback(
        session,
        accountDetails: details,
        accessToken: accessToken,
        transaction: null,
      );
    }
  } catch (e) {
    session.logAndThrow('Failed to get extra Microsoft account info: $e');
  }

  return details;
}