Authentificating API


#1

Hi,

I actually would have a login form using an laravel api, once connected it returns JSON data

{
id: 1,
group_id: 1,
username: "khalilben",
password: "CHIFFRED",
email: "mail@gmail.com",
first_name: "Khalil",
last_name: "Ben",
avatar: "1.jpg",
active: 1,
login_attempt: 12,
last_login: "2017-11-16 11:03:08",
created_at: "2014-03-12 09:18:46",
updated_at: "2017-11-13 16:29:10",
reminder: "CHIFFRED",
activation: null,
remember_token: "CHIFFRED",
last_activity: 1510833728
}

What i want to do is once it success, it send me to a profil page with those informations below. And save the ID globally to use it after on another page…
And don’t know how to proceed.
Already having this code but don’t know if it’s good and how to use it correctly

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

//https://www.djamware.com/post/58c1703e80aca7585c808ec1/step-by-step-tutorial-building-ionic-2-rest-api-authentication


//Providers
import {Resources} from  '../resources';
let apiUrl =Resources.Constants.API.api_login;
@Injectable()
export class AuthService {

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

  login(credentials) {
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');

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

  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);
        });
    });
  }

  logout() {
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('X-Auth-Token', localStorage.getItem('token'));

      this.http.post(apiUrl + 'logout', {}, { headers: headers })
        .subscribe(res => {
          localStorage.clear();
        }, (err) => {
          reject(err);
        });
    });
  }
}


#2
  1. First of all don’t use Localstorage, the device of the user deletes it, when it needs more space, so the user could be logged out.:fearful:

  2. Then you need a function on your rootpage that asks the authprovider at startup, if the user is loged in and change the groot page based on that information.

ChoosePage(){
 if(Authprovider.isLoggedIn()){
 this.rootPage = UserProfile;
 } else {
 this.rootPage = LoginPage;// to let this work you have to import the UserProfile and the LoginPage Page
 }
}
  1. import the Events module from ionic on your rootpage and subscribe to a event(with a name of your choice)
import { Platform, Events, AlertController, LoadingController, ToastController } from 'ionic-angular';
events.subscribe('main:choseRootPage', () => {
      this.ChosePage();
    });
  1. publish that event when the user logged in sucessfully (after you saved the id anywhere that it can detected by the ChosePage Function[in step one])

Something along these Lines should work


#3

Thanks, any alternative for localstorage ?


#4

Yes, even provided by Ionic:
https://ionicframework.com/docs/storage/

It uses an native sql plugin or indexdb and if those are not available it uses localStorage as fallback by default.