Dev Teywa

Dev Teywa

  • 1.9k
  • 250
  • 30.9k

how to verify if user is authenticated using angular2

Jan 25 2018 5:28 AM
I have a home page and login I want if the user is not logged I redirect him to the login page to authenticat
 
here is my script
 
login.component.ts  
  1. import { Component } from '@angular/core';  
  2. import {Routes, RouterModule} from '@angular/router';  
  3. import { Router } from '@angular/router';  
  4. import {AuthenticationService,User} from './data.service'  
  5.   
  6. @Component({  
  7.   selector: 'my-login',  
  8.   providers: [AuthenticationService],  
  9.     template: `  
  10.         <div class="container" >  
  11.             <div class="title">  
  12.                 Welcome  
  13.             div>  
  14.             <div class="panel-body">  
  15.                 <div class="row">  
  16.                     <div class="input-field col s12">  
  17.                         <input [(ngModel)]="user.email" id="email"   
  18.                             type="email" class="validate">  
  19.                         <label for="email">Emaillabel>  
  20.                     div>  
  21.                 div>  
  22.    
  23.                 <div class="row">  
  24.                     <div class="input-field col s12">  
  25.                         <input [(ngModel)]="user.password" id="password"   
  26.                             type="password" class="validate">  
  27.                         <label for="password">Passwordlabel>  
  28.                     div>  
  29.                 div>  
  30.    
  31.                 <span>{{errorMsg}}span>  
  32.                 <button (click)="login()"   
  33.                     class="btn waves-effect waves-light"   
  34.                     type="submit" name="action">Loginbutton>    
  35.   
  36.                     <li class="active"><a [routerLink]='["/register"]'>Registera>li>  
  37.             div>  
  38.         div>  
  39.         `  
  40. })  
  41. export class LoginComponent    
  42. {   
  43.   public user = new User('','');  
  44.   public errorMsg = '';  
  45.   
  46. constructor(  
  47.     private _service:AuthenticationService) {}  
  48.   
  49.     ngOnInit()  
  50.     {  
  51.         this._service.add_user(this.user);  
  52.     }  
  53.   
  54. login() {  
  55.     if(!this._service.login(this.user)){  
  56.         this.errorMsg = 'Failed to login';  
  57.     }  
  58. }  
  59.   
  60. }  
data.service.ts
  1. import {Injectable} from '@angular/core';  
  2. import {Router} from '@angular/router';  
  3.    
  4. export class User {  
  5.   constructor(  
  6.     public email: string,  
  7.     public password: string) { this.email=email;this.password=password}  
  8. }  
  9.   
  10.   
  11.   
  12.    
  13. @Injectable()  
  14. export class AuthenticationService {  
  15.   
  16.  users :User[]= [  
  17.     new User('admin@admin.com','adm'),  
  18.     new User('user1@gmail.com','a23'),  
  19.     new User('a@gmail.com','a')   
  20.   ];  
  21.   constructor(  
  22.     private _router: Router){}  
  23.    
  24.   logout() {  
  25.     localStorage.removeItem("user");  
  26.     this._router.navigate(['Login']);  
  27.   }  
  28.     
  29.   login(user :any){  
  30.     var authenticatedUser :any = this.users.find(u => u.email === user.email);  
  31.     if (authenticatedUser && authenticatedUser.password === user.password)  
  32.     {  
  33.       localStorage.setItem("user", authenticatedUser)  
  34.       this._router.navigate(['home']);   
  35.       console.log(this.users)       
  36.       return true;  
  37.     }  
  38.     return false;  
  39.    
  40.   }  
  41.   
  42.   add_user(usr:User)  
  43.   {   
  44.       
  45.     var authenticatedUser :any = this.users.push.call(new User(usr.email,usr.password));  
  46.     localStorage.setItem("usr",authenticatedUser);  
  47.     this._router.navigate(['login'])  
  48.     console.log(this.users)  
  49.   
  50.   }  
  51.   
  52.    checkCredentials(){  
  53.     if (localStorage.getItem("user") === null){  
  54.         this._router.navigate(['login']);  
  55.     }  
  56.   }   
  57. }  
home.component.ts 
  1. import { Component, OnInit } from '@angular/core';  
  2. import {AuthenticationService,User} from './data.service'  
  3.   
  4. @Component({  
  5.   selector: 'my-home',  
  6.   providers: [AuthenticationService],  
  7.     template: `  
  8.             <div class="container" >  
  9.                 <div class="content">  
  10.                     <span>Congratulations, you have successfully logged in!!span>  
  11.                     <br />  
  12.                     <a (click)="logout()" href="#">Click Here to logouta>  
  13.                 div>  
  14.             div>  
  15.         `  
  16. })  
  17. export class HomeComponent  {  
  18.   
  19.   constructor(  
  20.     private _service:AuthenticationService){}  
  21.   
  22. ngOnInit(){  
  23.     this._service.checkCredentials();  
  24. }  
  25.   
  26. logout() {  
  27.     this._service.logout();  
  28. }  
  29.   
  30.  }  
and thanks in advance  

Answers (2)