I'm having following error while authenticating LinkedIn in Passport JS.
{
"message": "LinkedIn authentication failed",
"error": "failed to fetch user profile"
}
Here is my code:
passport.use(
new LinkedInStrategy(
{
clientID: process.env.LINKEDIN_CLIENT_ID,
clientSecret: process.env.LINKEDIN_CLIENT_SECRET,
callbackURL: '',
scope: ['email', 'profile'],
},
async (accessToken, refreshToken, profile, done) => {
// console.log('Access Token:', accessToken);
console.log('Profile:', profile);
console.log('hi');
try {
let user = await User.findOne({ linkedinId: profile.id });
if (user) {
return done(null, user);
}
user = await User.findOne({ email: profile.emails[0].value });
if (user) {
if (!user.linkedinId) {
user.linkedinId = profile.id;
user.verify = true;
await user.save();
}
console.log('user in strategy:', user);
return done(null, user);
}
const newUser = new User({
linkedinId: profile.id,
email: profile.emails[0].value,
verify: true,
});
await newUser.save();
done(null, newUser);
} catch (error) {
done(error, null);
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (error) {
done(error, null);
}
});
exports.linkedinAuth = passport.authenticate('linkedin', { state: true, scope: ['email', 'profile']});
exports.linkedinAuthCallback = (req, res, next) => {
passport.authenticate('linkedin', { session: false }, async (error, user, info) => {
console.log('info:', info);
console.log('user in callback:', user);
if (error) {
console.error('LinkedIn authentication error:', error);
return res.status(400).json({ message: 'LinkedIn authentication failed error', error: error.message });
}
if (!user) {
const message = info ? info.message : 'User already registered with LinkedIn';
return res.redirect(`=${encodeURIComponent(message)}`);
}
try {
const token = jwt.sign({ userId: user._id }, secretKey, { expiresIn: '1h' });
const redirectUrl = `/recommendation?token=${token}&userId=${user._id}`;
res.redirect(redirectUrl);
} catch (jwtError) {
console.error('JWT generation error:', jwtError);
res.status(500).json({ message: 'Internal server error during JWT generation' });
}
})(req, res, next);
};
Also, I'm curious to know why the console 'hi' isn't printing? I'm actually confused about the flow of the process. Would be appreciated if someone guide about that. Note: Please read the question thoroughly instead of downvoting or suggesting a dupicate as there are the details that differ from other questions posted earlier.
Here is the link to a short video demonstrating this issue:
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742307899a4419307.html
评论列表(0条)