Ionic 4 and Angular 7 Tutorial: Securing Pages using Route Guard

The comprehensive step by step tutorial on securing pages using Ionic 4 and Angular 7 Route Guard

The Ionic 4 and Angular 7 app similar with the previous tutorial except add the Route Guard to securing the restricted page. The workflow diagram below shows the flow of the whole application.

Ionic 4 and Angular 7 Tutorial

Table of Contents:

  • Create a new Ionic 4 and Angular 7 App
  • Create a custom Angular 7 HttpInterceptor
  • Create Ionic 4 Angular 7 Authentication and Book Services
  • Create an Ionic 4 and Angular 7 Page for Displaying Books
  • Create the Ionic 4 and Angular 7 Pages for Login and Register
  • Secure the Guarded Book Page using Angular 7 Route Guard
  • Run and Test the Ionic 4 and Angular 7 Securing Pages using Route Guard

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
5.0.2

1. Create a new Ionic 4 and Angular 7 App

To create a new Ionic 4 and Angular 7 application, type this command in your terminal.

ionic start ionic4-angular7-routeguard blank --type=angular

If you see this question, just type N for because we will installing or adding Cordova later.

Integrate your new app with Cordova to target native iOS and Android? (y/N) N

After installing [NPM](https://morioh.com/topic/npm) modules and dependencies, you will see this question, just type N because we are not using it yet.

Install the free Ionic Pro SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-angular7-routeguard

As usual, run the Ionic 4 and Angular 7 app for the first time, but before run as lab mode, type this command to install @ionic/lab.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 and Angular 7 app with the iOS, Android, or Windowsview. If you see a normal Ionic 4 blank application, that’s mean you ready to go to the next steps.

Ionic 4 and Angular 7 Tutorial

2. Create a custom Ionic 4 Angular 7 HttpInterceptor

Before creating a custom Angular 7 HttpInterceptor, create a folder under app folder.

mkdir src/app/interceptors

Next, create a file for the custom Angular 7 HttpInterceptor.

touch src/app/interceptors/token.interceptor.ts

Open and edit that file the add these imports.

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import {
  Router
} from '@angular/router';
import { ToastController } from '@ionic/angular';

Create a class that implementing HttpInterceptor method.

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

}

Inject the required module to the constructor inside the class.

constructor(private router: Router,
  public toastController: ToastController) {}

Implement a custom Interceptor function.

intercept(request: HttpRequest, next: HttpHandler): Observable> {

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

  if (token) {
    request = request.clone({
      setHeaders: {
        'Authorization': token
      }
    });
  }

  if (!request.headers.has('Content-Type')) {
    request = request.clone({
      setHeaders: {
        'content-type': 'application/json'
      }
    });
  }

  request = request.clone({
    headers: request.headers.set('Accept', 'application/json')
  });

  return next.handle(request).pipe(
    map((event: HttpEvent) => {
      if (event instanceof HttpResponse) {
        console.log('event--->>>', event);
      }
      return event;
    }),
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        if (error.error.success === false) {
          this.presentToast('Login failed');
        } else {
          this.router.navigate(['login']);
        }
      }
      return throwError(error);
    }));
}

Add function for call a toast controller.

async presentToast(msg) {
  const toast = await this.toastController.create({
    message: msg,
    duration: 2000,
    position: 'top'
  });
  toast.present();
}

Next, we have to register this custom HttpInterceptor and HttpClientModule. Open and edit src/app/app.module.ts then add this imports.

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { TokenInterceptor } from './inteceptors/token.interceptor';

Add those modules to the provider array of the @NgModule.

providers: [
  StatusBar,
  SplashScreen,
  { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
  {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
  }
],

Now, the HTTP interceptor is ready to intercept any request to the API.

3. Create Ionic 4 Angular 7 Authentication and Book Services

First, create a folder for those services under src/app/.

mkdir src/app/services

Create services or providers for authentication and book.

ionic g service services/auth
ionic g service services/book

Next, open and edit src/app/services/auth.service.ts then replace all codes with this.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  apiUrl = 'http://localhost:3000/api/';
  isLoggedIn = false;
  redirectUrl: string;

  constructor(private http: HttpClient) { }

  login(data: any): Observable {
    return this.http.post(this.apiUrl + 'signin', data)
      .pipe(
        tap(_ => this.isLoggedIn = true),
        catchError(this.handleError('login', []))
      );
  }

  logout(): Observable {
    return this.http.get(this.apiUrl + 'signout')
      .pipe(
        tap(_ => this.isLoggedIn = false),
        catchError(this.handleError('logout', []))
      );
  }

  register(data: any): Observable {
    return this.http.post(this.apiUrl + 'signup', data)
      .pipe(
        tap(_ => this.log('login')),
        catchError(this.handleError('login', []))
      );
  }

  private handleError(operation = 'operation', result?: T) {
    return (error: any): Observable => {
      console.error(error); // log to console instead
      this.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }

  private log(message: string) {
    console.log(message);
  }
}

Next, open and edit src/app/services/book.service then replace all codes with this.

import { Injectable } from '@angular/core';
import { Book } from '../book/book';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BookService {

  apiUrl = 'http://localhost:3000/api/';

  constructor(private http: HttpClient) { }

  getBooks (): Observable {
    return this.http.get(this.apiUrl + 'book')
      .pipe(
        tap(_ => this.log('fetched books')),
        catchError(this.handleError('getBooks', []))
      );
  }

  private handleError (operation = 'operation', result?: T) {
    return (error: any): Observable => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  /** Log a HeroService message with the MessageService */
  private log(message: string) {
    console.log(message);
  }
}

4. Create an Ionic 4 and Angular 7 Page for Displaying Books

Type this command to generate an Ionic 4 and Angular 7 page for the book.

ionic g page book

Create a Typescript file for handle Book object or as a model for Book object.

touch src/app/book/book.ts

Open end edit that file then replaces all codes with this.

export class Book {
  _id: number;
  isbn: string;
  title: string;
  author: number;
  publisher: Date;
  __v: number;
}

Next, open and edit src/app/book/book.page.ts then add this imports.

import { Book } from './book';
import { BookService } from '../services/book.service';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

Inject all required modules to the constructor.

constructor(private bookService: BookService,
  private authService: AuthService,
  private router: Router) { }

Declare this variable before the constructor.

books: Book[];

Create a function for consuming or get a book list from the BookService.

getBooks(): void {
  this.bookService.getBooks()
    .subscribe(books => {
      console.log(books);
      this.books = books;
    });
}

Call this function from ngOnInit.

ngOnInit() {
  this.getBooks();
}

Add a function for log out the current session.

logout() {
  this.authService.logout()
    .subscribe(res => {
      console.log(res);
      localStorage.removeItem('token');
      this.router.navigate(['home']);
    });
}

Next, open and edit src/app/book/book.page.html then replace all HTML tags with this.


  
    List of Books
    
      
        
      
    
  



  
    
      {{b.title}}
    
  

The book page just shows the list of the book and log out button on the title bar.

5. Create the Ionic 4 and Angular 7 Pages for Login and Register

Before creating that pages, create this folder under src/app.

mkdir src/app/auth

Now, generate the Ionic 4 and Angular 7 pages.

ionic g page auth/login
ionic g page auth/register

Next, open and edit src/app/auth/login/login.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  loginForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
    private router: Router,
    private authService: AuthService,
    public toastController: ToastController) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      'username' : [null, Validators.required],
      'password' : [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    this.authService.login(form)
      .subscribe(res => {
        if (res.token) {
          localStorage.setItem('token', res.token);
          this.router.navigate(['book']);
        }
      }, (err) => {
        console.log(err);
      });
  }

  register() {
    this.router.navigate(['register']);
  }

  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }

}

Next, open and edit src/app/auth/login/login.module.ts then add the import of ReactiveFormsModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add that module to the @NgModule imports array.

imports: [
  CommonModule,
  FormsModule,
  IonicModule,
  ReactiveFormsModule,
  RouterModule.forChild(routes)
],

Next, open and edit src/app/auth/login/login.page.html then replace all HTML tags with this.


  
    
      
        Please, Sign In
      
      
        
          Username
          
        
        
          Password
          
        
        
          Login
        
        
          Register
        
      
    
  

Next, open and edit src/app/auth/register/register.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController, AlertController } from '@ionic/angular';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {

  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
    private router: Router,
    private authService: AuthService,
    public toastController: ToastController,
    public alertController: AlertController) { }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      'username' : [null, Validators.required],
      'password' : [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    this.authService.register(form)
      .subscribe(_ => {
        this.presentAlert('Register Successfully', 'Please login with your new username and password');
      }, (err) => {
        console.log(err);
      });
  }

  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }

  async presentAlert(header, message) {
    const alert = await this.alertController.create({
      header: header,
      message: message,
      buttons: [{
          text: 'OK',
          handler: () => {
            this.router.navigate(['login']);
          }
        }]
    });

    await alert.present();
  }

}

Next, open and edit src/app/auth/register/register.module.ts then add the import of ReactiveFormsModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add that module to the @NgModule imports array.

imports: [
  CommonModule,
  FormsModule,
  IonicModule,
  ReactiveFormsModule,
  RouterModule.forChild(routes)
],

Open and edit src/app/auth/register/register.page.html then replace all HTML tags with this.


  
    
      
    
    Register
  



  
    
      
        Register here
      
      
        
          Username
          
        
        
          Password
          
        
        
          Register
        
      
    
  

6. Secure the Guarded Book Page using Angular 7 Route Guard

This is the main part of the Ionic 4 tutorial. Type this command to generate a guard configuration file.

ng generate guard auth/auth

Open and edit that file then add this Angular 7 / Typescript imports.

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';

Next, add this implements code to the Class name.

export class AuthGuard implements CanActivate

Inject the AuthService and the Router to the constructor params.

constructor(private authService: AuthService, private router: Router) {}

Add the function for the Route Guard.

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): boolean {
  const url: string = state.url;

  return this.checkLogin(url);
}

Add the function to check the login status and redirect to the login page if it’s not logged in and redirect to the Guarded page if it’s logged in.

checkLogin(url: string): boolean {
  if (this.authService.isLoggedIn) { return true; }

  // Store the attempted URL for redirecting
  this.authService.redirectUrl = url;

  // Navigate to the login page with extras
  this.router.navigate(['/login']);
  return false;
}

Next, open and edit src/app/app-routing.module.ts then add this import.

import { AuthGuard } from './auth/auth.guard';

Modify the book path, so it will look like this.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'book', canActivate: [AuthGuard], loadChildren: './book/book.module#BookPageModule' },
  { path: 'login', loadChildren: './auth/login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './auth/register/register.module#RegisterPageModule' },
];

7. Run and Test the Ionic 4 and Angular 7 Securing Pages using Route Guard

Before run and the test the Ionic 4 and Angular 7 secure application, open the new terminal tab to run the MongoDB database.

mongod

In the other tab run the Node.js and Express.js secure REST API.

nodemon

In the main terminal tab run the Ionic 4 and Angular 7 application.

ionic serve -l

That it’s, the Ionic 4 and Angular 7 Securing Pages using Route Guard. You can find the full source code from our GitHub.

#angular #ionic

What is GEEK

Buddha Community

Ionic 4 and Angular 7 Tutorial: Securing Pages using Route Guard

Ionic 4 and Angular 7 Tutorial: Securing Pages using Route Guard

The comprehensive step by step tutorial on securing pages using Ionic 4 and Angular 7 Route Guard

The Ionic 4 and Angular 7 app similar with the previous tutorial except add the Route Guard to securing the restricted page. The workflow diagram below shows the flow of the whole application.

Ionic 4 and Angular 7 Tutorial

Table of Contents:

  • Create a new Ionic 4 and Angular 7 App
  • Create a custom Angular 7 HttpInterceptor
  • Create Ionic 4 Angular 7 Authentication and Book Services
  • Create an Ionic 4 and Angular 7 Page for Displaying Books
  • Create the Ionic 4 and Angular 7 Pages for Login and Register
  • Secure the Guarded Book Page using Angular 7 Route Guard
  • Run and Test the Ionic 4 and Angular 7 Securing Pages using Route Guard

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
5.0.2

1. Create a new Ionic 4 and Angular 7 App

To create a new Ionic 4 and Angular 7 application, type this command in your terminal.

ionic start ionic4-angular7-routeguard blank --type=angular

If you see this question, just type N for because we will installing or adding Cordova later.

Integrate your new app with Cordova to target native iOS and Android? (y/N) N

After installing [NPM](https://morioh.com/topic/npm) modules and dependencies, you will see this question, just type N because we are not using it yet.

Install the free Ionic Pro SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-angular7-routeguard

As usual, run the Ionic 4 and Angular 7 app for the first time, but before run as lab mode, type this command to install @ionic/lab.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 and Angular 7 app with the iOS, Android, or Windowsview. If you see a normal Ionic 4 blank application, that’s mean you ready to go to the next steps.

Ionic 4 and Angular 7 Tutorial

2. Create a custom Ionic 4 Angular 7 HttpInterceptor

Before creating a custom Angular 7 HttpInterceptor, create a folder under app folder.

mkdir src/app/interceptors

Next, create a file for the custom Angular 7 HttpInterceptor.

touch src/app/interceptors/token.interceptor.ts

Open and edit that file the add these imports.

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import {
  Router
} from '@angular/router';
import { ToastController } from '@ionic/angular';

Create a class that implementing HttpInterceptor method.

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

}

Inject the required module to the constructor inside the class.

constructor(private router: Router,
  public toastController: ToastController) {}

Implement a custom Interceptor function.

intercept(request: HttpRequest, next: HttpHandler): Observable> {

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

  if (token) {
    request = request.clone({
      setHeaders: {
        'Authorization': token
      }
    });
  }

  if (!request.headers.has('Content-Type')) {
    request = request.clone({
      setHeaders: {
        'content-type': 'application/json'
      }
    });
  }

  request = request.clone({
    headers: request.headers.set('Accept', 'application/json')
  });

  return next.handle(request).pipe(
    map((event: HttpEvent) => {
      if (event instanceof HttpResponse) {
        console.log('event--->>>', event);
      }
      return event;
    }),
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        if (error.error.success === false) {
          this.presentToast('Login failed');
        } else {
          this.router.navigate(['login']);
        }
      }
      return throwError(error);
    }));
}

Add function for call a toast controller.

async presentToast(msg) {
  const toast = await this.toastController.create({
    message: msg,
    duration: 2000,
    position: 'top'
  });
  toast.present();
}

Next, we have to register this custom HttpInterceptor and HttpClientModule. Open and edit src/app/app.module.ts then add this imports.

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { TokenInterceptor } from './inteceptors/token.interceptor';

Add those modules to the provider array of the @NgModule.

providers: [
  StatusBar,
  SplashScreen,
  { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
  {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
  }
],

Now, the HTTP interceptor is ready to intercept any request to the API.

3. Create Ionic 4 Angular 7 Authentication and Book Services

First, create a folder for those services under src/app/.

mkdir src/app/services

Create services or providers for authentication and book.

ionic g service services/auth
ionic g service services/book

Next, open and edit src/app/services/auth.service.ts then replace all codes with this.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  apiUrl = 'http://localhost:3000/api/';
  isLoggedIn = false;
  redirectUrl: string;

  constructor(private http: HttpClient) { }

  login(data: any): Observable {
    return this.http.post(this.apiUrl + 'signin', data)
      .pipe(
        tap(_ => this.isLoggedIn = true),
        catchError(this.handleError('login', []))
      );
  }

  logout(): Observable {
    return this.http.get(this.apiUrl + 'signout')
      .pipe(
        tap(_ => this.isLoggedIn = false),
        catchError(this.handleError('logout', []))
      );
  }

  register(data: any): Observable {
    return this.http.post(this.apiUrl + 'signup', data)
      .pipe(
        tap(_ => this.log('login')),
        catchError(this.handleError('login', []))
      );
  }

  private handleError(operation = 'operation', result?: T) {
    return (error: any): Observable => {
      console.error(error); // log to console instead
      this.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }

  private log(message: string) {
    console.log(message);
  }
}

Next, open and edit src/app/services/book.service then replace all codes with this.

import { Injectable } from '@angular/core';
import { Book } from '../book/book';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BookService {

  apiUrl = 'http://localhost:3000/api/';

  constructor(private http: HttpClient) { }

  getBooks (): Observable {
    return this.http.get(this.apiUrl + 'book')
      .pipe(
        tap(_ => this.log('fetched books')),
        catchError(this.handleError('getBooks', []))
      );
  }

  private handleError (operation = 'operation', result?: T) {
    return (error: any): Observable => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  /** Log a HeroService message with the MessageService */
  private log(message: string) {
    console.log(message);
  }
}

4. Create an Ionic 4 and Angular 7 Page for Displaying Books

Type this command to generate an Ionic 4 and Angular 7 page for the book.

ionic g page book

Create a Typescript file for handle Book object or as a model for Book object.

touch src/app/book/book.ts

Open end edit that file then replaces all codes with this.

export class Book {
  _id: number;
  isbn: string;
  title: string;
  author: number;
  publisher: Date;
  __v: number;
}

Next, open and edit src/app/book/book.page.ts then add this imports.

import { Book } from './book';
import { BookService } from '../services/book.service';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

Inject all required modules to the constructor.

constructor(private bookService: BookService,
  private authService: AuthService,
  private router: Router) { }

Declare this variable before the constructor.

books: Book[];

Create a function for consuming or get a book list from the BookService.

getBooks(): void {
  this.bookService.getBooks()
    .subscribe(books => {
      console.log(books);
      this.books = books;
    });
}

Call this function from ngOnInit.

ngOnInit() {
  this.getBooks();
}

Add a function for log out the current session.

logout() {
  this.authService.logout()
    .subscribe(res => {
      console.log(res);
      localStorage.removeItem('token');
      this.router.navigate(['home']);
    });
}

Next, open and edit src/app/book/book.page.html then replace all HTML tags with this.


  
    List of Books
    
      
        
      
    
  



  
    
      {{b.title}}
    
  

The book page just shows the list of the book and log out button on the title bar.

5. Create the Ionic 4 and Angular 7 Pages for Login and Register

Before creating that pages, create this folder under src/app.

mkdir src/app/auth

Now, generate the Ionic 4 and Angular 7 pages.

ionic g page auth/login
ionic g page auth/register

Next, open and edit src/app/auth/login/login.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  loginForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
    private router: Router,
    private authService: AuthService,
    public toastController: ToastController) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      'username' : [null, Validators.required],
      'password' : [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    this.authService.login(form)
      .subscribe(res => {
        if (res.token) {
          localStorage.setItem('token', res.token);
          this.router.navigate(['book']);
        }
      }, (err) => {
        console.log(err);
      });
  }

  register() {
    this.router.navigate(['register']);
  }

  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }

}

Next, open and edit src/app/auth/login/login.module.ts then add the import of ReactiveFormsModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add that module to the @NgModule imports array.

imports: [
  CommonModule,
  FormsModule,
  IonicModule,
  ReactiveFormsModule,
  RouterModule.forChild(routes)
],

Next, open and edit src/app/auth/login/login.page.html then replace all HTML tags with this.


  
    
      
        Please, Sign In
      
      
        
          Username
          
        
        
          Password
          
        
        
          Login
        
        
          Register
        
      
    
  

Next, open and edit src/app/auth/register/register.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController, AlertController } from '@ionic/angular';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {

  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
    private router: Router,
    private authService: AuthService,
    public toastController: ToastController,
    public alertController: AlertController) { }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      'username' : [null, Validators.required],
      'password' : [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    this.authService.register(form)
      .subscribe(_ => {
        this.presentAlert('Register Successfully', 'Please login with your new username and password');
      }, (err) => {
        console.log(err);
      });
  }

  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }

  async presentAlert(header, message) {
    const alert = await this.alertController.create({
      header: header,
      message: message,
      buttons: [{
          text: 'OK',
          handler: () => {
            this.router.navigate(['login']);
          }
        }]
    });

    await alert.present();
  }

}

Next, open and edit src/app/auth/register/register.module.ts then add the import of ReactiveFormsModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add that module to the @NgModule imports array.

imports: [
  CommonModule,
  FormsModule,
  IonicModule,
  ReactiveFormsModule,
  RouterModule.forChild(routes)
],

Open and edit src/app/auth/register/register.page.html then replace all HTML tags with this.


  
    
      
    
    Register
  



  
    
      
        Register here
      
      
        
          Username
          
        
        
          Password
          
        
        
          Register
        
      
    
  

6. Secure the Guarded Book Page using Angular 7 Route Guard

This is the main part of the Ionic 4 tutorial. Type this command to generate a guard configuration file.

ng generate guard auth/auth

Open and edit that file then add this Angular 7 / Typescript imports.

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';

Next, add this implements code to the Class name.

export class AuthGuard implements CanActivate

Inject the AuthService and the Router to the constructor params.

constructor(private authService: AuthService, private router: Router) {}

Add the function for the Route Guard.

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): boolean {
  const url: string = state.url;

  return this.checkLogin(url);
}

Add the function to check the login status and redirect to the login page if it’s not logged in and redirect to the Guarded page if it’s logged in.

checkLogin(url: string): boolean {
  if (this.authService.isLoggedIn) { return true; }

  // Store the attempted URL for redirecting
  this.authService.redirectUrl = url;

  // Navigate to the login page with extras
  this.router.navigate(['/login']);
  return false;
}

Next, open and edit src/app/app-routing.module.ts then add this import.

import { AuthGuard } from './auth/auth.guard';

Modify the book path, so it will look like this.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'book', canActivate: [AuthGuard], loadChildren: './book/book.module#BookPageModule' },
  { path: 'login', loadChildren: './auth/login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './auth/register/register.module#RegisterPageModule' },
];

7. Run and Test the Ionic 4 and Angular 7 Securing Pages using Route Guard

Before run and the test the Ionic 4 and Angular 7 secure application, open the new terminal tab to run the MongoDB database.

mongod

In the other tab run the Node.js and Express.js secure REST API.

nodemon

In the main terminal tab run the Ionic 4 and Angular 7 application.

ionic serve -l

That it’s, the Ionic 4 and Angular 7 Securing Pages using Route Guard. You can find the full source code from our GitHub.

#angular #ionic

Wilford  Pagac

Wilford Pagac

1596789120

Best Custom Web & Mobile App Development Company

Everything around us has become smart, like smart infrastructures, smart cities, autonomous vehicles, to name a few. The innovation of smart devices makes it possible to achieve these heights in science and technology. But, data is vulnerable, there is a risk of attack by cybercriminals. To get started, let’s know about IoT devices.

What are IoT devices?

The Internet Of Things(IoT) is a system that interrelates computer devices like sensors, software, and actuators, digital machines, etc. They are linked together with particular objects that work through the internet and transfer data over devices without humans interference.

Famous examples are Amazon Alexa, Apple SIRI, Interconnected baby monitors, video doorbells, and smart thermostats.

How could your IoT devices be vulnerable?

When technologies grow and evolve, risks are also on the high stakes. Ransomware attacks are on the continuous increase; securing data has become the top priority.

When you think your smart home won’t fudge a thing against cybercriminals, you should also know that they are vulnerable. When cybercriminals access our smart voice speakers like Amazon Alexa or Apple Siri, it becomes easy for them to steal your data.

Cybersecurity report 2020 says popular hacking forums expose 770 million email addresses and 21 million unique passwords, 620 million accounts have been compromised from 16 hacked websites.

The attacks are likely to increase every year. To help you secure your data of IoT devices, here are some best tips you can implement.

Tips to secure your IoT devices

1. Change Default Router Name

Your router has the default name of make and model. When we stick with the manufacturer name, attackers can quickly identify our make and model. So give the router name different from your addresses, without giving away personal information.

2. Know your connected network and connected devices

If your devices are connected to the internet, these connections are vulnerable to cyber attacks when your devices don’t have the proper security. Almost every web interface is equipped with multiple devices, so it’s hard to track the device. But, it’s crucial to stay aware of them.

3. Change default usernames and passwords

When we use the default usernames and passwords, it is attackable. Because the cybercriminals possibly know the default passwords come with IoT devices. So use strong passwords to access our IoT devices.

4. Manage strong, Unique passwords for your IoT devices and accounts

Use strong or unique passwords that are easily assumed, such as ‘123456’ or ‘password1234’ to protect your accounts. Give strong and complex passwords formed by combinations of alphabets, numeric, and not easily bypassed symbols.

Also, change passwords for multiple accounts and change them regularly to avoid attacks. We can also set several attempts to wrong passwords to set locking the account to safeguard from the hackers.

5. Do not use Public WI-FI Networks

Are you try to keep an eye on your IoT devices through your mobile devices in different locations. I recommend you not to use the public WI-FI network to access them. Because they are easily accessible through for everyone, you are still in a hurry to access, use VPN that gives them protection against cyber-attacks, giving them privacy and security features, for example, using Express VPN.

6. Establish firewalls to discover the vulnerabilities

There are software and firewalls like intrusion detection system/intrusion prevention system in the market. This will be useful to screen and analyze the wire traffic of a network. You can identify the security weakness by the firewall scanners within the network structure. Use these firewalls to get rid of unwanted security issues and vulnerabilities.

7. Reconfigure your device settings

Every smart device comes with the insecure default settings, and sometimes we are not able to change these default settings configurations. These conditions need to be assessed and need to reconfigure the default settings.

8. Authenticate the IoT applications

Nowadays, every smart app offers authentication to secure the accounts. There are many types of authentication methods like single-factor authentication, two-step authentication, and multi-factor authentication. Use any one of these to send a one time password (OTP) to verify the user who logs in the smart device to keep our accounts from falling into the wrong hands.

9. Update the device software up to date

Every smart device manufacturer releases updates to fix bugs in their software. These security patches help us to improve our protection of the device. Also, update the software on the smartphone, which we are used to monitoring the IoT devices to avoid vulnerabilities.

10. Track the smartphones and keep them safe

When we connect the smart home to the smartphone and control them via smartphone, you need to keep them safe. If you miss the phone almost, every personal information is at risk to the cybercriminals. But sometimes it happens by accident, makes sure that you can clear all the data remotely.

However, securing smart devices is essential in the world of data. There are still cybercriminals bypassing the securities. So make sure to do the safety measures to avoid our accounts falling out into the wrong hands. I hope these steps will help you all to secure your IoT devices.

If you have any, feel free to share them in the comments! I’d love to know them.

Are you looking for more? Subscribe to weekly newsletters that can help your stay updated IoT application developments.

#iot #enterprise iot security #how iot can be used to enhance security #how to improve iot security #how to protect iot devices from hackers #how to secure iot devices #iot security #iot security devices #iot security offerings #iot security technologies iot security plus #iot vulnerable devices #risk based iot security program

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Einar  Hintz

Einar Hintz

1594631472

Pros and Cons of Ionic Development

Entrepreneurs around the world want a top-notch mobile application for their business in both Android and iOS platforms. Most of them get stuck mid-way where they struggle to pick the best technology suitable for their business. From questions such as native mobile development or cross-platform development? Flutter or Ionic or React Native?. Each technology and development approach has its own Pros and Cons from which you will need to choose the right one for your business. If you think Ionic is the right cross-platform application development, here are a few pros and cons of Ionic development. 

What is Ionic Framework?

Being an open-source SDK for building Hybrid mobile applications in both Android and iOS platforms, Ionic is the best choice for building top of the line mobile applications. This Ionic framework is completely based on Apache Cordova and Angular. More precisely, Ionic is an npm module that requires the installation of Node JS to function.

One can build a full functioning mobile application in both platforms using their Javascript, HTML, and CSS knowledge without requiring the basics of Kotlin or Java. More than 5 Million mobile applications are built using this Ionic framework by leveraging its platform-specific UI elements, innumerable libraries, and more exciting features.

The applications that are built using the Ionic framework are cross-platform, web-based, and have access to native device’s APIs.

Ionic Applications are

  • Cross-platform – Single code base for both platforms (except native components)
  • Web-based – Built using web-views and can be displayed in a browser like PWAs.
  • Access to native API components – They can access native device’s camera, files, and others.

Advantages of Ionic Development

Quick Development and Time To Market

For entrepreneurs and business owners, ionic development can be beneficial if they want to develop a mobile application in both platforms in a short period of time while comparing to native applications. Building native applications specifically for each platform can be time-consuming which can imply a delay in time to market and development cost of native applications are generally expensive.

#mobile app development #ionic 4 advantages #ionic 4 best practices #ionic 5 #ionic appflow #ionic capacitor pros and cons #ionic vs react native #react native pros and cons #what is ionic app development

I am Developer

1611112146

Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS - Tuts Make

Autocomplete textbox search from database in codeigniter 4 using jQuery Typeahead js. In this tutorial, you will learn how to implement an autocomplete search or textbox search with database using jquery typehead js example.

This tutorial will show you step by step how to implement autocomplete search from database in codeigniter 4 app using typeahead js.

Autocomplete Textbox Search using jQuery typeahead Js From Database in Codeigniter

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Table in Database
  • Setup Database Credentials
  • Create Controller
  • Create View
  • Create Route
  • Start Development Server

https://www.tutsmake.com/codeigniter-4-autocomplete-textbox-from-database-using-typeahead-js/

#codeigniter 4 ajax autocomplete search #codeigniter 4 ajax autocomplete search from database #autocomplete textbox in jquery example using database in codeigniter #search data from database in codeigniter 4 using ajax #how to search and display data from database in codeigniter 4 using ajax #autocomplete in codeigniter 4 using typeahead js