Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.
Wall Script
Follow Me:
Thursday, June 22, 2017

Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.

Here is the continued article on my previous post for creating a welcome page with login and logout. Today’s post explains how to implement login authentication system for your AngularJS applications. It will show you how to log in with a user and store the user session, so it deals with token based authentication. Since we are using token based authentication, it protects if any unauthorized request is made and notices for a new login if required. This makes your application’s authentication to be more secured compared with any other authentication system. Every user details will be stored in an external database and a PHP based API is used in the backend for handling this authentication. Hope you’ll find it more easily using this as your authentication system in your AngularJS projects. Let’s look into the live demo and follow the below code.

Ionic 3 and Angular 4:Login and Signup with PHP Restful API.


Live Demo


Video Tutorial
Ionic 3 and Angular 4: PHP Token Based Restful API User Authentication Login and Signup.


Database Design
To build the user feed system, you have to create two tables such as Users and Feed. You can check my previous tutorials for creating token-based API system.

Users
User table contains all the users registration details.
CREATE TABLE users(
user_id int AUTO_INCREMENT PRIMARY KEY,
username varchar(50),
password varchar(300),
name varchar(200),
email varchar(300));

Feed
This table contains user daily updates.
CREATE TABLE feed(
feed_id int PRIMARY KEY AUTO_INCREMENT,
feed text,
user_id_fk int
);

Download PHP Restul Project
$git clone https://github.com/srinivastamada/PHP-Slim-Restful.git


Create an Authenstication Service Provider
You have to create an injectable component for API autentication. The following ionic command help you to create files automatically.
$ionic g provider authService

app.module.ts
Now go to src/app/app.module.ts and import authService provider and HttpModule.
Now got src/app/app.module.ts and import Welcome, Login and Signup pages.
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { MyApp } from './app.component';
import { AuthService } from '../providers/auth-service';
import { Welcome } from '../pages/welcome/welcome';
import { Login } from '../pages/login/login';
import { Signup } from '../pages/signup/signup';
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 { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    Welcome,
    Login,
    Signup,
    TabsPage
  ],
  imports: [
    BrowserModule, HttpModule
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    Welcome,
    Login,
    Signup,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen, AuthService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

authService.ts
Include post data function for HTTP post access. You will understand more in the youtube video.
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = 'http://yourdomain.com/PHP-Slim-Restful/api/';

@Injectable()
export class AuthService {

  constructor(public http : Http) {
    console.log('Hello AuthService Provider');
  }

  postData(credentials, type) {
    return new Promise((resolve, reject) => {
      let headers = new Headers();

      this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
        .subscribe(res => {
          resolve(res.json());
        }, (err) => {
          reject(err);
        });
    });

  }

}

signup.ts
Here you have to import AuthService provider and implement with user signup data. Once the API call is succesful, the user data storing into application local storage with accessing data key call userData.
import { Component } from '@angular/core';
import {  NavController} from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { LoginPage } from '../login/login';
import { AuthService } from '../../providers/auth-service';

@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
  responseData : any;
  userData = {"username": "","password": "", "name": "","email": ""};

  constructor(public navCtrl: NavController, public authService:AuthService ) {
  }

  signup(){
     this.authService.postData(this.userData,'signup').then((result) => {
      this.responseData = result;
      console.log(this.responseData);
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);
    }, (err) => {
      // Error log
    });

  }

  login(){
    //Login page link
    this.navCtrl.push(LoginPage);
  }
}

signup.html
Bind the userDetails object with form inputs.
<ion-content padding class="appBackground">
  <ion-card>
    <ion-card-header>
      Registration
    </ion-card-header>
    <ion-card-content>
      <ion-list>
        <ion-item>
          <ion-label stacked>Name</ion-label>
          <ion-input type="text" [(ngModel)]="userData.name"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Email</ion-label>
          <ion-input type="text" [(ngModel)]="userData.email"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Username</ion-label>
          <ion-input type="text" [(ngModel)]="userData.username"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Password</ion-label>
          <ion-input type="password" [(ngModel)]="userData.password"></ion-input>
        </ion-item>

        <button ion-button full color="success" (click)="signup()">Sign up</button>
        <a href="#" (click)="login()">Login Page</a>
      </ion-list>
    </ion-card-content>
  </ion-card>
</ion-content>

login.ts
You have to follow the same like signup module.

home.ts
Reading the application local storage data and binding with userDetails. Logout function is clearing the local storage data and redirecting to the welcome page with time deplay option.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  userDetails : any;
  responseData: any;
 
  userPostData = {"user_id":"","token":""};

  constructor(public navCtrl: NavController, public authService:AuthService) {
  const data = JSON.parse(localStorage.getItem('userData'));
  this.userDetails = data.userData;

  this.userPostData.user_idthis.userDetails.user_id;
  this.userPostData.tokenthis.userDetails.token;

}

backToWelcome(){
   const root = this.app.getRootNav();
   root.popToRoot();
}

logout(){
     localStorage.clear();
     setTimeout(() => this.backToWelcome(), 1000);
}

}

home.html
Binding the local storage data with HTML template.
<ion-header>
  <ion-navbar>
    <img ion-right src="assets/imgs/bananalogo.png" class="navbarLogo" />
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to {{userDetails.name}}</h2>
  <h3>Email: {{userDetails.email}}</h3>
  <button ion-button color="primary" (click)="logout()">Logout</button>
</ion-content>

Build iOS App
Following commands for executing Xcode build, watch the video tutorial you will understand more.
$ cordova add platform ios
$ ionic build ios

Build Android App
Open Android build using Android SDK>
cordova add platform android
ionic build android

Previous Video Tutorial
Ionic 3 and Angular 4 Create a Welcome Page with Login and Logout.



Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


13 comments:

  1. could you just make upload Ionic 3 and Angular 4 json parsing Example and Push Notification pls.
    Thanks
    -Sapan

    ReplyDelete
  2. This is video too much helpfull and work for me
    Thanks
    -sapan

    ReplyDelete
  3. your tutorials helping to me lot, thanks

    ReplyDelete
  4. why there is not error message if i use random account

    ReplyDelete
  5. Error: this.userDetails is undefined

    ReplyDelete
    Replies
    1. Clear your browser local storage. Go to developer tools -> application -> Clear Site Data

      Delete
    2. Thank you so much. Ok After log in, user can insert some details to other table How can we do ... can you please help me ? like want to insert feed data from ionic.

      Delete
    3. Hi Srinivas, some how I've done inserting data from ionic.
      One thing I want to know how to display toast msg when same user signup like "user already existed" ?

      Delete
  6. {"error":{"text":"Enter valid data"}}

    ReplyDelete
  7. am also getting this error {"error":{"text":"Enter valid data"} please help.!

    ReplyDelete
  8. The video is very helpful. Thanks for the share

    ReplyDelete

Make in India