Guest User

Untitled

a guest
Sep 27th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. const state = {
  2. user: null,
  3. loading: false
  4. }
  5.  
  6. const getters = {
  7. user: state => state.user,
  8. loading: state => state.loading
  9. }
  10.  
  11. const actions = {
  12. me : ({ commit }) => {
  13. commit('setLoading', true)
  14. apolloClient
  15. .query({
  16. query: GET_CURRENT_USER
  17. })
  18. .then(({ data }) => {
  19. setTimeout(() => {
  20. commit('setLoading', false)
  21. // Add user data to state
  22. commit('setUser', data.me)
  23. console.log(data)
  24. }, 500)
  25. })
  26. .catch(err => {
  27. commit('setLoading', false)
  28. console.log(err)
  29. })
  30. },
  31.  
  32. login: ({ commit }, payload) => {
  33. localStorage.setItem('token', '')
  34. apolloClient
  35. .mutate({
  36. mutation: LOGIN,
  37. variables: payload
  38. })
  39. .then(({ data }) => {
  40. setTimeout(() => {
  41. localStorage.setItem("token", data.login.auth.token)
  42. router.go('/')
  43. VueNotifications.success({ message: 'Welcome !' })
  44. }, 500)
  45. })
  46. .catch(err => {
  47. VueNotifications.error({ message: 'Error' });
  48. })
  49. },
  50.  
  51. logout : async ({ commit }) => {
  52. Nprogress.start();
  53. // clear user in state
  54. commit('clearUser')
  55. // remove token in localStorage
  56. localStorage.setItem('token', '')
  57. // end session
  58. await apolloClient.resetStore()
  59. // redirect to home - kick users out of private pages
  60. router.push('/session/login')
  61. Nprogress.done();
  62.  
  63. }
  64. }
  65.  
  66. const mutations = {
  67. setUser: (state, payload) => {
  68. state.user = payload
  69. },
  70. setLoading: (state, payload) => {
  71. state.loading = payload
  72. },
  73. clearUser: state => (state.user = null)
  74. }
  75.  
  76. computed: {
  77. ...mapGetters(['loading', 'user'])
  78. },
  79. created() {
  80. this.$store.dispatch('me')
  81. },
  82. watch: {
  83. deep: true,
  84. immediate:true,
  85. user(value) {
  86. if(value) {
  87. this.$router.push('/')
  88. }
  89. }
  90. },
  91. methods: {
  92. loginUser() {
  93. if(this.$refs.form.validate()) {
  94. this.$store.dispatch("login", {
  95. email: this.email,
  96. password: this.password
  97. })
  98. }
  99. }
  100. }
  101.  
  102. router.beforeEach((to, from, next) => {
  103. if (to.matched.some(record => record.meta.requiresAuth)) {
  104. // this route requires auth, check if logged in
  105. // if not, redirect to login page.
  106. if (!store.getters.user) {
  107. next({
  108. path: '/session/login',
  109. })
  110. } else {
  111. next()
  112. }
  113. } else {
  114. next() // make sure to always call next()!
  115. }
  116. })
Add Comment
Please, Sign In to add comment