Reputation: 189
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},
];
Upvotes: 3
Views: 5309
Reputation: 690
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");
}
});
}
}
Upvotes: 2
Reputation: 271
login.component.ts
constructor(
private userService : UserService,
private router: Router
) {
if (this.loginService.getLogin()) {
this.router.navigate(['product'])
}
}
This will automatically redirect you to '/product' if you accidentally go back, but won't persist if you reload the page
If you want your login data to persist (refresh, etc) you should use session storage or cookies in your userService to store your login data
userService.ts
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
login: boolean = false;
storage: Storage;
constructor() {
this.storage = window.localStorage;
if (this.storage.getItem('login')) {
this.login = this.storage.getItem('login') == 'true'
}
}
setLogin(val:boolean) {
this.login = val
this.storage.setItem('login',val == true ? 'true' : 'false')
}
getLogin() {
return this.login
}
}
EDIT : working example on plunker https://plnkr.co/edit/XsGhXgte3woDfpKJdLxP?p=info
Also, I'm using a simple value just for the example, this is a good read about using json web tokens for auth : http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial
Upvotes: 2