Improve check auth in middleware. Some fixes.

This commit is contained in:
2019-03-23 11:51:50 +07:00
parent b79f31e7de
commit 3c7d774757
4 changed files with 36 additions and 17 deletions

View File

@@ -55,7 +55,8 @@ export default {
signOut() {
this.$confirm('Вы точно хотите выйти?').then(res => {
if (res) {
this.$store.dispatch('signOut');
this.$store.dispatch('signOut')
.then(() => this.changeLocation({ name: 'home' }));
}
});
},
@@ -110,5 +111,3 @@ export default {
};
</script>
<style scoped>
</style>

View File

@@ -39,10 +39,6 @@ new Vue({
store,
render: h => h(App),
created: function onApplicationCreated() {
firebase.auth().onAuthStateChanged((user) => {
this.$store.dispatch('stateChanged', user);
});
this.$store.dispatch('loadArticles');
},
}).$mount('#app');

View File

@@ -6,15 +6,7 @@ import Home from '@/views/Home';
Vue.use(Router);
function AuthMiddleware(from, to, next) {
if (Store.getters.isUserAuthenticated) {
next();
} else {
next('/sign_in');
}
}
export default new Router({
const router = new Router({
routes: [
{
path: '/',
@@ -47,7 +39,7 @@ export default new Router({
path: '/profile',
name: 'profile',
component: () => import(/* webpackChunkName: "words" */ '@/views/Profile'),
beforeEnter: AuthMiddleware,
meta: { authRequired: true },
},
{
path: '/sign_in',
@@ -66,3 +58,16 @@ export default new Router({
],
mode: 'history',
});
router.beforeEach((to, from, next) => {
Store.dispatch('initAuth')
.then((user) => {
if (to.matched.some(route => route.meta.authRequired)) {
return user ? next() : next('/sign_in');
}
return next();
})
})
export default router;

View File

@@ -11,6 +11,7 @@ export default {
email: null,
name: null,
},
unSubscribeAuth: null,
},
mutations: {
setUser(state, { uid, email }) {
@@ -28,8 +29,26 @@ export default {
setUserEmail(state, email) {
Vue.set(state.user, 'email', email);
},
setUnSubscribeAuth(state, func) {
state.unSubscribeAuth = func;
},
},
actions: {
initAuth({ commit, dispatch, state }) {
return new Promise((resolve) => {
if (state.unSubscribeAuth) {
state.unSubscribeAuth();
}
const unSubscribe = firebase.auth()
.onAuthStateChanged((user) => {
dispatch('stateChanged', user);
resolve(user);
});
commit('setUnSubscribeAuth', unSubscribe);
})
},
async signUp({ commit }, payload) {
await commit('setProcessing', true);
commit('clearError');