Untitled

mail@pastecode.io avatar
unknown
dart
18 days ago
2.4 kB
6
Indexable
Never
import 'package:amazon_cognito_identity_dart_2/cognito.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CognitoAuthService {
  static const accessTokenKey = 'accessToken';
  static const expirationTimeKey = 'expirationTime';
  static const refreshTokenKey = 'refreshToken';

  final userPool = CognitoUserPool('USER_POOL_ID', 'APP_CLIENT_ID');

  Future<void> authenticateUser(String email, String password) async {
    final cognitoUser = CognitoUser(email, userPool);
    final authDetails = AuthenticationDetails(username: email, password: password);
    final userSession = await cognitoUser.authenticateUser(authDetails);

    final accessToken = userSession.getAccessToken().getJwtToken();
    final expirationTime = userSession.getAccessToken().getExpiration();
    final refreshToken = userSession.getRefreshToken().getToken();

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(accessTokenKey, accessToken);
    await prefs.setInt(expirationTimeKey, expirationTime.millisecondsSinceEpoch);
    await prefs.setString(refreshTokenKey, refreshToken);
  }

  Future<bool> isAccessTokenExpired() async {
    final prefs = await SharedPreferences.getInstance();
    final expirationTime =
        DateTime.fromMillisecondsSinceEpoch(prefs.getInt(expirationTimeKey)!);
    return DateTime.now().isAfter(expirationTime);
  }

  Future<String> getAccessToken(String email) async {
    final prefs = await SharedPreferences.getInstance();
    final cognitoUser = CognitoUser(email, userPool);
    if (await isAccessTokenExpired()) {
      final refreshToken = prefs.getString(refreshTokenKey)!;
      final updatedSession =
          await cognitoUser.initiateAuth(AuthFlow.REFRESH_TOKEN, refreshToken);

      final newAccessToken = updatedSession.getAccessToken().getJwtToken();
      final newExpirationTime = updatedSession.getAccessToken().getExpiration();

      await prefs.setString(accessTokenKey, newAccessToken);
      await prefs.setInt(expirationTimeKey, newExpirationTime.millisecondsSinceEpoch);

      return newAccessToken;
    }

    return prefs.getString(accessTokenKey)!;
  }

  Future<void> makeApiCall(String email) async {
    final accessToken = await getAccessToken(email);
    final headers = {'Authorization': 'Bearer $accessToken'};

    // Make the API call using the headers
    // ...
  }
}
Leave a Comment