auth.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { signIn, signOut } from "misago/reducers/auth"
  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(
  30. signIn({
  31. username: newState.username
  32. })
  33. )
  34. } else if (state.isAuthenticated) {
  35. // check if we are authenticated in this tab
  36. // because some browser plugins prune local store
  37. // aggressively, forcing erroneous message to display here
  38. // tracking bug #955
  39. this._store.dispatch(signOut())
  40. }
  41. })
  42. this._modal.hide()
  43. }
  44. signIn(user) {
  45. this._store.dispatch(signIn(user))
  46. this._local.set("auth", {
  47. isAuthenticated: true,
  48. username: user.username
  49. })
  50. this._modal.hide()
  51. }
  52. signOut() {
  53. this._store.dispatch(signOut())
  54. this._local.set("auth", {
  55. isAuthenticated: false
  56. })
  57. this._modal.hide()
  58. }
  59. softSignOut() {
  60. this._store.dispatch(signOut(true))
  61. this._local.set("auth", {
  62. isAuthenticated: false
  63. })
  64. this._modal.hide()
  65. }
  66. }
  67. export default new Auth()