Meteorjs link social media accounts - meteor

I'm attempting to use the bozhao:link-accounts package from Atmosphere, but with no luck. Rather than linking the accounts, it is creating additional accounts. Here is what my implementation looks like:
PACKAGES ADDED:
meteor add accounts-facebook
meteor add accounts-twitter
meteor add bozhao:link-accounts
meteor add service-configuration
<!--/client/signIn.html-->
<template name="signInTmpl">
<button class="btn btn-facebook">Sign in with Facebook</button>
</template>
<!--/client/linkTweets.html-->
<template name="linkTweetsTmpl">
<button class="btn btn-twitter">Connect Twitter Account</button>
</template>
//client/signIn.js
Template.siginInTmpl.events({
'click .btn-facebook': function() {
Meteor.loginWithFacebook({requestPermissions: ['email']}, function(err) {
//Do if conditional ...
})
}
})
//client/linkTweets.js
Template.linkTweetsTmpl.events({
'click .btn-twitter': function() {
Meteor.linkWithTwitter(function(err) {
//Do if conditional ...
})
}
})
//server/accounts.js
var createServiceConfiguration;
createServiceConfiguration = function(service, clientId, secret) {
var config;
ServiceConfiguration.configurations.remove({
service: service
});
config = {
generic: {
service: service,
clientId: clientId,
secret: secret
},
instagram: {
service: service,
clientId: clientId,
scope: 'basic',
secret: secret,
loginStyle: "redirect"
},
facebook: {
service: service,
appId: clientId,
secret: secret,
loginStyle: "redirect"
},
twitter: {
service: service,
consumerKey: clientId,
secret: secret,
loginStyle: "redirect"
}
};
switch (service) {
case 'instagram':
return ServiceConfiguration.configurations.insert(config.instagram);
case 'facebook':
return ServiceConfiguration.configurations.insert(config.facebook);
case 'twitter':
return ServiceConfiguration.configurations.insert(config.twitter);
default:
return ServiceConfiguration.configurations.insert(config.generic);
}
};
//DEV KEYS
createServiceConfiguration('instagram', 'api-key', 'api-secret')
createServiceConfiguration('facebook', 'api-key', 'api-secret')
createServiceConfiguration('twitter', 'api-key', 'api-secret')
createServiceConfiguration('google', 'api-key', 'api-secret')
I successfully sign in with Facebook and when I click on the "Connect Twitter Button" it goes through the authorisation sequence fine, but then creates another account altogether.

I recommend using https://atmospherejs.com/splendido/accounts-meld instead to do what you want. The documentation is pretty self explanatory and it supports a wide range of account melding configurations.

Related

How to populate client-side Meteor.user.services after OAuth with built-in accounts-ui package in Meteor v1.4+?

I'm using accounts-ui and accounts-google in Meteor v1.4.1. I can't get the user.services object to appear scoped in the client code. In particular, I need google's profile picture.
I've configured the server-side code to authenticate with Google like so:
import { Meteor } from 'meteor/meteor';
import { ServiceConfiguration } from 'meteor/service-configuration';
const services = Meteor.settings.private.oauth;
for (let service of Object.keys(services)) {
ServiceConfiguration.configurations.upsert({
service
}, {
$set: {
clientId: services[service].app_id,
secret: services[service].secret,
loginStyle: "popup"
}
});
}
...and the client side code to configure permissions like so:
Accounts.ui.config({
requestPermissions: {
google: ['email', 'profile']
},
forceApprovalPrompt: {
google: true
},
passwordSignupFields: 'EMAIL_ONLY'
});
When users click the 'Sign-In with Google' button, a pop-up appears and they can authenticate. No prompt appears, however, despite forceApprovalPrompt being set to true for google.
The big issue is that when I execute this,
const user = Meteor.user();
console.log(user.services);
anywhere in client code, I do not see the expected user services information. I check my database and it is definitely there for the taking:
$ mongo localhost:27017
> db.users.find({})
> ... "services" : { "google" : { "accessToken" : ... } } ...
I'm curious what I'm missing? Should I explicitly define a publish function in order for user services data to exist in the client?
The services property is intentionally hidden on the client side for security reasons. There are a couple of approaches here :
Suggestions
My preferred one would be to expose a meteor method to bring you the
public keys and avatars you might need in the few places you'd need
them.
On a successful login, you could record the data you need somewhere in the user object, but outside of the services property.
As you said, you could make a new publication which explicitly specifies which fields to retrieve and which ones to hide. You have to be careful what you publish, though.
Code Examples
Meteor methods:
// server
Meteor.methods({
getProfilePicture() {
const services = Meteor.user().services;
// replace with actual profile picture property
return services.google && services.google.profilePicture;
}
});
// client
Meteor.call('getProfilePicture', (err, profilePicture) => {
console.log('profile picture url', profilePicture);
});
Update on successful user creation (you might want to have a login hook as well to reflect any avatar/picture changes in google):
// Configure what happens with profile data on user creation
Accounts.onCreateUser((options, user) => {
if (!('profile' in options)) { options.profile = {}; }
if (!('providers' in options.profile)) { options.profile.providers = {}; }
// Define additional specific profile options here
if (user.services.google) {
options.profile.providers.google = {
picture: user.services.google.picture
}
}
user.profile = options.profile;
return user;
});
Publish only select data...
// Server
Meteor.publish('userData', function () {
if (this.userId) {
return Meteor.users.find({ _id: this.userId }, {
fields: { other: 1, things: 1 }
});
} else {
this.ready();
}
});
// Client
Meteor.subscribe('userData');

FlowRouter redirect if user is logged in and if path is

I'm using Meteor with FlowRouter and i'm looking for a condition like this:
if the user is logged && if the accessed path is http://x.x.x.x/
then redirect to http://x.x.x.x/clients
My current Routes:
Accounts.onLogin(function(){
FlowRouter.go('clients');
});
Accounts.onLogout(function(){
FlowRouter.go('home')
});
FlowRouter.triggers.enter([function(context, redirect){
if(!Meteor.userId()){
FlowRouter.go('home')
}
}]);
FlowRouter.route('/', {
name: 'home',
action(){
BlazeLayout.render('HomeLayout');
}
});
FlowRouter.route('/clients',{
name: 'clients',
action(){
BlazeLayout.render('MainLayout', {main: 'Clients'});
}
});
if(Meteor.userId() && FlowRouter.getRouteName() === 'route_name'){
FlowRouter.go('/route_name');
}
In flow router docs there are a few was to get the current route if you need to restructure the statement above.
https://github.com/kadirahq/flow-router/blob/master/README.md
I'd say that you just have to change your FlowRouter.route('/'...) configuration a bit:
FlowRouter.route('/', {
triggersEnter: [function(context, redirect) {
if (Meteor.userId()) {
redirect('/clients');
}
}],
name: 'home',
action(){
BlazeLayout.render('HomeLayout');
}
});
So any logged in user that accesses '/' will be redirected to 'clients' - worked fine when I tested it. Here's some background info in the flow router docs: https://github.com/kadirahq/flow-router/blob/master/README.md#redirecting-with-triggers

How to get user ID during user creation in Meteor?

I am creating default users on the server with a Meteor startup function. I want to create a user and also verify his/her email on startup (I'm assuming you can only do this after creating the account).
Here's what I have:
Meteor.startup(function() {
// Creates default accounts if there no user accounts
if(!Meteor.users.find().count()) {
// Set default account details here
var barry = {
username: 'barrydoyle18',
password: '123456',
email: 'myemail#gmail.com',
profile: {
firstName: 'Barry',
lastName: 'Doyle'
},
roles: ['webmaster', 'admin']
};
// Create default account details here
Accounts.createUser(barry);
Meteor.users.update(<user Id goes here>, {$set: {"emails.0.verified": true}});
}
});
As I said, I assume the user has to be created first before setting the the verified flag as true (if this statement is false please show a solution to making the flag true in the creation of the user).
In order to set the email verified flag to be true I know I can update the user after creation using Meteor.users.update(userId, {$set: {"emails.0.verified": true}});.
My problem is, I don't know how to get the userID of my newly created user, how do I do that?
You should be able to access the user id that is returned from the Accounts.createUser() function:
var userId = Accounts.createUser(barry);
Meteor.users.update(userId, {
$set: { "emails.0.verified": true}
});
Alternatively you can access newly created users via the Accounts.onCreateUser() function:
var barry = {
username: 'barrydoyle18',
password: '123456',
email: 'myemail#gmail.com',
profile: {
firstName: 'Barry',
lastName: 'Doyle'
},
isDefault: true, //Add this field to notify the onCreateUser callback that this is default
roles: ['webmaster', 'admin']
};
Accounts.onCreateUser(function(options, user) {
if (user.isDefault) {
Meteor.users.update(user._id, {
$set: { "emails.0.verified": true}
});
}
});

How to avoid that Accounts.onCreateUser overwrites users.profile?

on the client site I have an extraSignupField -> name. This is stored in users.profile.name. Here is the code:
Meteor.startup(function() {
Accounts.ui.config({
passwordSignupFields: 'EMAIL_ONLY'
});
AccountsEntry.config({
homeRoute: '/',
dashboardRoute: '/dashboard',
profileRoute: '/profile',
language: 'de',
showSignupCode: false,
extraSignUpFields: [{
field: "name",
label: "Name",
type: "text",
required: true
}]
});
});
On the server site I run onCreateUser, this gets fired but it only sets the values which at mentioned there. NO users.profile entry is created when onCreateUser is in place.
Here is the server code:
Meteor.startup(function() {
AccountsEntry.config({
signupCode: null
});
Accounts.onCreateUser(function (options, user) {
user.username = options.email;
return user;
});
});
My goal is to keep the data from users.profile AND the username entry. Unfortunately I got stuck at this point.
Thanks a lot
Michael
When you write your own Accounts.onCreateUser, it overrides the default. In the default, options.profile is copied to user.profile. You can restore default behavior by making this copy in your own version of the function. You see this in the docs.
Accounts.onCreateUser( function (options, user) {
if (options.profile) user.profile = options.profile;
user.username = options.email;
return user;
}

How to add External Service logins to an already existing account in Meteor?

Having created a profile page for my app, I would like to display a list of social services that the user is on. It struck me that the easiest way would be to use Meteor's built in accounts system for this.
Is there a good way to add external services to an existing account?
Also, will the user then be able to log in with either (e.g.) Facebook and his password from my app?
Another question that naturally follows: Is there a good way to add an application specific password to an account that was created with an external service?
Here's an alternate method. In this solution, I'm overriding a core function and adding some custom behavior. My goal is to associate the service data with the currently logged in user, then allow the core function to do its thing like normal.
orig_updateOrCreateUserFromExternalService = Accounts.updateOrCreateUserFromExternalService;
Accounts.updateOrCreateUserFromExternalService = function(serviceName, serviceData, options) {
var loggedInUser = Meteor.user();
if(loggedInUser && typeof(loggedInUser.services[serviceName]) === "undefined") {
var setAttr = {};
setAttr["services." + serviceName] = serviceData;
Meteor.users.update(loggedInUser._id, {$set: setAttr});
}
return orig_updateOrCreateUserFromExternalService.apply(this, arguments);
}
Pros:
Avoids creation of unnecessary accounts
Code is short and easy to understand
Code is easy to remove if this functionality is added to Meteor core
Cons:
Requires the user to be logged in. If a user logs in with twitter initially, logs out, and then logs in with facebook, then two seperate accounts will be created.
Users who share a computer may get their accounts merged unintentionally.
Relies on knowledge of how updateOrCreateUserFromExternalService works. This isn't terrible - because it's part of Meteor's public api it probably won't change drastically (not often anyway). But it's still risky.
Here is how I add credentials to existing user account: .../meteor-how-to-login-with-github-account.html
Yes, a user account can be associated with multiple services and have a password-based login at the same time. In the Meteor docs, you can see the structure of such a user account:
{
_id: "bbca5d6a-2156-41c4-89da-0329e8c99a4f", // Meteor.userId()
username: "cool_kid_13", // unique name
emails: [
// each email address can only belong to one user.
{ address: "cool#example.com", verified: true },
{ address: "another#different.com", verified: false }
],
createdAt: 1349761684042,
profile: {
// The profile is writable by the user by default.
name: "Joe Schmoe"
},
services: {
facebook: {
id: "709050", // facebook id
accessToken: "AAACCgdX7G2...AbV9AZDZD"
},
resume: {
loginTokens: [
{ token: "97e8c205-c7e4-47c9-9bea-8e2ccc0694cd",
when: 1349761684048 }
]
}
}
}
For adding a username/password login to an existing account, you can use Accounts.sendResetPasswordEmail on the server side. This also ensures the change happens authenticated and authorized.
Of course you can also just update the user record on the server side with a new password yourself, but this might create a security hole in your app. I would also advise against implementing your own crypto protocol for this if possible, as it is hard.
If you want to add other services than email, you could for example
call a server method that saves a random, long token in the current user's MongoDB document and returns it to the client.
re-login the user with another service using Accounts.loginWith[OtherService]. This logs the user out and in again, using a new account on the other service.
call a second server method with the returned token from the first method as parameter. This second method searches for the user account with the given token and merges its data into the current (new) account.
Check out the example and answer in this posting. It pretty much gives you the code to integrate multiple external and internal accounts. With minor tweaks, you can add the password fields for each account as you desire.
How to use Meteor.loginWithGoogle with mrt:accounts-ui-bootstrap-dropdown
Code:
isProdEnv = function () {
if (process.env.ROOT_URL == "http://localhost:3000") {
return false;
} else {
return true;
}
}
Accounts.loginServiceConfiguration.remove({
service: 'google'
});
Accounts.loginServiceConfiguration.remove({
service: 'facebook'
});
Accounts.loginServiceConfiguration.remove({
service: 'twitter'
});
Accounts.loginServiceConfiguration.remove({
service: 'github'
});
if (isProdEnv()) {
Accounts.loginServiceConfiguration.insert({
service: 'github',
clientId: '00000',
secret: '00000'
});
Accounts.loginServiceConfiguration.insert({
service: 'twitter',
consumerKey: '00000',
secret: '00000'
});
Accounts.loginServiceConfiguration.insert({
service: 'google',
appId: '00000',
secret: '00000'
});
Accounts.loginServiceConfiguration.insert({
service: 'facebook',
appId: '00000',
secret: '00000'
});
} else {
// dev environment
Accounts.loginServiceConfiguration.insert({
service: 'github',
clientId: '11111',
secret: '11111'
});
Accounts.loginServiceConfiguration.insert({
service: 'twitter',
consumerKey: '11111',
secret: '11111'
});
Accounts.loginServiceConfiguration.insert({
service: 'google',
clientId: '11111',
secret: '11111'
});
Accounts.loginServiceConfiguration.insert({
service: 'facebook',
appId: '11111',
secret: '11111'
});
}
Accounts.onCreateUser(function (options, user) {
if (user.services) {
if (options.profile) {
user.profile = options.profile
}
var service = _.keys(user.services)[0];
var email = user.services[service].email;
if (!email) {
if (user.emails) {
email = user.emails.address;
}
}
if (!email) {
email = options.email;
}
if (!email) {
// if email is not set, there is no way to link it with other accounts
return user;
}
// see if any existing user has this email address, otherwise create new
var existingUser = Meteor.users.findOne({'emails.address': email});
if (!existingUser) {
// check for email also in other services
var existingGitHubUser = Meteor.users.findOne({'services.github.email': email});
var existingGoogleUser = Meteor.users.findOne({'services.google.email': email});
var existingTwitterUser = Meteor.users.findOne({'services.twitter.email': email});
var existingFacebookUser = Meteor.users.findOne({'services.facebook.email': email});
var doesntExist = !existingGitHubUser && !existingGoogleUser && !existingTwitterUser && !existingFacebookUser;
if (doesntExist) {
// return the user as it came, because there he doesn't exist in the DB yet
return user;
} else {
existingUser = existingGitHubUser || existingGoogleUser || existingTwitterUser || existingFacebookUser;
if (existingUser) {
if (user.emails) {
// user is signing in by email, we need to set it to the existing user
existingUser.emails = user.emails;
}
}
}
}
// precaution, these will exist from accounts-password if used
if (!existingUser.services) {
existingUser.services = { resume: { loginTokens: [] }};
}
// copy accross new service info
existingUser.services[service] = user.services[service];
existingUser.services.resume.loginTokens.push(
user.services.resume.loginTokens[0]
);
// even worse hackery
Meteor.users.remove({_id: existingUser._id}); // remove existing record
return existingUser; // record is re-inserted
}
});

Resources