auth.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { signIn, signOut } from 'misago/reducers/auth'; // jshint ignore:line
  2. export class Auth {
  3. init(store, local) {
  4. this._store = store;
  5. this._local = local;
  6. // tell other tabs what auth state is because we are most current with it
  7. this.syncSession();
  8. // listen for other tabs to tell us that state changed
  9. this.watchState();
  10. }
  11. syncSession() {
  12. let state = this._store.getState().auth;
  13. if (state.isAuthenticated) {
  14. this._local.set('auth', {
  15. isAuthenticated: true,
  16. username: state.user.username
  17. });
  18. } else {
  19. this._local.set('auth', {
  20. isAuthenticated: false
  21. });
  22. }
  23. }
  24. watchState() {
  25. this._local.watch('auth', (newState) => {
  26. if (newState.isAuthenticated) {
  27. this._store.dispatch(signIn({
  28. username: newState.username
  29. }));
  30. } else {
  31. this._store.dispatch(signOut());
  32. }
  33. });
  34. }
  35. signIn(user) {
  36. this._store.dispatch(signIn(user));
  37. this._local.set('auth', {
  38. isAuthenticated: true,
  39. username: user.username
  40. });
  41. }
  42. signOut() {
  43. this._store.dispatch(signOut());
  44. this._local.set('auth', {
  45. isAuthenticated: false
  46. });
  47. }
  48. softSignOut() {
  49. this._store.dispatch(signOut(true));
  50. this._local.set('auth', {
  51. isAuthenticated: false
  52. });
  53. }
  54. }
  55. export default new Auth();