I have a site where I want to login programmatically in a scenario sending credentials to API(endpoint). So the app is working well if I log in manually.
Now I have a condition, if it's true, just do a login, this code is in app.component.ts
export class AppComponent {
{
this.initializeApp();
}
initializeApp() {
if((this.platform.is('mobileweb') || this.platform.is('desktop')) && this.id == "C3E1EE21-A62C-452F-BE0D-AC3EF5449F23"){
//Authenticate
var loginModel: myLoginModel =
{
applicationId: "C1F3A7D7-709D-EB11-A008-00155E00F00B",
username: "username",
password: "pwrd5893"
};
this._auth.login(loginModel).then(token => {
let user:any = jwt_decode(token);
user.token = token;
this.storageService.setItem('user',user);
}).catch(err => {
console.log(err);
});
this.navController.navigateRoot('myScreen');
}
}
}
the _auth.login method is on auth.service.ts:
login(credentials): Promise<any> {
return this._api.security_post('Login', credentials)
.then((res: any) => {
this.storageService.setItem('token',res);
return res;
}).catch(e => {
this.logout();
return e;
})
}
And this._api.security_post used on auth.login it's on api.service.ts
security_post(url, data) {
const promise = new Promise((resolve, reject) => {
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
responseType: 'text' as 'json'
};
this.http.post(this.apiSecurity+'/'+url, data, httpOptions).subscribe(data => {
resolve(data)
},error=>{
reject(error);
});
})
return promise;
}
So the app login correctly, but it keeps doing infinite login request
How can I solve that? Regards
I guess the condition under which you want to login programmatically is this.id == "C3E1EE21-..."
?
In that case, I suppose it remains true
throughout your App session, and therefore the block is executed at each component update.
A possible solution could be to add an extra condition, typically to login only if you currently have no known user in your session:
if((
this.platform.is('mobileweb')
|| this.platform.is('desktop')
) && this.id == "C3E1EE21-..."
&& !this.storageService.getItem('user') ) {
//Authenticate...
}