'Trying to restrict access to a route if loggedIn condition is true
I am trying to restrict access to the login if the user is already logged in by checking if there is already a token in the localStorage. Any idea on how I can fix it ?
import { createRouter, createWebHistory } from "vue-router";
import Login from "./pages/auth/Login";
import Register from "./pages/auth/Register";
import Forgot from "./pages/auth/Forgot";
import Home from "./pages/landing/Home";
import Team from "./pages/landing/Team";
import Prices from "./pages/landing/Prices";
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: "/", redirect: "/home" },
{ path: "/login", component: Login },
{ path: "/register", component: Register },
{ path: "/forgot", component: Forgot },
{ path: "/home", component: Home },
{ path: "/team", component: Team },
{ path: "/prices", component: Prices },
],
});
const loggedIn = !!localStorage.getItem("token");
router.beforeEach((to, from, next) => {
if (to.name !== "Login" && !loggedIn) next({ name: "Login" });
else next("./home");
});
export default router;
Solution 1:[1]
Although, for unauthenticated users the guard will behave as expected, after the user is logged in, every route is redirected to "/home". Instead, you should call next()
without options, and let the router navigate to initial location.
router.beforeEach((to, from, next) => {
if (to.name !== "Login" && !loggedIn) next({ name: "Login" });
else next();
});
Also, since it seems that you are using vue-router
v4, you can dump next
argument (it is deprecated now) and just return the route.
router.beforeEach((to, from) => {
if (to.name !== "Login" && !loggedIn) return { name: "Login" };
});
Also, as a side note, next("./home")
does not look right. It is not a path but a url: next("/home")
Solution 2:[2]
just you can add a middleware to your route like this:
Route::get('/login',[CustomAuthController::class,'login'])->middleware('alreadyLoggedIn');
and this is a middleware example:
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId') && (url('login')==$request->url()|| url('registration')
==$request->url())){
return back();
}
return $next($request);
}
Solution 3:[3]
Sample code for route :
Route::get('login',[AuthController::class,'login'])->middleware('CurrentlyLoggedIn');
Sample code for middleware :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CurrentlyLoggedIn
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if(session()->has('loginId')
&& (url('login') == $request->url() || url('registration') == $request->url())){
return back();
}
return $next($request);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Igor Moraru |
Solution 2 | a bcd |
Solution 3 | AlirezaAhmadi |