Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// https://gist.github.com/JanKoppe/1491e37d1022c77a286087e6c81d6092#file-example-js-L5
// TODO.
// Pick-up secrets file and check structure.
var orcid_secrets = yaml.load(provider_path);
console.log('secrets for ' + provider, orcid_secrets);
if( orcid_secrets['clientID'] &&
orcid_secrets['clientSecret'] &&
orcid_secrets['callbackURL'] ){
// Pass.
}else{
throw new Error(provider + ' not structured correctly!');
}
var ORCIDStrategy = require('passport-oauth2').Strategy;
passport.use(new ORCIDStrategy({
passReqToCallback: true,
session: false,
authorizationURL: 'https://orcid.org/oauth/authorize',
tokenURL: 'https://pub.orcid.org/oauth/token',
scope: '/authenticate',
clientID: orcid_secrets['clientID'],
clientSecret: orcid_secrets['clientSecret'],
callbackURL: orcid_secrets['callbackURL']
}, function(req, accessToken, refreshToken, params, profile, done){
console.log("Start auth...");
//console.log(provider + ' callback profile: ', profile);
//console.log(provider + ' callback params: ', params);
// Try and extract from sessioner using orcid id.
if( ! params || ! us.isString(params['orcid']) ){
private createStrategy(
req: Request,
integration: Required
): OAuth2Strategy {
const { clientID, clientSecret, authorizationURL, tokenURL } = integration;
// Construct the callbackURL from the request.
const callbackURL = reconstructURL(req, `/api/auth/oidc/callback`);
// Create a new OAuth2Strategy, where we pass the verify callback bound to
// this OIDCStrategy instance.
return new OAuth2Strategy(
{
passReqToCallback: true,
clientID,
clientSecret,
authorizationURL,
tokenURL,
callbackURL,
},
this.userAuthenticatedCallback
);
}
exports.initialize = function(app) {
var users = exports.users = {};
var params = Config.get('strategy:params');
params.state = true;
params.authorizationURL = 'https://slack.com/oauth/authorize';
params.tokenURL = 'https://slack.com/api/oauth.access';
params.callbackURL = URL.format(Util._extend(Config.get('frontend'), {
pathname: exports.callback
}));
var handler = new OAuth2(params, function(token, _, profile, done) {
profile.id = Crypto.randomBytes(36).toString('base64');
profile.token = token;
users[profile.id] = profile;
done(null, profile);
});
// Load profile from Slack API
handler.userProfile = function(token, done) {
this._oauth2._request('GET', URL.format({
protocol: 'https',
hostname: 'slack.com',
pathname: '/api/auth.test',
query: {
token: token
}
self._oauth2.get(self._profileURL, accessToken, function(err, body) {
let json;
if (err) {
return done(new InternalOAuthError('Failed to fetch user profile', err));
}
try {
json = JSON.parse(body);
} catch (ex) {
return done(new Error('Failed to parse user profile'));
}
const profile = {
id: String(json.id),
username: json.username,
displayName: json.name,
emails: [{value: json.email}],
// jshint camelcase: false
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
avatarUrl: json.avatar_url,
this._oauth2.get(this._userProfileURL, accessToken, function (err, body, res) {
var json;
if (err) {
if (err.data) {
try {
json = JSON.parse(err.data);
} catch (_) {}
}
if (json && json.error && json.error.message) {
return done(new GooglePlusAPIError(json.error.message, json.error.code));
} else if (json && json.error && json.error_description) {
return done(new UserInfoError(json.error_description, json.error));
}
return done(new InternalOAuthError('Failed to fetch user profile', err));
}
try {
json = JSON.parse(body);
} catch (ex) {
return done(new Error('Failed to parse user profile'));
}
var profile;
switch (self._userProfileFormat) {
case 'openid':
profile = OpenIDProfile.parse(json);
break;
default: // Google Sign-In
profile = GooglePlusProfile.parse(json);
break;
function Strategy(options, verify) {
options = options || {};
options.authorizationURL = options.authorizationURL || 'https://accounts.google.com/o/oauth2/v2/auth';
options.tokenURL = options.tokenURL || 'https://www.googleapis.com/oauth2/v4/token';
OAuth2Strategy.call(this, options, verify);
this.name = 'google';
this._userProfileURL = options.userProfileURL || 'https://www.googleapis.com/oauth2/v3/userinfo';
var url = uri.parse(this._userProfileURL);
if (url.pathname.indexOf('/userinfo') == (url.pathname.length - '/userinfo'.length)) {
this._userProfileFormat = 'openid';
} else {
this._userProfileFormat = 'google+'; // Google Sign-In
}
}
options.state = true;
options.botPrompt = _options.botPrompt || defaultOptions.botPrompt;
options.scope = _options.scope || defaultOptions.scope;
options.uiLocales = _options.uiLocales || defaultOptions.uiLocales;
options.authorizationURL = options.authorizationURL || defaultOptions.authorizationURL;
options.tokenURL = options.tokenURL || defaultOptions.tokenURL;
if (!options.botPrompt) {
delete options.botPrompt;
}
if (!options.uiLocales) {
delete options.uiLocales;
}
OAuth2Strategy.call(this, options, verify);
this.name = 'line';
this._profileURL = options.profileURL || defaultOptions.profileURL;
this._clientId = options.clientID;
this._clientSecret = options.clientSecret;
this._botPrompt = options.botPrompt;
if (options.uiLocales) {
this._uiLocales = options.uiLocales;
}
// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter (By node-oauth)
// Use Authorization Header (Bearer with Access Token) for GET requests. Used to get User's profile.
this._oauth2.useAuthorizationHeaderforGET(defaultOptions.useAuthorizationHeaderforGET);
}
function Strategy(options, verify) {
options = options || {};
options.authorizationURL = options.authorizationURL || 'https://github.com/login/oauth/authorize';
options.tokenURL = options.tokenURL || 'https://github.com/login/oauth/access_token';
options.scopeSeparator = options.scopeSeparator || ',';
options.customHeaders = options.customHeaders || {};
if (!options.customHeaders['User-Agent']) {
options.customHeaders['User-Agent'] = options.userAgent || 'passport-github';
}
OAuth2Strategy.call(this, options, verify);
this.name = 'github';
this._userProfileURL = options.userProfileURL || 'https://api.github.com/user';
this._oauth2.useAuthorizationHeaderforGET(true);
// NOTE: GitHub returns an HTTP 200 OK on error responses. As a result, the
// underlying `oauth` implementation understandably does not parse the
// response as an error. This code swizzles the implementation to
// handle this condition.
var self = this;
var _oauth2_getOAuthAccessToken = this._oauth2.getOAuthAccessToken;
this._oauth2.getOAuthAccessToken = function(code, params, callback) {
_oauth2_getOAuthAccessToken.call(self._oauth2, code, params, function(err, accessToken, refreshToken, params) {
if (err) { return callback(err); }
if (!accessToken) {
return callback({
statusCode: 400,
const apiKey = req.header("X-Api-Key");
if (!apiKey) return cb("API key missing");
const userId = await apiLogins.getUserIdByApiKey(apiKey);
if (userId) {
return cb(null, { apiKey, userId });
}
cb("API key not found");
}),
);
// Initialize OAuth2 for Discord login
// When the user logs in through OAuth2, we create them a "login" (= api token) and update their user info in the DB
passport.use(
new OAuth2Strategy(
{
authorizationURL: "https://discordapp.com/api/oauth2/authorize",
tokenURL: "https://discordapp.com/api/oauth2/token",
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.OAUTH_CALLBACK_URL,
scope: ["identify"],
},
async (accessToken, refreshToken, profile, cb) => {
const user = await simpleDiscordAPIRequest(accessToken, "users/@me");
// Make sure the user is able to access at least 1 guild
const permissions = await apiPermissionAssignments.getByUserId(user.id);
if (permissions.length === 0) {
cb(null, {});
return;
const OAuth2Strategy = require("passport-oauth2");
const passport = require("passport");
const config = require("./config");
const { decodeOpaqueId } = require("./lib/utils/decoding");
const logger = require("./lib/logger");
// This is needed to allow custom parameters (e.g. loginActions) to be included
// when requesting authorization. This is setup to allow only loginAction to pass through
OAuth2Strategy.prototype.authorizationParams = function (options = {}) {
return { loginAction: options.loginAction };
};
passport.use(
"oauth2",
new OAuth2Strategy(
{
authorizationURL: config.OAUTH2_AUTH_URL,
tokenURL: config.OAUTH2_TOKEN_URL,
clientID: config.OAUTH2_CLIENT_ID,
clientSecret: config.OAUTH2_CLIENT_SECRET,
callbackURL: config.OAUTH2_REDIRECT_URL,
state: true,
scope: ["offline"]
},
(accessToken, refreshToken, profile, cb) => {