LoginRepository.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package me.yoqi.android.netauth.data;
  2. import me.yoqi.android.netauth.data.model.LoggedInUser;
  3. /**
  4. * Class that requests authentication and user information from the remote data source and
  5. * maintains an in-memory cache of login status and user credentials information.
  6. */
  7. public class LoginRepository {
  8. private static volatile LoginRepository instance;
  9. private LoginDataSource dataSource;
  10. // If user credentials will be cached in local storage, it is recommended it be encrypted
  11. // @see https://developer.android.com/training/articles/keystore
  12. private LoggedInUser user = null;
  13. // private constructor : singleton access
  14. private LoginRepository(LoginDataSource dataSource) {
  15. this.dataSource = dataSource;
  16. }
  17. public static LoginRepository getInstance(LoginDataSource dataSource) {
  18. if (instance == null) {
  19. instance = new LoginRepository(dataSource);
  20. }
  21. return instance;
  22. }
  23. public boolean isLoggedIn() {
  24. return user != null;
  25. }
  26. public void logout() {
  27. user = null;
  28. dataSource.logout();
  29. }
  30. private void setLoggedInUser(LoggedInUser user) {
  31. this.user = user;
  32. // If user credentials will be cached in local storage, it is recommended it be encrypted
  33. // @see https://developer.android.com/training/articles/keystore
  34. }
  35. public Result<LoggedInUser> login(String username, String password) {
  36. // handle login
  37. Result<LoggedInUser> result = dataSource.login(username, password);
  38. if (result instanceof Result.Success) {
  39. setLoggedInUser(((Result.Success<LoggedInUser>) result).getData());
  40. }
  41. return result;
  42. }
  43. }