Skip to content

Commit b16a2de

Browse files
committed
issue CodeRoyale#26 : implemented github authentication using passport.
1 parent 1f466cc commit b16a2de

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

package-lock.json

Lines changed: 17 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
"nodemailer": "^6.4.17",
1818
"passport": "^0.4.1",
1919
"passport-facebook-token": "^4.0.0",
20+
"passport-github2": "^0.1.12",
21+
"passport-jwt": "^4.0.0",
2022
"swagger-jsdoc": "^4.0.0"
2123
},
2224
"devDependencies": {

server/utils/githubAuth.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const { sign } = require('jsonwebtoken');
2+
const GitHubStrategy = require('passport-github2').Strategy;
3+
const passport = require('passport');
4+
const passportJwt = require('passport-jwt');
5+
6+
function authJwt(email) {
7+
return sign({ user: { email } }, `SECRET`);
8+
}
9+
10+
passport.use(
11+
new GitHubStrategy(
12+
{
13+
clientID: `GITHUB_CLIENT_ID`,
14+
clientSecret: `GITHUB_CLIENT_SECRET`,
15+
// callbackURL: `${BASE_URL}${ENDPOINT}/auth/github/callback`,
16+
scope: ['user:email'],
17+
},
18+
async (accessToken, refreshToken, profile, done) => {
19+
try {
20+
//* can include other required attributes
21+
const email = profile.emails[0].value;
22+
23+
// Here you'd typically create a new or load an existing user and
24+
// store the bare necessary informations about the user in the JWT.
25+
const jwt = authJwt(email);
26+
27+
return done(null, { email, jwt });
28+
} catch (error) {
29+
return done(error);
30+
}
31+
}
32+
)
33+
);
34+
35+
// ? this can act as a common strategy for authtication using jwt
36+
passport.use(
37+
new passportJwt.Strategy(
38+
{
39+
jwtFromRequest(req) {
40+
if (!req.cookies) throw new Error('Missing cookie-parser middleware');
41+
return req.cookies.jwt;
42+
},
43+
secretOrKey: `SECRET`,
44+
},
45+
async ({ user: { email } }, done) => {
46+
try {
47+
// Here you'd typically load an existing user
48+
// and use the data to create the JWT.
49+
const jwt = authJwt(email);
50+
51+
return done(null, { email, jwt });
52+
} catch (error) {
53+
return done(error);
54+
}
55+
}
56+
)
57+
);

0 commit comments

Comments
 (0)