Pages

Tuesday, August 2, 2016

Learning Meteor.js [Part 42]: Access the user profile on a server method

We have already seen how to use 'this.userId' to access the user id from a server method and subscription. To access more information about the current user you can call Meteor.user(). Here is an example on how to get the user's display name and his/her email address.
export const addOrUpdate = new ValidatedMethod({
    name: 'recipe.addOrUpdate',
    validate: new SimpleSchema({
        recipe: { type: RecipeSchema }
    }).validator({ clean: true }),
    mixins: [Mixins.authenticated],
    run({ recipe }) {
        var user = Meteor.isServer && Meteor.user();
        var email = user && user.services.google.email;
        var displayName = user && user.profile.name;

        recipe.userId = this.userId;
        recipe.userName = email && email.substring(0, email.indexOf('@'));
        recipe.author = displayName;

        Recipes.update({ _id: recipe._id }, recipe, { upsert: true });
    }
});

Notice that the information is stored in two separate places of the user object. The 'profile' object is a standard structure regardless of the login provider used, and it has things like the full display name of the user. Under the 'services' object you will find separate object for each login provider that is used, in my case there is a key for the 'google' service provider and under it the structure depends on each provider.

Meteor.isServer is checked inside the method because the services object is not passed into the client so the call would fail when the stub runs on the client.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.