[Tutorial]Ionic App Development : Adding security to ionic apps

in #utopian-io6 years ago (edited)

download.jpeg
Image Source

Repository: Ionic App Repository Github

Software Requirements:
Visual Studio Code(Or any preferred code editor)
Chrome(Or any preferred browser)

What you will learn:
In this tutorial you would learn how to live code a real ionic application with practical examples including these major concepts:

  • Protecting certain pages from users access
  • Adding login functionality to your application
  • Determining application accessibility directly from your website

Difficulty: Intermediate

Tutorial
If you choose to create a profitable application using ionic, you would certainly need to restrict access to some areas unless payment has been made. Other than this, if you would want to make sure each user has an account on your website before granting access, you would also need to protect some pages and some functionality of your application.

This tutorial would cover some aspects you would use to protect your application using providers and life cycle events.

First of all
What are Providers?
Providers are components in ionic that help gather requests from a server or even locally within your application and serve it to whatever page may be in need of this data. Developers usually use providers with web APIs to collect data and use it within their applications.

Secondly
What are life cycle events?
This was explained in the last tutorial of this series. So you could simply click here and scroll to the bottom of the tutorial to see what a life cycle events is and how to use them.

For this tutorial, I would be using an app which is still in the stages of its live development to explain how to use this security measures, so you could head to my GITHUB repo to see the code for this application.

So let's get coding
First things first, we would need to create a provider. To do this simply head to your terminal and use this line of code to generate a new provider.

ionic g provider security

This would generate a provider and call it security.

Next thing is to go to the app.module.ts file in the app folder and add the created provider to the list of providers after importing it.

Our file should look like this

import { Security } from '../providers/security/security'//Import it here
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { IonicStorageModule } from '@ionic/storage';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { ProductsPage } from '../pages/products/products';
import { NewproductPage } from '../pages/newproduct/newproduct';
import { CheckoutPage } from '../pages/checkout/checkout';
import { ProductdetailPage } from '../pages/productdetail/productdetail';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    ProductsPage,
    NewproductPage,
    CheckoutPage,
    ProductdetailPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    ProductsPage,
    NewproductPage,
    CheckoutPage,
    ProductdetailPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}, security /*include the import here*/
  ]
})
export class AppModule {}

Now let's see how to use this.
For this application, just for tryout, I would be restricting accessibility to the new products page based on login authenticity.

So head to the security.ts file and add a boolean that determines whether the user is logged in

Our file should look like this

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
 
@Injectable()
export class SecurityProvider {
  LoggedIn :boolean = false;
 
  constructor(private http: Http) {
    
  }
}

Note: For your website interactions, you would need to build an API for your website using whatever programming language your website uses as its back-end. It will work regardless as long as it returns useful information back to you.

To test this out, we would be using two basic functions.
A login and a logOut function.
Note that this is technicality and wouldn't be able to be displayed as any visible(In simpler terms I wouldn't be showing any visual example of what I am doing). So try to understand the concept behind this.

Let's see the functions individually
Let's say that on our server we create status variables which are boolean that determine whether the user is logged in OR logged out.
We would create a function to change that on our server and allow accessibility to a new page when that is changed.
This function can be bound to a click event

login(user){
    //Assuming our server side returns the LoggedIn value
    this.http.get(www.websitename.com {user + 'login'} Then.(data) =>{
        this.loggedIn = data; //Log the value gotten from your server side. 
}
}

So this function sends a HTTP request which changes the state of the LoggedIn value on the server and returns the state of the user on the server.

With something like this you could keep track of all people loggedIn and using your app directly from your server side.
This depends on the back-end though which is not covered in this tutorial.

So the next thing is using the boolean to determine whether our user would get access past the login screen.

This is where our life cycle events come in
For such a case we would use the
ionViewCanEnter Event. If this event returns true, the page it is available on would be able to load and if it returns false it would deny accessibility to that page.

So if for instance, we would like to restrict out newproduct page, we would simply add this event to the page and let it return the value based on the security provider.

To do this we would need to import the provider so that we could use data from it.
newproduct.ts should look like this.

import { security } from '../providers/security/security'
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-newproduct',
  templateUrl: 'newproduct.html',
})
export class NewproductPage {
  public product: any;
  constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public security: Security) {
    this.product ={name: "",type: "",costprice: null,sellingprice:null,numOfGoods: 1,totalsellingprice: 0,profit: 0,timeOfEntry: null};
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad NewproductPage');
  };
  
  savedata(){
    if(this.product){
      this.product.totalsellingprice = this.product.sellingprice * this.product.numOfGoods;
      this.product.profit = this.product.sellingprice - this.product.costprice;
      this.product.timeOfEntry = Date.now;
      let data = this.product;
      this.viewCtrl.dismiss(data); 
    } else {
      this.viewCtrl.dismiss();
      console.log("No data input");
      }
  };
  addone(){
    this.product.numOfGoods += 1;
  };
ionViewCanEnter(){
   return this.security.loggedIn//This would return the value of the boolean
}

So try this out and see how this would restricting accessibility based on the LoggedIn state. Since you don't have a website or APi to use yet though, you could use simple boolean and just change the values whenever the logged in button is clicked.
For example
this.loggedIn = true;

So any comments would be appreciated and hope this tutorial helped. To see the live code used for explanations in this tutorials check out my GITHUB repo
Here

Sort:  

Thank you for your contribution @yalzeee.
Your tutorial has been reviewed and we suggest the following points:

  • We suggest you put images of your application in the tutorial, so the reader sees what is being built.
  • Please put more comments in your code.

Thanks for the development of this tutorial. We are waiting for your next tutorial.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin!

So far this week you've reviewed 2 contributions. Keep up the good work!

As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!

Hello! I find your post valuable for the wafrica community! Thanks for the great post! We encourage and support quality contents and projects from the West African region.
Do you have a suggestion, concern or want to appear as a guest author on WAfrica, join our discord server and discuss with a member of our curation team.
Don't forget to join us every Sunday by 20:30GMT for our Sunday WAFRO party on our discord channel. Thank you.

Hi @yalzeee!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @yalzeee!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.26
TRX 0.11
JST 0.033
BTC 64203.15
ETH 3065.06
USDT 1.00
SBD 3.93