How to efficiently store and use Authentication in Ionic 3

Viewed 9170

I'm currently developing an Ionic (3.4) app for iOS/Android. I'm not familiar with authentification processes or with applications.

After using HTTP request in a provider, I get my object, the user. But I have absolutely no idea how to store it or to deal with it. What are the good practices:

  • Am I suppose to just store the object in the provider and call in in every single page I have?
  • Am I suppose to store it as a sort of global object in the app?
  • Or am I suppose (as bellow) to transfer it as a Navigation variable from one page to another? (I guess that's not the right answer)

And finally, how will the application react on reloading/restarting: how to avoid people to fill the form again and again?

Here is my service:

@Injectable()
export class UserProvider {
    data = {};
    username: string;
    password: string;

    constructor(private _http: Http) {
        console.log('Hello UserProvider Provider');
    }

    getUser(username:string, password:string){

        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let params = urlSearchParams.toString()

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        return this._http
        .post("http://api.minesdedouai.fr/user/login", params, {headers:headers} )
        .map(response => response.json())

    }

}

I'm aware that a login request is supposed to use some token, but as I said, this is a small student's API, we're not pro and it's working.

And this is the method that uses the service, somewhere in a component (a page).

onLogin(form: NgForm) {
  if (form.valid) {
    this._userProvider.getUser(this.login.username, this.login.password)
    .subscribe((response) => {
      this.user = response;
      console.log("Authentification Success");
      this.navCtrl.push(TabsPage, {user: this.user});
    },
    (error) => {
      if (error.status===403){
        console.log("Wrong User")
      }
      else{
        console.log(error);
      }

    });
  }
}

Thank you very much

2 Answers
Related