【发布时间】:2023-02-15 09:52:34
【问题描述】:
目前,用户可以毫无问题地登录并注册我的应用程序。然后我添加了一个“将您的 Twitter 用户链接到帐户”按钮,单击该按钮会将用户带到“/auth/twitter”。然后启动 passport-twitter 并开始 oAuth 过程。
现在,我正在使用 passport-twitter 作为 twitter oAuth 的包。这个过程有效。我能够让用户成功通过身份验证。这是代码。
但是有两个问题:我没有找到一种方法来 1) 让用户登录到 Twitter,这样他们就不必每次想从我的应用程序向其推送内容时都重新连接他们的 Twitter。和 2) 将 Twitter 用户和登录用户关联到我的应用程序。从长远来看,我计划添加其他社交媒体帐户,因此用户将链接多个社交媒体。推特将只是其中之一。
问题 #2:我无法从我的 redux 存储或从前端调用 axios.get 到“/auth/twitter/”,否则我只能从调用中获取信息,然后将其发布到用户的表(对吗?)。因此,我改为从前端的标签访问“/auth/twitter”以启动流程。
passport.use(
new TwitterStrategy(
{
consumerKey: "XXX",
consumerSecret: "XXX",
callbackURL: "http://localhost:8080/auth/twitter/callback",
// callbackURL: "http://www.localhost:8080/home",
includeEmail: true,
},
async(accessToken, refreshToken, profile, cb) => {
console.log('got the prodile')
const twitterIDforOAuth = profile.id
const { id, username } = profile;
let theuser = await User.findOne({
where: {
twitterID: id
}
})
if(theuser){
console.log('FOUND USER', '\n', theuser)
} else {
try {
console.log('NO USER FOUND')
var passwordUser = (Math.random() + 1).toString(36).substring(7);
console.log('CREATING USER')
theuser = await Promise.all([
User.create({
twitterID: id,
username : username,
password: passwordUser
})
])
console.log('USER CREATED');
} catch (error) {
console.log(error);
}
}
//this callback calls the auth/callback url to kick off the redirect process
// need to send username and password to /auth/signup
return cb(null, {username: username, password: passwordUser})
//Line below sends too much data that is irrelevant for the user... lets review it?
// return cb(null, {username: twitterIDforOAuth})
}
)
);
app.get('/auth/twitter', passport.authenticate("twitter"));
app.get(
"/auth/twitter/callback",
passport.authenticate("twitter", {
failureRedirect: "/login",
failureMessage: true,
session: false
}),
async (req, res) => {
var user = req.user;
console.log(user.username, user.password);
//GET USERNAME AND PASSWORD
var username = user.username;
var password = user.password;
///they need to login the app
//auth/login
res.redirect('/AccountSettings')
}
);
用户在通过此流程时被重定向到 /AccountSettings,因此我知道用户已通过 100% 身份验证并使用 Twitter 登录(否则他们将被推送到 /login,而这不会发生)。
此流程中的大多数人使用从 Twitter 返回的信息在他们的数据库中创建一个用户。
但是,我试图将此信息链接到登录用户,并让他们登录到 Twitter,这样用户就不需要继续重新连接他们的 Twitter 帐户(至少不经常)。 (通过访问他们的 Twitter 帐户,我的计划是允许他们向其中推送内容)
目前,我正在使用带有 href 标签的“/auth/twitter”路由将其带到“/auth/twitter”。这是正确的方法还是这种方法导致了我的链接问题?
人们对此问题有何建议?将社交媒体帐户链接到已登录用户帐户的正确方法是什么?
我正在使用 Express、Redux、React、Postgres 和 passport-twitter
【问题讨论】:
标签: reactjs express redux twitter-oauth passport-twitter