Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
*/
this.passport.serializeUser(function(user, done) {
done(null, user._id);
});
this.passport.deserializeUser(function(user_id, done) {
// The `done` callback here accepts err and user,
// which are just what findOne will pass.
User.findOne({'_id': mongoose.Types.ObjectId(user_id)}, done);
});
/**
* Use Github Auth Strategy
* @link https://github.com/jaredhanson/passport-github/blob/master/examples/login/app.js#L26
*/
this.passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: process.env.GITHUB_CALLBACK_URL
},
function(accessToken, refreshToken, profile, done) {
// Code to verify user. Return the user object
// if verified.
// Try to find a user with this GitHub ID.
User.findOne({'githubInfo.id': profile._json.id}, function(err, user){
// If we could not find a user, create one.
if (user === null){
console.log("Creating new user");
// Error handling.
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'staging') {
app.use(errorHandler());
}
// Forest
forest(app);
// Cors.
app.use(cors());
const verify = (accessToken, tokenSecret, profile, done) => done(null, accessToken, { tokenSecret, profile });
if (has(config, 'github.clientID') && has(config, 'github.clientSecret')) {
passport.use(new GitHubStrategy(get(config, 'github'), verify));
} else {
console.warn('Configuration missing for passport GitHubStrategy, skipping.');
}
if (has(config, 'meetup.clientID') && has(config, 'meetup.clientSecret')) {
passport.use(new MeetupStrategy(get(config, 'meetup'), verify));
} else {
console.warn('Configuration missing for passport MeetupStrategy, skipping.');
}
if (has(config, 'twitter.consumerKey') && has(config, 'twitter.consumerSecret')) {
passport.use(new TwitterStrategy(get(config, 'twitter'), verify));
} else {
console.warn('Configuration missing for passport TwitterStrategy, skipping.');
}
app.use(cookieParser());
user.tokens.push({ kind: mappings.providerField, accessToken });
user.profile.name = user.profile.name || objectByString(profile, mappings.name);
user.profile.picture = user.profile.picture || objectByString(profile, mappings.picture);
user.profile.gender = user.profile.gender || objectByString(profile, mappings.gender);
user.profile.location = user.profile.location || objectByString(profile, mappings.location);
user.profile.website = user.profile.website || objectByString(profile, mappings.website);
user.save((err) => {
// console.info(err);
return done(err, user, { message : `${mappings.provider} account has been linked.` });
});
}
/**
* Sign in with GitHub.
*/
passport.use(new GithubStrategy({
clientID: config.get('passport.github.clientID'),
clientSecret: config.get('passport.github.clientSecret'),
callbackURL: config.get('passport.github.callbackURL'),
passReqToCallback: true
}, (...args) => {
const mappings = {
provider: 'GitHub',
providerField: 'github',
id: 'id',
name: 'displayName',
email: '_json.email',
picture: '_json.avatar_url',
location: '_json.location',
website: '_json.blog',
};
return oauth(mappings, ...args);
const initPassport = app => {
// Serialize sessions
passport.serializeUser(function(user, done) {
// user is the profile in github strategy
done(null, user);
});
// Deserialize sessions
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(
new Strategy(
{
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, cb) {
// console.log('accessToken', accessToken)
// console.log('refreshToken', refreshToken)
// console.log('profile', profile)
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
cb(null, providerData);
}
app.use(expressSession({ secret: "keyboard cat", resave: true, saveUninitialized: true }));
app.use(cookieParser());
//setup email templates
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('view engine', 'ejs');
//Setup Passport
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
passport.use(
new GitHubStrategy(
{
clientID: process.env.SCOREBOARD_GH_APPID,
clientSecret: process.env.SCOREBOARD_GH_SECRET,
callbackURL: "/auth/github/callback",
},
function(accessToken, refreshToken, profile, cb) {
const { displayName, username } = profile;
let email = "";
if ("emails" in profile && profile.emails.length) email = profile.emails[0].value;
db.gitHubUser(username, email, displayName).then(user => {
return cb(null, user);
});
//
}
)
// check whether the strategy has already been set up
if (this.isGitHubStrategySetup) {
throw new Error('GitHubStrategy has already been set up');
}
const { configManager } = this.crowi;
const isGitHubEnabled = configManager.getConfig('crowi', 'security:passport-github:isEnabled');
// when disabled
if (!isGitHubEnabled) {
return;
}
debug('GitHubStrategy: setting up..');
passport.use(
new GitHubStrategy(
{
clientID: configManager.getConfig('crowi', 'security:passport-github:clientId'),
clientSecret: configManager.getConfig('crowi', 'security:passport-github:clientSecret'),
callbackURL: (this.crowi.appService.getSiteUrl() != null)
? urljoin(this.crowi.appService.getSiteUrl(), '/passport/github/callback') // auto-generated with v3.2.4 and above
: configManager.getConfig('crowi', 'security:passport-github:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
skipUserProfile: false,
},
(accessToken, refreshToken, profile, done) => {
if (profile) {
return done(null, profile);
}
return done(null, false);
},
),
// Ex: user.providers[user.currentProvider].name
user.currentProvider = 'local';
user.save(function (err) {
if (err) {
logger.error('PassportJS LocalStrategy save error: ' + err.toString());
}
return done(err, user);
});
});
}
));
// Use github strategy
passport.use(new GitHubStrategy({
clientID: config.get('github').clientID,
clientSecret: config.get('github').clientSecret,
callbackURL: config.get('github').callbackURL
},
function (accessToken, refreshToken, profile, done) {
var email = profile.emails[0].value;
var provider = {
name: profile.displayName,
username: profile.username,
profile: profile._json
};
email: data.email,
lastLogin: Date.now(),
[providerName]: {
id: String(data.id),
accessToken: data.accessToken
}
})
// init the passport junk
const strategyConfig = {
clientID: config[providerName].id,
clientSecret: config[providerName].secret,
callbackURL: `/auth/${providerName}/callback`
}
const strategy = new Strategy(strategyConfig, findOrCreateUser(dataToUser))
passport.use(strategy)
// init the router
const start = passport.authenticate(providerName)
const callback = passport.authenticate(providerName, {
failureRedirect: '/login'
})
const router = Router({ mergeParams: true })
router.get(`/auth/${providerName}/start`, redirect.pre, start)
router.get(`/auth/${providerName}/callback`, callback, redirect.post)
export default router
constructor(req, config)
{
super(req, config);
if (!config.properties) {
config.properties = {};
}
if (!config.properties.id) {
config.properties.id = "id";
}
// passport
this.githubStrategy = new GithubStrategy({
clientID: config.clientID,
clientSecret: config.clientSecret,
callbackURL: config.callbackURL,
passReqToCallback: true
}, auth.buildPassportCallback(config, this));
req.passport.use(this.githubStrategy);
}
import app from '~/';
import { UserSchema, User } from '~/model/user';
// Passport setup
// TODO: Serialize User for sessions
passport.serializeUser(function(user, done) {
done(null, user);
});
// TODO: Deserialize User for sessions
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
// Define GitHub Login Strategy
passport.use(new GitHubStrategy({
clientID: app.config.github.clientID,
clientSecret: app.config.github.secret,
callbackURL: app.config.github.callback,
}, (accessToken, refreshToken, profile, done) => {
User.updateOrCreate(accessToken, profile)
.then(user => {
done(null, user);
}, err => {
done(err);
});
}
));
app.use(passport.initialize());
app.use(passport.session());