alina
alina

Reputation: 291

Add a user manually on server side and set their session

I can't seem to understand the relation between Accounts.createUser() and Accounts.onCreateUser(). I have an external api that validates the users' login credentials. Once the api sends me a positive response, I need to add the user in MongoDB and start its session so it can be considered as a logged in user. Accounts.createUser() is creating a user on server side, but I need Accounts.onCreateUser() because I need to add custom fields like user's token that is being generated from the external api.

This is the code I have right now (which doesn't add a user at all):

server-side code:

var request = {
'headers': {
  'Content-Type': 'application/x-www-form-urlencoded'
},
'params': user
};

try {

var response = HTTP.call('POST', url, request); //send call to the external api
var token = response.data.token;
//decode the token and add the user in the database
var userInfo = Base64.decode(token.split('.')[1]);

var options = {
  email: user._username,
  profile: {
    name: user._username
  },
  token: token
};

var user = Accounts.onCreateUser(function(options, user) {
   if (options.token)
       user.token = options.token;
   if (options.profile)
       user.profile = options.profile;
   return user;
 });

console.log(user); //this returns undefined
return JSON.stringify({
  'code': 200,
  'token': userInfo
});
} catch (error) {
  console.log(error);
//console.log(error.response);
var body = error.response.content;
return body;
}

Upvotes: 1

Views: 80

Answers (1)

alina
alina

Reputation: 291

Okay. So I finally found what I had been looking for. The relation between Accounts.createUser and Accounts.onCreateUser is that Accounts.onCreateUser is a hook and adds extended functionality to the original Accounts.createUser function. What is the extended functionality? It lets you create additional fields prior to actually inserting your user in the database. You have to write this hook in your main.js (server side) in the startup code snippet:

Meteor.startup(() => {
 Accounts.onCreateUser(function(options, user) {
if (options.token)
    user.token = options.token;
if (options.profile)
    user.profile = options.profile;
return user;
 });
})

And wherever you want to add the user, simply call Accounts.createUser() and this hook will be called automatically prior to the createUser call

Upvotes: 1

Related Questions