Created
June 22, 2018 20:22
-
-
Save JCKodel/ed916760adef5d8d702f94611013e9cc to your computer and use it in GitHub Desktop.
Intercept Framework7 routes for authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import EventBus from "@/eventBus"; // A simple new Vue() event bus | |
import store from "@/store"; | |
import HomePage from "./pages/index.vue"; | |
import NotFoundPage from "./pages/404.vue"; | |
import CustomersHomePage from "./pages/customers/index.vue"; | |
import CustomersCategoriesPage from "./pages/customers/categories.vue"; | |
const routes = | |
[ | |
{ | |
path: "/", | |
component: HomePage, // Anonymous page | |
}, | |
{ | |
path: "/customers/", | |
secureComponent: CustomersHomePage, // "Only for authorized users" page | |
}, | |
{ | |
path: "/customers/categories/", | |
secureComponent: CustomersCategoriesPage, // "Only for authorized users" page | |
}, | |
{ | |
path: "(.*)", | |
component: NotFoundPage, | |
}, | |
]; | |
for(const route of routes) | |
{ | |
if(route.secureComponent) // If page is defined as secure... | |
{ | |
route.async = function(routeTo, routeFrom, resolve, reject) | |
{ | |
if(store.state.user.isAuthenticated) // ...check if user is authenticated... | |
{ | |
const newRoute = { path: routeTo.route.path, component: routeTo.route.secureComponent }; | |
resolve(newRoute); // ...if so, keep going... | |
} | |
else | |
{ | |
reject(); // For anonymous user, reject the navigation... | |
let url = routeTo.route.path; | |
if(routeTo.params) | |
{ | |
for(const p in routeTo.params) // ...generate a "would go to" url with the parameters... | |
{ | |
url = url.replace(new RegExp(`:${p}`, "gi"), routeTo.params[p]); | |
} | |
} | |
store.dispatch("login", { returnUrl: url }); // ...this vuex action would show a login popup | |
// setting the this.$store.state.login.returnUrl for the returnUrl (the url that would be | |
// loaded, if user were authenticated). | |
// on the app.vue (where the login popup is), a @popup:closed event handler would check the | |
// authentication success and then redirect the user to the this.$store.state.login.returnUrl | |
/* | |
if(this.$store.state.user.isAuthenticated && this.$store.state.login.returnUrl) | |
{ | |
this.$f7.router.navigate(this.$store.state.login.returnUrl); | |
} | |
*/ | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment