Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - Redirect to another view if user is logged

Tags:

angular

I'm using Authguard and a service called User which they don't allow the access to certain views unless you log in.
So i found a few errors:
1) They can access to login view anyway even they are logged (I added this code in my login.component.ts but still doesn't work).

 isLog() {
if (this.user.getUserLoggedIn() === true) {

  this.router.navigate(['/products']);
} else {
 this.router.navigate(['/login']);
}}

1.1) If they use back/forward/refresh "automatically they log out"(it redirects to login and i have to access again.

Authguard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {UserService} from './user.service';

@Injectable()
export class AuthguardGuard implements CanActivate {
  constructor(private user: UserService) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.user.getUserLoggedIn();
  }
}

userService.ts

import { Injectable } from '@angular/core';

@Injectable()
export class UserService {

  public isUserLoggedIn;
  public matricula;
  constructor() {
    this.isUserLoggedIn = false;
  }

  setUserLoggedIn() {
    this.isUserLoggedIn = true;
  }
  getUserLoggedIn() {
    return this.isUserLoggedIn;
  }
  setUserLoggedOut() {
    this.isUserLoggedIn = false;
  }
}

My routes(added in app.module.ts)

const appRoutes: Routes = [
  {path: 'login',  component: LoginComponent},
  {path: 'cPanel', canActivate: [AuthguardGuard], component: CPanelComponent},
  {path: 'cPanel/producto/crearProducto', canActivate: [AuthguardGuard] , component: CrearProductoComponent},
  {path: 'productos', canActivate: [AuthguardGuard] , component: ProductosComponent},
  {path: 'cPanel/producto/modificarProducto/:id', canActivate: [AuthguardGuard], component: ModificarProductoComponent},
  {path: 'cPanel/usuario/crearUsuario', canActivate: [AuthguardGuard] , component: CrearUsuarioComponent},
  {path: 'cPanel/usuario/modificarUsuario/:id', canActivate: [AuthguardGuard] , component: ModificarUsuarioComponent},
  {path: 'cPanel/menu/modificarMenu/:id', canActivate: [AuthguardGuard], component: ModificarMenuComponent},
  {path: 'cPanel/menu/crearMenu', canActivate: [AuthguardGuard], component: CrearMenuComponent},
  {path: 'menu', canActivate: [AuthguardGuard] , component: MenuComponent},
  {path: '',
    redirectTo: 'login', canActivate: [AuthguardGuard],
    pathMatch: 'full'},
  {path: '**', component: E404Component},
  ];
like image 970
QuickAccount123 Avatar asked Jan 21 '26 04:01

QuickAccount123


1 Answers

Logging in by modifying your existing code slightly

Added the use of localStorage to persist your login information. This, however, might not be the best way to go about it. If you require proper user authentication, you should modify this to use a token (i.e. json web token (JWT) ) to properly verify your user.

userService.ts

import { Injectable } from '@angular/core';

@Injectable()
export class UserService {



public isUserLoggedIn;
  public matricula;
  constructor() {
    this.isUserLoggedIn = false;
    localStorage.setItem('login',this.isUserLoggedIn);
  }

  setUserLoggedIn() {
    this.isUserLoggedIn = true;
    localStorage.setItem('login',this.isUserLoggedIn);
  }
  getUserLoggedIn() {
    return (localStorage.getItem('login') != null ? localStorage.getItem('login') : false);
  }
  setUserLoggedOut() {
    this.isUserLoggedIn = false;
    localStorage.setItem('login',this.isUserLoggedIn);
  }
}

My own Login component for reference

export class LoginComponent implements OnInit {
  private sub: any;
  private results: any;
  title: string = "Login";
  subtitle: string = "Welcome owner";
  constructor(private route: ActivatedRoute, private http: HttpClient, private authService: AuthService, public router: Router) { }

  ngOnInit() {
    if (this.authService.isAuthenticated()) {
      this.router.navigate(['write']); // if user was logged in before, redirect to default landing page
    }
  }
  onSubmit(f: NgForm) {
    var formItems = JSON.stringify(f.value);
    this.authService.login(JSON.stringify(f.value)).subscribe(data => {
      if (data) { // auth service returns boolean value
        this.router.navigate(['write']);
      }
      else {
        console.log("invalid credentials");
      }
    });
  }
}
like image 52
Edwin Chua Avatar answered Jan 23 '26 21:01

Edwin Chua