Skip to content

Commit

Permalink
issue CodeRoyale#26 : implemented github authentication using passport.
Browse files Browse the repository at this point in the history
  • Loading branch information
afif1400 committed May 27, 2021
1 parent 1f466cc commit b16a2de
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
17 changes: 17 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
"nodemailer": "^6.4.17",
"passport": "^0.4.1",
"passport-facebook-token": "^4.0.0",
"passport-github2": "^0.1.12",
"passport-jwt": "^4.0.0",
"swagger-jsdoc": "^4.0.0"
},
"devDependencies": {
Expand Down
57 changes: 57 additions & 0 deletions server/utils/githubAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const { sign } = require('jsonwebtoken');
const GitHubStrategy = require('passport-github2').Strategy;
const passport = require('passport');
const passportJwt = require('passport-jwt');

function authJwt(email) {
return sign({ user: { email } }, `SECRET`);
}

passport.use(
new GitHubStrategy(
{
clientID: `GITHUB_CLIENT_ID`,
clientSecret: `GITHUB_CLIENT_SECRET`,
// callbackURL: `${BASE_URL}${ENDPOINT}/auth/github/callback`,
scope: ['user:email'],
},
async (accessToken, refreshToken, profile, done) => {
try {
//* can include other required attributes
const email = profile.emails[0].value;

// Here you'd typically create a new or load an existing user and
// store the bare necessary informations about the user in the JWT.
const jwt = authJwt(email);

return done(null, { email, jwt });
} catch (error) {
return done(error);
}
}
)
);

// ? this can act as a common strategy for authtication using jwt
passport.use(
new passportJwt.Strategy(
{
jwtFromRequest(req) {
if (!req.cookies) throw new Error('Missing cookie-parser middleware');
return req.cookies.jwt;
},
secretOrKey: `SECRET`,
},
async ({ user: { email } }, done) => {
try {
// Here you'd typically load an existing user
// and use the data to create the JWT.
const jwt = authJwt(email);

return done(null, { email, jwt });
} catch (error) {
return done(error);
}
}
)
);

0 comments on commit b16a2de

Please sign in to comment.