Skip to content

Commit 92c252f

Browse files
committed
refactor passport routes with clearer errors for no user
1 parent 7bcfde0 commit 92c252f

File tree

1 file changed

+13
-26
lines changed

1 file changed

+13
-26
lines changed

server/routes/passport.routes.js

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,38 +3,19 @@ import passport from 'passport';
33

44
const router = new Router();
55

6-
router.get('/auth/github', passport.authenticate('github'));
7-
router.get('/auth/github/callback', (req, res, next) => {
6+
const authenticateOAuth = (service) => (req, res, next) => {
87
passport.authenticate(
9-
'github',
8+
service,
109
{ failureRedirect: '/login' },
11-
(err, user) => {
10+
(err, user, info) => {
1211
if (err) {
1312
// use query string param to show error;
14-
res.redirect('/account?error=github');
13+
res.redirect(`/account?error=${service}`);
1514
return;
1615
}
1716

18-
req.logIn(user, (loginErr) => {
19-
if (loginErr) {
20-
next(loginErr);
21-
return;
22-
}
23-
res.redirect('/');
24-
});
25-
}
26-
)(req, res, next);
27-
});
28-
29-
router.get('/auth/google', passport.authenticate('google'));
30-
router.get('/auth/google/callback', (req, res, next) => {
31-
passport.authenticate(
32-
'google',
33-
{ failureRedirect: '/login' },
34-
(err, user) => {
35-
if (err) {
36-
// use query string param to show error;
37-
res.redirect('/account?error=google');
17+
if (!user) {
18+
res.redirect(`/account?error=${service}NoUser`);
3819
return;
3920
}
4021

@@ -47,6 +28,12 @@ router.get('/auth/google/callback', (req, res, next) => {
4728
});
4829
}
4930
)(req, res, next);
50-
});
31+
};
32+
33+
router.get('/auth/github', passport.authenticate('github'));
34+
router.get('/auth/github/callback', authenticateOAuth('github'));
35+
36+
router.get('/auth/google', passport.authenticate('google'));
37+
router.get('/auth/google/callback', authenticateOAuth('google'));
5138

5239
export default router;

0 commit comments

Comments
 (0)