Authentication Ionic + Laravel


#1

Hi guys, I need your help
I got this code example around, I dont remenber
I dont know if this code is good

service-provider.ts

export class ServiceProvider {

  api: string = 'https://www.mydomine/api/v1/';
  isLoggedIn = false;
  AuthToken: string;

  constructor(public http: Http) {
    this.isLoggedIn = false;
    this.AuthToken = null;
  }

  // Authenticate and verify email and password of User and create TOKEN
  authenticate(user) {
    let creds = 'email=' + user.email + "&password=" + user.password;
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return new Promise(resolve => {
        this.http.post(this.api+'auth', creds, {headers: headers}).subscribe( data => {
            if(data.json().success){
                this.storeUserCredentials(data.json().success);
                resolve(true);
            }
            else
                resolve(false);
        });
    });
  }

  // Get the token and send to userCredentials method bellow
  storeUserCredentials(token) {
    window.localStorage.setItem('token', token);
    this.useCredentials(token);
  }

  useCredentials(token) {
    this.isLoggedIn = true;
    this.AuthToken = token;
  }

  loadUserCredentials() {
    let token = window.localStorage.getItem('token');
    this.useCredentials(token);
  }

  // Destroy Authentication of User
  destroyUserCredentials() {
      this.isLoggedIn = false;
      this.AuthToken = null;
      window.localStorage.clear();
  }

  createAuthorization(headers: Headers) {
    headers.append('Authorization', window.localStorage.getItem('token'));
  }

  getCauses() {
    return this.http.get(this.api+'causes').map( res => res.json());
  }

}

I’m doing login and get the token of my API, but I dont know to use TOKEN in other places, for example in getCauses method
I want resolve by steps
1 - To use TOKEN in others requests using Headers Authorization + Beares + Token
2 - To use TOKEN to call forever user logged in all pages


#2

The easiest thing to do is to use this package https://github.com/auth0/angular2-jwt

It will automatically send your token and authorization header along with requests if you use this.authHttp.get and it has lots of helper functions like isTokenExpired()

If you want to do it like you have it, it would be something like this

let headers = new Headers({ 'Authorization': 'Bearer ' + window.localStorage.getItem('token') });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.api+'causes', options).map( res => res.json());

I’m not sure what you are asking in the second question


#3

@nb1990 Sorry if I asked you wrong, I want to use the data of user logged, example, wellcome {{ user->name }}, other example, to use data of user logged to edit and update in myProfileComponent.ts for example, its ok now friend ?


#4

Assuming that you return user info from the back end just do something like this to check what is being returned

this.http.post(this.api+'auth', creds, {headers: headers}).subscribe( data => {
            if(data.json().success){
                console.log(data.json().success); 
                this.storeUserCredentials(data.json().success);
                resolve(true);
            }

If username is something being returned you can do

this.username = data.json().sucess.username 

#5

I’m trying testing authenticatio friend, I’ll return feedback


#6

Ok, if I use

return this.http.get(this.api+'causes', options).map( res => res.json());

this is return Error:
Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays.

return a object

if I use this

return this.http.get(this.api+'causes' + options).map( res => res.json());

…causes[object%20Object]
any idea ?


#7

@nb1990 I did it, following yout instructions, thats right
the problema was in my home.ts look:

  getData() {
    this.service.getCauses()
      .subscribe(
        data => this.causes = data,
        err => console.log(err)
      );
  }
 

when in fact it was for me to do

  getData() {
    this.service.getCauses()
      .subscribe(
        data => this.causes = data.causas,  /// data.causes is object its wrong
        err => console.log(err)
      );
  }

thanks friend, now I trying guard user in variable and work in edit profile, step 2… I’ll come back


#8

@rafaelmoura Can you guide me how to get token and use it in other component ?