I'm currently facing an issue with accessing the data of the authenticated user in my code and figuring out how to fetch it.
I have completed the authentication flow, allowing users to register and login successfully with a token. Even after refreshing the page, the user remains logged in and the token is stored in the ionic/storage.
It seems like having the token should be sufficient to retrieve the specific user data/permissions. However, I am uncertain about how to accomplish this.
When viewing a user's profile by clicking on their profile tab, I can easily pass along their ID from a list. But how do I obtain the ID of the authenticated user just by clicking on the profile tab?
In this scenario, there isn't another page where I can retrieve the ID from. I have included my auth.service code for reference, which handles the token, but the key parts seem to be the last two snippets.
This is the snippet from auth.service.ts:
private token = null;
user = null;
authenticationState = new BehaviorSubject(false);
constructor(private http: HttpClient, private alertCtrl: AlertController, private storage: Storage, private helper: JwtHelperService,
private plt: Platform) {
this.plt.ready().then(() => {
this.checkToken();
});
}
checkToken() {
this.storage.get(TOKEN_KEY).then(access => {
if (access) {
this.user = this.helper.decodeToken(access);
this.authenticationState.next(true);
}
});
}
apilogin(username: string, password: string) {
return this.http.post<any>(`${this.url}/api/token/`, { username, password })
.pipe(
tap(res => {
this.storage.set(TOKEN_KEY, res['access']);
this.storage.set(USERNAME_KEY, username);
this.user = this.helper.decodeToken(res['access']);
console.log('my user: ', this.user);
this.authenticationState.next(true);
}),
catchError(e => {
this.showAlert('Oops smth went wrong!');
throw new Error(e);
}));
}
And here is the snippet from user.service.ts:
// get a user's profile
getUserDetails(id: number): Observable<any> {
return this.http.get(`${this.url}/users/${id}/`);
}
Lastly, in profile.ts:
information = null;
id: number;
ngOnInit() {
// How to get just the authenticated api?
this.activatedRoute.paramMap.subscribe(params => {
this.id = validateId(params.get('id'));
});
function validateId(id: any): number {
return parseInt(id);
}
// Get the information from the API
this.userService.getUserDetails(this.id).subscribe(result => {
this.information = result;
});
}