Angular Routes Issue/ routes not considering my token conditioning

I have a an App which have 3 components 1: sellerlogin 2: Sellerhome 3: Home

after login i am redirecting the user to Sellerhome, during login i am storing a token in local storage and checking if the token doesnt exit user should always redirected to login but the issue is even if the token is present in the localstorage i am being able to access the login page can any tell what i am doing wrong?

my login component has a login

login() {
    const foremail = (this.email = this.loginForm.get('email')?.value);
    const formpassword = (this.password =
      this.loginForm.get('password')?.value);
    this.sellerservice.sellerlogin(foremail, formpassword).subscribe((res) => {
      if (res[0].email == foremail && res[0].password == formpassword) {
        localStorage.setItem('token', res[0].email);
        this.router.navigate(['/sellerhome']);
        
      } else {
        alert('Invalid credentials');
      }
    });
  }

and my Authentication Guard has this code

const token = localStorage.getItem('token');

  const router = inject(Router);
  console.log(token);
  if (!token) {
    console.log('false');
    router.navigate(['/sellerlogin']);
    return false;
  } else {
    return true;
  }

this is my routes

  {path:'sellerhome',component:SellerhomeComponent,pathMatch:'full',canActivate:[authguardsGuard]},
  {path:'sellerlogin',component:SellerloginComponent,pathMatch:'full'}

this is my login function in service i know i am using get instead of post but its just for time being.

sellerlogin(email:string,password:string):Observable<any>{
    return this.http.get(`${this.url}?email=${email}&password=${password}`);

  }

after login i am redirecting the user to Sellerhome, during login i am storing a token in local storage and checking if the token doesnt exit user should always redirected to login but the issue is even if the token is present in the localstorage i am being able to access the login page can any tell what i am doing wrong?

Upvotes: 0

Views: 84

Answers (1)

Midhun
Midhun

Reputation: 104

From What i understood, your problem is you can directly access the login route directly even if your token is set in the localstorage.

if that's the case it is probably because you are only setting the route guard to path:'sellerhome' and not to path:'sellerlogin', and the token checking is added to sellerlogin route.

so in order to make this work you may have to add a route guard to sellerlogin too (where it should pass and redirect back to logged in state).

Upvotes: 1

Related Questions