LoginRepository.java 1.8 KB

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