Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refresh Token #333

Open
nikunjshaligram opened this issue Aug 13, 2024 · 1 comment
Open

Refresh Token #333

nikunjshaligram opened this issue Aug 13, 2024 · 1 comment
Labels

Comments

@nikunjshaligram
Copy link

If access token is expired so how to manage with refresh token and work through the app.

My code :

main.dart file :

final GlobalKey navigatorKey = GlobalKey();
late final AuthController authController;

final config = Config(
// tenant: '416a0629-c2f6-468c-b028-ec1aaaaf6e37',
tenant: 'heartid',
clientId: '45fff3bf-c5f3-4ad7-a227-e09ee495bc91',
scope:
'openid offline_access https://heartid.onmicrosoft.com/80487dfc-2b55-408d-a998-4c7eb488f699/access_as_user',
redirectUri: 'https://login.live.com/oauth20_desktop.srf',
isB2C: true,
navigatorKey: navigatorKey,
policy: 'B2C_1_CustomerSignin',
tokenIdentifier: 'UNIQUE IDENTIFIER A',
webUseRedirect: true,
loader: const Center(child: CircularProgressIndicator()),
);

final oauth = AadOAuth(config);
await GetStorage.init();
//final storage = GetStorage();
authController = AuthController(oauth, config);

authcontroller.dart file

class AuthController extends BaseGetXController {
AuthController(this.oauth, this.config); // this.storage,
final AadOAuth oauth;
// final GetStorage storage;
final Config config;

//RxBool isAuthenticated = false.obs;
RxString accessToken = ''.obs;
RxString refreshToken = ''.obs;
final box = GetStorage();

Future signIn() async {
try {
final result = await oauth.login();
await result.fold(
(failure) {
if (failure.errorType ==
ErrorType.accessDeniedOrAuthenticationCanceled) {
print('Access denied or authentication canceled.');
Get.snackbar(
'Authentication Error',
'Access denied or authentication canceled.',
snackPosition: SnackPosition.BOTTOM,
);
} else {
print('Failed to sign in: ${failure.errorType}');
Get.snackbar(
'Authentication Error',
'Failed to sign in: ${failure.errorType}',
snackPosition: SnackPosition.BOTTOM,
);
}
},
(token) async {
//isAuthenticated.value = true;
accessToken.value = token.accessToken!;
refreshToken.value = token.refreshToken!;
await boxStorage.setString(
GetStorageHelper.token,
accessToken.toString(),
);

      if (accessToken.value.isNotEmpty) {
        await getUserData(accessToken.value);
      }

      // storage.write('accessToken', token.accessToken);
      // print('Token: ${token.accessToken}');

      //Get.offAllNamed(Routes.dashboard);
    },
  );
} catch (e) {
  print('Failed to sign in: $e');
  Get.snackbar(
    'Error',
    'Failed to sign in. Please check your network connection.',
    snackPosition: SnackPosition.BOTTOM,
  );
}

}

void signOut() {
oauth.logout();
//isAuthenticated.value = false;
//accessToken.value = '';
// storage.remove('accessToken');
Get.offAllNamed(Routes.login);
}

Future getUserData(String token) async {
// await authController.signIn();

await boxStorage.setString(
  GetStorageHelper.token,
  token,
);

final failureOrSuccess = await authRepository.userProfile();

await failureOrSuccess.fold((failure) {
  isLoading.value = false;
  if (failure == ServerFailure()) {
    SnackBarWidget().showSnackBar(
      messageText: 'Server lost',
    );
  }
}, (response) async {
  final result = response.firstWhereOrNull(
    (element) =>
        element.emailAddress ==
        '[email protected]', //emailController.text.trim(),
  );

  if (result != null) {
    SnackBarWidget().showSnackBar(
      messageText: AppLabel.loginSuccessfullyText,
    );

    await box.write('userData', result.toJson());

    isLoading.value = false;
    await boxStorage.setBool(key: GetStorageHelper.isLogin, value: true);
    await Get.toNamed(Routes.dashboard);
  } else {
    SnackBarWidget().showSnackBar(
      messageText: AppLabel.invalidCredentialText,
    );
    isLoading.value = false;
  }
});
isLoading.value = false;

}

@OverRide
void onInit() {
super.onInit();
// accessToken.value = storage.read('accessToken') ?? '';
// isAuthenticated.value = accessToken.isNotEmpty;
}
}

Can you check the code and provide me a solution.

Copy link

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. If you still think this issue is needed, reopen it again.

@github-actions github-actions bot added the stale label Oct 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant