I have a login service with discord Oauth2.
After the user authorize discord, they are redirected to home page.
my login service is like this:
login() {
this.commonService.showLoadingOverlay();
return this.http.get('http://localhost:3000/auth/login/').subscribe((data: any) => {
const token = data.token;
this.token = token;
if (token) {
this.userInfo = data.user;
console.log(this.userInfo);
this.userId = data.user.user_id;
this.discordId = data.user.discord_id;
this.authStatusListener.next(true);
this.isAuthenticated = true;
const expiresInDuration = data.expiresIn;
const now = new Date();
const expirationDate = new Date(now.getTime() + expiresInDuration * 1000);
this.saveAuthData(token, expirationDate, this.userId, this.userInfo);
this.setAuthTimer(expiresInDuration);
this.commonService.hideLoadingOverlay();
this.router.navigate(['/']);
}
}, error => {
this.commonService.hideLoadingOverlay();
this.router.navigate(['/'])
const message = 'Not logged in...'
this.commonService.showErrorMessage(message);
}
)
}
Following a guide I was told to add this to save in local storage:
private getAuthData() {
const token = localStorage.getItem("token");
const expirationDate = localStorage.getItem("expiration");
const userId = localStorage.getItem("userId");
const userInfo = localStorage.getItem("userInfo");
if (!token || !expirationDate) {
return;
}
return {
token: token,
expirationDate: new Date(expirationDate),
userId: userId,
userInfo: userInfo
}
}
autoAuthUser() {
const authInformation = this.getAuthData();
if (!authInformation) {
return;
}
const now = new Date();
const expiresIn = authInformation.expirationDate.getTime() - now.getTime();
if (expiresIn > 0) {
this.token = authInformation.token;
this.isAuthenticated = true;
this.userId = authInformation.userId;
this.userInfo = authInformation.userInfo;
this.setAuthTimer(expiresIn / 1000);
this.authStatusListener.next(true);
}
}
I also have this to get the user info:
getUserInfo() {
return this.userInfo;
}
getUserId() {
return this.userId;
}
in my sidenav component I am calling user info like this:
if(this.currentUser) {
this.userId = this.authService.getUserId();
console.log(this.userId);
this.userInfo = this.authService.getUserInfo();
console.log('user:')
console.log(this.userInfo);
}
user ID is comming fine, but the user info object is coming as [Object Object], I have also tried to console.log userInfo.user_id
the data should be like this:
{user_id: "13", discord_id: "123456xxxx", username: null}
any ideas?
Thanks :)