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},
];
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.
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);
}
}
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");
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With