pocketbase / dart-sdk

PocketBase Dart SDK
https://pub.dev/packages/pocketbase
MIT License
511 stars 51 forks source link

android app auth data #32

Closed elsacutealways closed 1 year ago

elsacutealways commented 1 year ago

How to load recent authorization data after android app restarted and check if authorization is valid?

ganigeorgiev commented 1 year ago

The store at the moment is not persistent because the SDK is intended as generic Dart package, not just for Flutter and as noted in https://github.com/pocketbase/dart-sdk/issues/13, there are too many options - localstore, std or encrypted shared_preferences, local json file, key-value store, etc.

For now this is left to the developers to handle on their own depending on what persistent store and state management they prefer to use.

You can find 2 example approaches using shared_preferences in https://github.com/pocketbase/pocketbase/discussions/1887#discussioncomment-5057297 (note that there is also encrypted shared_preferences). The second shown example (with the pb.authStore.onChange.listen stream) is the easier and more generic approach.

ganigeorgiev commented 1 year ago

Sorry, I forgot about the "and check if authorization is valid" part of the question.

To loosely check (without making request to the backend) whether a pb.authStore holds unexpired auth data, you can call pb.authStore.isValid.

To check the loaded pb.authStore auth data server-side, you can send an authRefresh() request. On invalid or expired token it returns an error, otherwise - up-to-date user data and new token with refreshed exp claim (pb.authStore is updated automatically on success).

You can also combine both to prevent sending unnecessary server-side requests like this:

try {
  pb.authStore.isValid && await pb.collection("users").authRefresh();
} catch (e) {
  // clear the store on invalid or expired data
  pb.authStore.clear();
}