HackMD/lib/auth.js

87 lines
2.8 KiB
JavaScript
Raw Normal View History

2015-05-04 07:53:29 +00:00
//auth
//external modules
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;
var GithubStrategy = require('passport-github').Strategy;
var GitlabStrategy = require('passport-gitlab2').Strategy;
2015-05-04 07:53:29 +00:00
var DropboxStrategy = require('passport-dropbox-oauth2').Strategy;
//core
var config = require('./config.js');
2015-07-01 16:10:20 +00:00
var logger = require("./logger.js");
var models = require("./models");
2015-05-04 07:53:29 +00:00
function callback(accessToken, refreshToken, profile, done) {
2015-07-01 16:10:20 +00:00
//logger.info(profile.displayName || profile.username);
models.User.findOrCreate({
where: {
profileid: profile.id.toString()
},
defaults: {
2016-05-11 21:06:05 +00:00
profile: JSON.stringify(profile),
accessToken: accessToken,
refreshToken: refreshToken
2015-05-04 07:53:29 +00:00
}
}).spread(function (user, created) {
if (user) {
if (user.accessToken == accessToken) {
2016-05-11 21:06:05 +00:00
if (config.debug)
logger.info('user login: ' + user.id);
return done(null, user);
}
user.accessToken = accessToken;
user.refreshToken = refreshToken;
user.save().then(function () {
2016-05-11 21:06:05 +00:00
if (config.debug)
logger.info('user login: ' + user.id);
return done(null, user);
})
}
}).catch(function (err) {
logger.error('auth callback failed: ' + err);
return done(err, null);
})
2015-05-04 07:53:29 +00:00
}
//facebook
if (config.facebook) {
module.exports = passport.use(new FacebookStrategy({
clientID: config.facebook.clientID,
clientSecret: config.facebook.clientSecret,
callbackURL: config.serverurl + '/auth/facebook/callback'
}, callback));
}
2015-05-04 07:53:29 +00:00
//twitter
if (config.twitter) {
passport.use(new TwitterStrategy({
consumerKey: config.twitter.consumerKey,
consumerSecret: config.twitter.consumerSecret,
callbackURL: config.serverurl + '/auth/twitter/callback'
}, callback));
}
2015-05-04 07:53:29 +00:00
//github
if (config.github) {
passport.use(new GithubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.serverurl + '/auth/github/callback'
}, callback));
}
//gitlab
if (config.gitlab) {
passport.use(new GitlabStrategy({
baseURL: config.gitlab.baseURL,
clientID: config.gitlab.clientID,
clientSecret: config.gitlab.clientSecret,
callbackURL: config.serverurl + '/auth/gitlab/callback'
}, callback));
}
2015-05-04 07:53:29 +00:00
//dropbox
if (config.dropbox) {
passport.use(new DropboxStrategy({
clientID: config.dropbox.clientID,
clientSecret: config.dropbox.clientSecret,
callbackURL: config.serverurl + '/auth/dropbox/callback'
}, callback));
}