4
votes

I have different routes on my applications:

GET /game/{any}

This route is protected by Laravel auth middleware. Inside this Laravel route I want to build SPA and provide Vue router:

const routes = [
  { path: '/game/start', component: GameStart },
  { path: '/game/stats', component: GameStats }
]

And I have 'main' route which is not protected by any Laravel Middleware

GET /{any}

Whole Vue Router looks like this:

const routes = [
      // Not protected URLs
      { path: '/', component: Main },
      { path: '/news', component: News },

      // Protected URLs
      { path: '/game/start', component: GameStart },
      { path: '/game/stats', component: GameStats }
    ]

So my question is: Is it good idea to mixed up back-end and front-end like this? Because I'm assuming that '/game/*' routers is not protected on front-end part.

Or should I use Laravel Passport and token auth on frond-end?

1

1 Answers

1
votes

You should use Laravel Passport and token auth on the front end using vue-router meta and callback (beforeEach).

routes.js

...

export const routes = [
  { path: '/game/start', component: GameStart, meta: { requiresAuth: true } },
  { path: '/game/stats', component: GameStats, meta: { requiresAuth: true } },
  { path: '/signin', component: SigninPage },
  { path: '*', redirec: '/' }
];

router.js

import VueRouter from 'vue-router';
import { routes } from './routes';
import store from './store'

export const router = new VueRouter({
  routes,
  mode: 'history'
});

router.beforeEach((to, from, next) => {
  // you could define your own authentication logic with token
  let isAuthenticated = store.getters.isAuthenticated

  // check route meta if it requires auth or not
  if(to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
          path: '/signin',
          params: { nextUrl: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router