我目前正在使用VueJS SPA、VueJS Router和Laravel构建一个新的 Web 应用程序,用户应该能够以访客(未经身份验证)或登录(经过身份验证)的身份访问页面!
我包括$this->middleware(['auth', 'verified']);
SpaController 以限制对我的页面的访问仅限于经过身份验证的用户,但某些页面(路由)也应该是公开访问的,但它是 SPA 的一部分。
我怎样才能使/:username
,/:username/places
路线可公开访问?beforeEach
在用户注销时使用仍然重定向到一个页面/login
,看起来$this->middleware(['auth', 'verified']);
不允许到达/:username/places
路由!
routes.js
:
import VueRouter from 'vue-router';
import Cities from './views/Cities';
import Places from './views/Places';
import Home from './views/Home';
import Dashboard from './views/Dashboard';
import NotFound from './views/NotFound';
let routes = [
{
path: '/',
name: 'home',
component: Home,
meta: { requiresAuth: true },
},
{
path: '/404',
name: '404',
component: NotFound,
meta: { requiresAuth: false },
},
{
path: '/:username',
name: 'dashboard',
component: Dashboard,
meta: { requiresAuth: false },
children: [
{
path: 'places',
name: 'places',
component: Places,
meta: { requiresAuth: false },
},
]
},
{
path: 'cities',
name: 'cities',
component: Cities,
meta: { requiresAuth: true },
},
{
path: '*',
redirect: '/404'
},
];
const router = new VueRouter ({
mode: 'history',
routes
});
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
next('/test')
} else next()
})
export default router
web.php
:
Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');
Auth::routes(['verify' => true]);
Route::get('/auth/redirect/{provider}', 'Socialite\SocialController@redirect');
Route::get('/callback/{provider}', 'Socialite\SocialController@callback');
Route::get('/{any}', 'SpaController@index')->where('any', '.*');
SpaController.php
:
<?php
namespace App\Http\Controllers;
class SpaController extends Controller
{
// This class and its' functions are available only for authorised and verified users
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
return view('spa');
}
}
spa.blade.php
:
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
@include('layouts.header')
</head>
<body>
<div id="app" class="content">
@include ('layouts.nav')
<main class="py-4">
<div class="container">
<app></app>
</div>
</main>
</div>
@include('layouts.footer')
</body>
</html>