【发布时间】:2019-11-13 04:26:14
【问题描述】:
我正在努力解决一个问题,即我的代码应该如何知道哪些是经过身份验证的用户的数据,或者我如何获取该数据。
我已经完成了我的身份验证流程,这意味着我可以使用令牌成功注册和登录。我仍然通过刷新页面登录,我的令牌仍然存储在 ionic/storage 中。
我认为这实际上应该足以获取用户的已验证数据的特定用户数据/权限。但我不知道该怎么做。
当我从列表中获取任何用户并查看他的个人资料时,我只需传递他的 ID。如何仅通过单击配置文件选项卡来获取经过身份验证的用户的 ID?
我不是来自另一个可以获取 id 的页面。我还放了我的 auth.service 代码,如果这对您有帮助,以便因为令牌帮助我,但重要的是最后两个 sn-ps(我认为是这样)。
这是我的代码:
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);
}));
}
user.service.ts
// get a user's profile
getUserDetails(id: number): Observable<any> {
return this.http.get(`${this.url}/users/${id}/`);
}
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;
});
}
【问题讨论】:
-
我不是真正的问题,您的意思是您在认证成功后无法通过 id 获取另一个用户吗?在使用之前我需要知道通过id获取用户的端点需要身份验证,对!
-
@AbdelrhmanElSayed 不是另一个工作正常的用户。但是如何只获取经过身份验证的用户。因此,如果我以 user1 身份登录,如何获取此身份验证的数据。用户 1? api 端点是
http://1234/users/{id}/,如果是经过身份验证的用户,则有权更新用户。因此,它不会获取任何用户(有效),而只是获取经过身份验证的用户。就像查看我自己的个人资料时一样。 -
这个调用的返回值是多少?
-
@AbdelrhmanElSayed 回复? => 它只需要一个 id。然后你得到的数据是用户信息,如用户名、电子邮件等。我想在自己的配置文件视图中显示 auth 用户的数据。
-
我知道了,当您打开任何用户的个人资料然后尝试打开当前用户个人资料时,没有任何变化,对吧?
标签: javascript angular typescript ionic-framework ionic4