Skip to content

Commit

Permalink
Route guards
Browse files Browse the repository at this point in the history
  • Loading branch information
juanwmedia committed Aug 24, 2020
1 parent 6da068c commit 9f99fbb
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
23 changes: 21 additions & 2 deletions src/router/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import RoomsView from "../views/RoomsView.vue";
import AuthView from "../views/AuthView.vue";
import store from "../store";

Vue.use(VueRouter);

const routes = [
{
path: "/",
name: "Home",
component: Home
component: RoomsView,
meta: {
requiresAuth: true
}
},
{
path: "/auth",
Expand All @@ -24,4 +28,19 @@ const router = new VueRouter({
routes
});

router.beforeEach(async (to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

// Requires auth & no user
if (requiresAuth && !(await store.dispatch("user/getCurrentUser"))) {
next({ name: "auth" });
// No requires auth and user (auth)
} else if (!requiresAuth && (await store.dispatch("user/getCurrentUser"))) {
next({ name: "Home" });
} else {
// Anything else
next();
}
});

export default router;
13 changes: 13 additions & 0 deletions src/store/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ const mutations = {
};

const actions = {
getCurrentUser() {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged(
user => {
unsubscribe();
resolve(user);
},
() => {
reject();
}
);
});
},
async doLogin({ commit }, { email, password }) {
await auth.signInWithEmailAndPassword(email, password);
commit("setUser", auth.currentUser);
Expand Down
2 changes: 1 addition & 1 deletion src/views/Home.vue → src/views/RoomsView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<script>
import { fb, auth } from "../firebase";
export default {
name: "Home",
name: "RoomsView",
data() {
return {
user: null
Expand Down

0 comments on commit 9f99fbb

Please sign in to comment.