auth.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { signIn, signOut } from 'misago/reducers/auth'; // jshint ignore:line
  2. export class Auth {
  3. init(store, local, modal) {
  4. this._store = store;
  5. this._local = local;
  6. this._modal = modal;
  7. // tell other tabs what auth state is because we are most current with it
  8. this.syncSession();
  9. // listen for other tabs to tell us that state changed
  10. this.watchState();
  11. }
  12. syncSession() {
  13. const state = this._store.getState().auth;
  14. if (state.isAuthenticated) {
  15. this._local.set('auth', {
  16. isAuthenticated: true,
  17. username: state.user.username
  18. });
  19. } else {
  20. this._local.set('auth', {
  21. isAuthenticated: false
  22. });
  23. }
  24. }
  25. watchState() {
  26. const state = this._store.getState().auth;
  27. this._local.watch('auth', (newState) => {
  28. if (newState.isAuthenticated) {
  29. this._store.dispatch(signIn({
  30. username: newState.username
  31. }));
  32. } else if (state.isAuthenticated) {
  33. // check if we are authenticated in this tab
  34. // because some browser plugins prune local store
  35. // aggressively, forcing erroneous message to display here
  36. // tracking bug #955
  37. this._store.dispatch(signOut());
  38. }
  39. });
  40. this._modal.hide();
  41. }
  42. signIn(user) {
  43. this._store.dispatch(signIn(user));
  44. this._local.set('auth', {
  45. isAuthenticated: true,
  46. username: user.username
  47. });
  48. this._modal.hide();
  49. }
  50. signOut() {
  51. this._store.dispatch(signOut());
  52. this._local.set('auth', {
  53. isAuthenticated: false
  54. });
  55. this._modal.hide();
  56. }
  57. softSignOut() {
  58. this._store.dispatch(signOut(true));
  59. this._local.set('auth', {
  60. isAuthenticated: false
  61. });
  62. this._modal.hide();
  63. }
  64. }
  65. export default new Auth();