Accounts.saml.settings.providers = services.map((service) => {
		if (service.value === true) {
			const samlConfigs = getSamlConfigs(service);
			logger.updated(service.key);
			ServiceConfiguration.configurations.upsert({
				service: serviceName.toLowerCase(),
			}, {
				$set: samlConfigs,
			});
			return configureSamlService(samlConfigs);
		}
		return ServiceConfiguration.configurations.remove({
			service: serviceName.toLowerCase(),
		});
	}).filter((e) => e);
Example #2
0
Meteor.loginWithBlockstack = (options, callback = handleError) => {
	if (!options || !options.redirectURI) {
		options = ServiceConfiguration.configurations.findOne({
			service: 'blockstack',
		});

		options.blockstackIDHost = Meteor.Device.isDesktop()
			? 'http://localhost:8888/auth'
			: 'https://blockstack.org/auth';

		options.scopes = ['store_write'];
	}

	try {
		check(options, Match.ObjectIncluding({
			blockstackIDHost: String,
			redirectURI: String,
			manifestURI: String,
		}));

		import('blockstack/dist/blockstack').then(({ redirectToSignIn }) =>
			redirectToSignIn(options.redirectURI, options.manifestURI, options.scopes));
	} catch (err) {
		callback.call(Meteor, err);
	}
};
 _.each(Meteor.settings.private.serviceConfiguration, (settings) => {
   settings = _.extend(settings, {loginStyle: "popup"});
   ServiceConfiguration.configurations.upsert(
     {service: settings.service},
     settings
   );
 });
Example #4
0
const getConfiguration = function () {
  const config = ServiceConfiguration.configurations.findOne({ service: 'hsl' });
  if (!config) {
    throw new ServiceConfiguration.ConfigError('Service hsl not configured.');
  }
  return config;
};
Example #5
0
const configureService = _.debounce(Meteor.bindEnvironment(() => {
	const serviceConfig = getSettings();

	if (!serviceConfig.enable) {
		logger.debug('Blockstack not enabled', serviceConfig);
		return ServiceConfiguration.configurations.remove({
			service: 'blockstack',
		});
	}

	ServiceConfiguration.configurations.upsert({
		service: 'blockstack',
	}, {
		$set: serviceConfig,
	});

	logger.debug('Init Blockstack auth', serviceConfig);
}), 1000);
Meteor.publish("ServiceConfiguration", function (checkUserId) {
  check(checkUserId, Match.OneOf(String, null));
  if (this.userId === null) {
    return this.ready();
  }
  // Admins and account managers can manage the login methods for the shop
  if (Roles.userIsInRole(
    this.userId, ["owner", "admin", "dashboard/accounts"],
    Reaction.getShopId()
  )) {
    return ServiceConfiguration.configurations.find({});
  }

  return ServiceConfiguration.configurations.find({}, {
    fields: {
      secret: 0
    }
  });
});
Example #7
0
export function configureOauth() {
  ServiceConfiguration.configurations.upsert(
    {service: 'twitter'},
    {
      $set: {
        consumerKey: Meteor.settings.public.TwitterConsumerKey,
        secret: Meteor.settings.TwitterConsumerSecret
      }
    }
  );
}
Meteor.startup(() => {
  const services = Meteor.settings.private.oAuth;

  if (services) {
    for (const service in services) {
      if (services.hasOwnProperty(service)) {
        ServiceConfiguration.configurations.upsert({ service }, {
          $set: services[service]
        });
      }
    }
  }
});
Example #9
0
Meteor.startup(function() {
	return ServiceConfiguration.configurations.find({
		custom: true,
	}).observe({
		added(record) {
			return new CustomOAuth(record.service, {
				serverURL: record.serverURL,
				authorizePath: record.authorizePath,
				scope: record.scope,
			});
		},
	});
});
	getAccessToken(query) {
		const config = ServiceConfiguration.configurations.findOne({ service: this.name });
		if (!config) {
			throw new ServiceConfiguration.ConfigError();
		}

		let response = undefined;

		const allOptions = {
			headers: {
				'User-Agent': this.userAgent, // http://doc.gitlab.com/ce/api/users.html#Current-user
				Accept: 'application/json',
			},
			params: {
				code: query.code,
				redirect_uri: OAuth._redirectUri(this.name, config),
				grant_type: 'authorization_code',
				state: query.state,
			},
		};

		// Only send clientID / secret once on header or payload.
		if (this.tokenSentVia === 'header') {
			allOptions.auth = `${ config.clientId }:${ OAuth.openSecret(config.secret) }`;
		} else {
			allOptions.params.client_secret = OAuth.openSecret(config.secret);
			allOptions.params.client_id = config.clientId;
		}

		try {
			response = HTTP.post(this.tokenPath, allOptions);
		} catch (err) {
			const error = new Error(`Failed to complete OAuth handshake with ${ this.name } at ${ this.tokenPath }. ${ err.message }`);
			throw _.extend(error, { response: err.response });
		}

		let data;
		if (response.data) {
			data = response.data;
		} else {
			data = JSON.parse(response.content);
		}

		if (data.error) { // if the http response was a json object with an error attribute
			throw new Error(`Failed to complete OAuth handshake with ${ this.name } at ${ this.tokenPath }. ${ data.error }`);
		} else {
			return data.access_token;
		}
	}
Meteor.startup(() => {
  ServiceConfiguration.configurations.remove({});

  const {appId, secret} = Meteor.settings.loginServices.facebook;

  ServiceConfiguration.configurations.upsert(
    { service: "facebook" },
    {
      $set: {appId, secret}
    }
  );

  Accounts.onCreateUser(function(options, user) {
    if (user.services && user.services.facebook) {
      user.services.facebook.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
    }

    if (options.profile) {
      user.profile = {...user.profile, ...options.profile};
    }

    return user;
  });
});
Example #12
0
Meteor.logout = (...args) => {
	const serviceConfig = ServiceConfiguration.configurations.findOne({
		service: 'blockstack',
	});

	const blockstackAuth = Session.get('blockstack_auth');

	if (serviceConfig && blockstackAuth) {
		Session.delete('blockstack_auth');
		import('blockstack/dist/blockstack').then(({ signUserOut }) =>
			signUserOut(window.location.href));
	}

	return meteorLogout(...args);
};
Example #13
0
	timer = Meteor.setTimeout(function() {
		const data = {
			// These will pe passed to 'node-cas' as options
			enabled:          settings.get('CAS_enabled'),
			base_url:         settings.get('CAS_base_url'),
			login_url:        settings.get('CAS_login_url'),
			// Rocketchat Visuals
			buttonLabelText:  settings.get('CAS_button_label_text'),
			buttonLabelColor: settings.get('CAS_button_label_color'),
			buttonColor:      settings.get('CAS_button_color'),
			width:            settings.get('CAS_popup_width'),
			height:           settings.get('CAS_popup_height'),
			autoclose:        settings.get('CAS_autoclose'),
		};

		// Either register or deregister the CAS login service based upon its configuration
		if (data.enabled) {
			logger.info('Enabling CAS login service');
			ServiceConfiguration.configurations.upsert({ service: 'cas' }, { $set: data });
		} else {
			logger.info('Disabling CAS login service');
			ServiceConfiguration.configurations.remove({ service: 'cas' });
		}
	}, 2000);
Example #14
0
  "accounts/updateServiceConfiguration": function (service, fields) {
    check(service, String);
    check(fields, Array);
    const dataToSave = {};

    _.each(fields, function (field) {
      dataToSave[field.property] = field.value;
    });

    if (Reaction.hasPermission(["dashboard/accounts"])) {
      return ServiceConfiguration.configurations.upsert({
        service: service
      }, {
        $set: dataToSave
      });
    }
    return false;
  }
Example #15
0
Meteor.logout = function(...args) {
	const samlService = ServiceConfiguration.configurations.findOne({ service: 'saml' });
	if (samlService) {
		const provider = samlService.clientConfig && samlService.clientConfig.provider;
		if (provider) {
			if (samlService.logoutBehaviour == null || samlService.logoutBehaviour === logoutBehaviour.TERMINATE_SAML) {
				if (samlService.idpSLORedirectURL) {
					console.info('SAML session terminated via SLO');
					return Meteor.logoutWithSaml({ provider });
				}
			}

			if (samlService.logoutBehaviour === logoutBehaviour.ONLY_RC) {
				console.info('SAML session not terminated, only the Rocket.Chat session is going to be killed');
			}
		}
	}
	return MeteorLogout.apply(Meteor, args);
};
Example #16
0
Accounts.registerLoginHandler(function(options) {
	if (!options.accessToken) {
		return undefined; // don't handle
	}

	check(options, Match.ObjectIncluding({
		serviceName: String,
	}));

	const service = AccessTokenServices[options.serviceName];

	// Skip everything if there's no service set by the oauth middleware
	if (!service) {
		throw new Error(`Unexpected AccessToken service ${ options.serviceName }`);
	}

	// Make sure we're configured
	if (!ServiceConfiguration.configurations.findOne({ service: service.serviceName })) {
		throw new ServiceConfiguration.ConfigError();
	}

	if (!_.contains(Accounts.oauth.serviceNames(), service.serviceName)) {
		// serviceName was not found in the registered services list.
		// This could happen because the service never registered itself or
		// unregisterService was called on it.
		return {
			type: 'oauth',
			error: new Meteor.Error(
				Accounts.LoginCancelledError.numericError,
				`No registered oauth service found for: ${ service.serviceName }`
			),
		};
	}

	const oauthResult = service.handleAccessTokenRequest(options);

	return Accounts.updateOrCreateUserFromExternalService(service.serviceName, oauthResult.serviceData, oauthResult.options);
});
Example #17
0
import { ServiceConfiguration } from 'meteor/service-configuration';
import { Meteor } from 'meteor/meteor';

// const settings = Meteor.settings.google;
// console.log(settings)
// if(settings){
    ServiceConfiguration.configurations.update(
    { service: "google" },
    { $set: {
        clientId:"xxx",
        secret: "xxx",
        loginStyle: "popup"
      }
    },{upsert:true});
// }
Example #18
0
		added(record) {
			return new CustomOAuth(record.service, {
				serverURL: record.serverURL,
				authorizePath: record.authorizePath,
				scope: record.scope,
			});
		},
	});
});

Template.loginServices.helpers({
	loginService() {
		const services = [];
		const authServices = ServiceConfiguration.configurations.find({}, {
			sort: {
				service: 1,
			},
		}).fetch();
		authServices.forEach(function(service) {
			let icon;
			let serviceName;
			switch (service.service) {
				case 'meteor-developer':
					serviceName = 'Meteor';
					icon = 'meteor';
					break;
				case 'github':
					serviceName = 'GitHub';
					icon = 'github-circled';
					break;
				case 'gitlab':
Example #19
0
const fillSettings = _.debounce(Meteor.bindEnvironment(() => {
	config.serverURL = settings.get('API_Wordpress_URL');
	if (!config.serverURL) {
		if (config.serverURL === undefined) {
			return fillSettings();
		}
		return;
	}

	delete config.identityPath;
	delete config.identityTokenSentVia;
	delete config.authorizePath;
	delete config.tokenPath;
	delete config.scope;

	const serverType = settings.get('Accounts_OAuth_Wordpress_server_type');
	switch (serverType) {
		case 'custom':
			if (settings.get('Accounts_OAuth_Wordpress_identity_path')) {
				config.identityPath = settings.get('Accounts_OAuth_Wordpress_identity_path');
			}

			if (settings.get('Accounts_OAuth_Wordpress_identity_token_sent_via')) {
				config.identityTokenSentVia = settings.get('Accounts_OAuth_Wordpress_identity_token_sent_via');
			}

			if (settings.get('Accounts_OAuth_Wordpress_token_path')) {
				config.tokenPath = settings.get('Accounts_OAuth_Wordpress_token_path');
			}

			if (settings.get('Accounts_OAuth_Wordpress_authorize_path')) {
				config.authorizePath = settings.get('Accounts_OAuth_Wordpress_authorize_path');
			}

			if (settings.get('Accounts_OAuth_Wordpress_scope')) {
				config.scope = settings.get('Accounts_OAuth_Wordpress_scope');
			}
			break;
		case 'wordpress-com':
			config.identityPath = 'https://public-api.wordpress.com/rest/v1/me';
			config.identityTokenSentVia = 'header';
			config.authorizePath = 'https://public-api.wordpress.com/oauth2/authorize';
			config.tokenPath = 'https://public-api.wordpress.com/oauth2/token';
			config.scope = 'auth';
			break;
		default:
			config.identityPath = '/oauth/me';
			break;
	}

	const result = WordPress.configure(config);
	if (Meteor.isServer) {
		const enabled = settings.get('Accounts_OAuth_Wordpress');
		if (enabled) {
			ServiceConfiguration.configurations.upsert({
				service: 'wordpress',
			}, {
				$set: config,
			});
		} else {
			ServiceConfiguration.configurations.remove({
				service: 'wordpress',
			});
		}
	}

	return result;
}), Meteor.isServer ? 1000 : 100);
Example #20
0
// Meteor packages imports
import { Meteor } from 'meteor/meteor';

// Meteor contributed packages imports
import { ServiceConfiguration } from 'meteor/service-configuration';

// Collection imports
// import Settings from '/apinf_packages/settings/collection';
import LoginPlatforms from '../collection';

// Helper object to organize save functions for each service configuration
const updateFunctions = {
  saveGithubConfiguration (settings) {
    // remove existing configuration
    ServiceConfiguration.configurations.remove({
      service: 'github',
    });

    // Insert new service configuration if there are parameters given
    if (settings.githubConfiguration) {
      ServiceConfiguration.configurations.insert({
        service: 'github',
        clientId: settings.githubConfiguration.clientId,
        secret: settings.githubConfiguration.secret,
      });
    }

    // Return status message
    return 'GitHub configuration updated successfully';
  },
  saveFiwareConfiguration (settings) {
Example #21
0
			Accounts_Linkedin_secret: 'Accounts_OAuth_Linkedin_secret',
			Accounts_Meteor: 'Accounts_OAuth_Meteor',
			Accounts_Meteor_id: 'Accounts_OAuth_Meteor_id',
			Accounts_Meteor_secret: 'Accounts_OAuth_Meteor_secret',
			Accounts_Twitter: 'Accounts_OAuth_Twitter',
			Accounts_Twitter_id: 'Accounts_OAuth_Twitter_id',
			Accounts_Twitter_secret: 'Accounts_OAuth_Twitter_secret',
		};

		for (const from of Object.keys(changes)) {
			const to = changes[from];
			const record = RocketChat.models.Settings.findOne({
				_id: from,
			});

			if (record) {
				delete record._id;
				RocketChat.models.Settings.upsert({
					_id: to,
				}, record);
			}

			RocketChat.models.Settings.remove({
				_id: from,
			});
		}

		return ServiceConfiguration.configurations.remove({});
	},
});
Example #22
0
export function loadSettings(json) {
  check(json, String);
  let exists;
  let service;
  let services;
  let settings;
  const validatedJson = EJSON.parse(json);

  // validate json and error out if not an array
  if (!_.isArray(validatedJson[0])) {
    Logger.warn(
      "Load Settings is not an array. Failed to load settings.");
    return false;
  }

  let result;
  // loop settings and upsert packages.
  for (const pkg of validatedJson) {
    for (const item of pkg) {
      exists = Packages.findOne({
        name: item.name
      });
      //
      // TODO migrate functionality to Reaction.Import
      // Reaction.Import.package(item, shopId);
      //
      // insert into the Packages collection
      if (exists) {
        result = Packages.upsert({
          name: item.name
        }, {
          $set: {
            settings: item.settings,
            enabled: item.enabled
          }
        }, {
          multi: true,
          upsert: true,
          validate: false
        });
      }
      // sets the private settings of various
      // accounts authentication services
      if (item.settings.services) {
        for (services of item.settings.services) {
          for (service in services) {
            // actual settings for the service
            if ({}.hasOwnProperty.call(services, service)) {
              settings = services[service];
              ServiceConfiguration.configurations.upsert({
                service: service
              }, {
                $set: settings
              });
              Logger.debug("service configuration loaded: " +
                item.name + " | " + service);
            }
          }
        }
      }
      Logger.debug(`loaded local package data: ${item.name}`);
    }
  }
  return result;
}
function OAuthServicesRemove(_id) {
	const serviceName = _id.replace('Accounts_OAuth_Custom-', '');
	return ServiceConfiguration.configurations.remove({
		service: serviceName.toLowerCase(),
	});
}
	services.forEach((service) => {
		logger.oauth_updated(service.key);
		let serviceName = service.key.replace('Accounts_OAuth_', '');
		if (serviceName === 'Meteor') {
			serviceName = 'meteor-developer';
		}
		if (/Accounts_OAuth_Custom-/.test(service.key)) {
			serviceName = service.key.replace('Accounts_OAuth_Custom-', '');
		}
		if (service.value === true) {
			const data = {
				clientId: RocketChat.settings.get(`${ service.key }_id`),
				secret: RocketChat.settings.get(`${ service.key }_secret`),
			};
			if (/Accounts_OAuth_Custom-/.test(service.key)) {
				data.custom = true;
				data.clientId = RocketChat.settings.get(`${ service.key }-id`);
				data.secret = RocketChat.settings.get(`${ service.key }-secret`);
				data.serverURL = RocketChat.settings.get(`${ service.key }-url`);
				data.tokenPath = RocketChat.settings.get(`${ service.key }-token_path`);
				data.identityPath = RocketChat.settings.get(`${ service.key }-identity_path`);
				data.authorizePath = RocketChat.settings.get(`${ service.key }-authorize_path`);
				data.scope = RocketChat.settings.get(`${ service.key }-scope`);
				data.buttonLabelText = RocketChat.settings.get(`${ service.key }-button_label_text`);
				data.buttonLabelColor = RocketChat.settings.get(`${ service.key }-button_label_color`);
				data.loginStyle = RocketChat.settings.get(`${ service.key }-login_style`);
				data.buttonColor = RocketChat.settings.get(`${ service.key }-button_color`);
				data.tokenSentVia = RocketChat.settings.get(`${ service.key }-token_sent_via`);
				data.identityTokenSentVia = RocketChat.settings.get(`${ service.key }-identity_token_sent_via`);
				data.usernameField = RocketChat.settings.get(`${ service.key }-username_field`);
				data.mergeUsers = RocketChat.settings.get(`${ service.key }-merge_users`);
				new CustomOAuth(serviceName.toLowerCase(), {
					serverURL: data.serverURL,
					tokenPath: data.tokenPath,
					identityPath: data.identityPath,
					authorizePath: data.authorizePath,
					scope: data.scope,
					loginStyle: data.loginStyle,
					tokenSentVia: data.tokenSentVia,
					identityTokenSentVia: data.identityTokenSentVia,
					usernameField: data.usernameField,
					mergeUsers: data.mergeUsers,
				});
			}
			if (serviceName === 'Facebook') {
				data.appId = data.clientId;
				delete data.clientId;
			}
			if (serviceName === 'Twitter') {
				data.consumerKey = data.clientId;
				delete data.clientId;
			}
			ServiceConfiguration.configurations.upsert({
				service: serviceName.toLowerCase(),
			}, {
				$set: data,
			});
		} else {
			ServiceConfiguration.configurations.remove({
				service: serviceName.toLowerCase(),
			});
		}
	});
Example #25
0
Template.accountsSettings.onCreated(function () {
  this.subscribe("ServiceConfiguration", Meteor.userId());
});

/**
 * Account Settings Helpers
 */
Template.accountsSettings.helpers({

  /**
   * services
   * @return {Array} available services
   */
  services() {
    const serviceHelper = new ServiceConfigHelper();
    const configurations = ServiceConfiguration.configurations.find().fetch();

    const services = serviceHelper.services((item) => {
      const matchingConfigurations = _.filter(configurations, {
        service: item.name
      });
      if (matchingConfigurations.length) {
        return matchingConfigurations[0];
      }
    });

    return services;
  },

  /**
   * Template helper to add a hidden class if the condition is false
/* eslint "import/no-unresolved": [ 2, { "ignore": ["^meteor/"] }] */
import { Meteor } from 'meteor/meteor';
import { ServiceConfiguration } from 'meteor/service-configuration';

const services = Meteor.settings.private.oAuth;

ServiceConfiguration.configurations.upsert({
  service: 'facebook',
}, {
  $set: {
    clientId: services.facebook.clientId,
    loginStyle: 'popup',
    secret: services.facebook.secret,
  },
});