【发布时间】:2021-06-29 04:47:57
【问题描述】:
我认为我做错了。
如何授权用户并将访问令牌发送到前端 (Angular) 并发出 api 请求以获取用户的 avatar..etc
在我的应用程序中,我使用 discord oauth2 和 passport-discord。我这样称呼我的后端(nodejs):
login() {
this.commonService.showLoadingOverlay();
return this.http.get('/auth/login/').subscribe((data: any) => {
const token = data.token;
this.token = token;
if (token) {
this.userInfo = data.user;
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 * 10000);
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);
}
)
}
后端:
router.get('/login', (req, res) => {
if (req.user) {
const token = jwt.sign({ userId: req.user.user_id, discordId: req.user.discord_id },
process.env.COOKIE_SECRET,
{ expiresIn: '6h' });
res.status(200).json({
token: token,
expiresIn: 3600,
user: req.user
});
} else {
res.send('not logged in!')
}
});
不和谐策略:
passport.use(new DiscordStrategy({
clientID: process.env.DISCORD_CLIENT,
clientSecret: process.env.DISCORD_SECRET,
callbackURL: process.env.DISCORD_REDIRECT,
scope: scopes
},
function (accessToken, refreshToken, profile, done) {
const currentQuery = 'SELECT user_id, discord_id FROM users WHERE discord_id= $1';
const currentUserValues = [profile.id];
db.query(currentQuery, currentUserValues, (err, res) => {
if (err) {
console.log(err);
} else if (!err && res.rows[0]) {
const currentUser = res.rows[0];
done(null, currentUser); //send to serilize
} else if (!err && !res.rows[0]) {
const newUserQuery = 'INSERT INTO users (discord_id, discord_email) VALUES ($1,$2) ON CONFLICT DO NOTHING RETURNING user_id'
const newUserValues = [profile.id, profile.email]
db.query(newUserQuery, newUserValues, (err, res) => {
if (err) {
console.log(err);
} else {
const newUser = res.rows[0];
done(null, newUser); //send to serilize
}
});
}
})
}));
我确定我做错了,我找不到正确的方法吗?最佳做法是什么?如何获取令牌并将其与其他 api 调用一起使用?
感谢任何帮助
【问题讨论】: