Publishing Users information but without "secret" fields - meteor

I am publishing multi-user information (using Meteor.users collection) for the purpose of naming posts creators and have their names and other small details associated with those posts, but I do NOT want to publish the complete documents for each user as they have "secret" login information.
Here is the code I am using:
Meteor.publish("serverforumthread", function(thread){
check(thread, String);
var replies = forumReplies.find({thread: thread});
var users = {};
replies.map(function(r){
users[r.owner] = r.owner;
});
var userids = _.map(users, function(value, key){ return value; });
var projectedFields = {_id:1, username:1, forumStats: 1, services: 0};
var usrs = Meteor.users.find({_id:{$in: userids}}, projectedFields);
var anyUpdateToUsers = false;
usrs.map(function(owner){
var changed = false;
if(!owner.username){
owner.username = owner.emails[0].address.split("#")[0];
changed = true;
}
//owner.forumStats = undefined;
if(!owner.forumStats){
owner.forumStats = {};
owner.forumStats.postCount = 0;
owner.forumStats.postLikes = 0;
owner.forumStats.title = "the newbie";
owner.forumStats.tag = "newbie";
owner.forumStats.img = "http://placehold.it/122x122";
changed = true;
}
if(changed){
anyUpdateToUsers = true;
Meteor.users.update({_id: owner._id}, {$set:{ forumStats:owner.forumStats }});
}
});
if(anyUpdateToUsers) // refresh it
usrs = Meteor.users.find({_id:{$in: userids}}, projectedFields);
usrs.map(function(owner){
console.log(owner);
});
return [replies, usrs];
});
As you can see, I am only interested in publishing relies (posts) for a thread and their associated users username and small forumStats, I want to keep the "services" key secret, as it contains details that should not be published.
A sample output of the "console.log":
{ _id: 'hoRYFbRkXXbHYm8Ty',
createdAt: Tue Jun 03 2014 16:25:42 GMT+0100 (WEST),
emails: [ { address: 'somemail#gmail.com', verified: false } ],
forumStats:
{ postCount: 85,
postLikes: 5,
title: 'the newbie',
tag: 'newbie',
img: 'http://placehold.it/122x122' },
services:
{ password: { srp: [Object] },
resume: { loginTokens: [Object] } } }
What am I doing wrong?
Thank you.

Have a look at the examples in the field specifiers section of the docs, and give this a try:
var projectedFields = {fields: {username:1, forumStats: 1}};
You'll get _id for free, and it will only include the other fields that you specify. Note that you can't mix inclusion and exclusion options, meaning you can't have both 0's and 1's.
If that doesn't work, let me know and I'll look more carefully.

Related

firebase reset password controller

Yesterday my app was launched, Ionic v1, and a few users entered the wrong password and can't log into the app.
The app uses firebase authentication. I have a __refs file that points to the database and have tried numerous things trying to get the reset to work.
I've tried referencing $firebaseAuth, of course my __refs, $firebase then use $firebase.auth()...
I didn't write the authentication of this app so I'm not real sure how it works. I'm hoping that someone can help me.
My reset controller
angular.module('formulaWizard').controller('ResetPasswordCtrl',
function($scope, $ionicLoading, $firebaseAuth, __Refs) {
$scope.user = {
email: ''
};
$scope.errorMessage = null;
var fbAuth = $firebaseAuth(__Refs.rootRef);
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
fbAuth.sendPasswordResetEmail($scope.user.email)
.then(showConfirmation)
.catch(handleError);
};
function showConfirmation() {
$scope.emailSent = true;
$ionicLoading.hide();
}
function handleError(error) {
switch (error.code) {
case 'INVALID_EMAIL':
case 'INVALID_USER':
$scope.errorMessage = 'Invalid email';
break;
default:
$scope.errorMessage = 'Error: [' + error.code + ']';
}
$ionicLoading.hide();
}
});
My Refs file
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
customers: ref.child('customers'),
}
});
I can't take credit for the answer it was provide by Abimbola Idowu on HackHands.
Since I paid for the answer I thought I would share it with anyone else that might also be stumped by this.
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
__Refs.rootRef.resetPassword({ email: $scope.user.email }, function(error) {
if (error === null) {
showConfirmation();
} else {
handleError()
}
});
};
This is the __refs service
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
}
});

Meteor observe not working properly in 1.6

I recently upgraded from 1.2 to Meteors latest version 1.6.0.1.
I was using observe in a publication and an observe on the client to get changes.
in 1.2 no problems at all, but in 1.6 observed changes are not received in a "changed" client callback, but the client does get the ddp message. I can verify that by looking in Chromes dev tools > websocket, see the incoming message, but it's never fired in a client callback. This only happens when changing 2-3 documents at a time.
So when I delete a few documents from the DB, the publication fires off the callbacks, and the client receives them in the websocket messages, but it only fires once in the "observe" callback on the client.
Here is my code.
Client -
CollectionTest = new Meteor.Collection('collectionTest');
CollectionTest.find({}).observe({
added: function (doc) {
console.log("ADDED DOC ", doc);
},
changed: function (newDoc, oldDoc) {
console.log("CHANGED DOC new ", newDoc);
},
removed: function (doc) {
console.log("REMOVED DOC ", doc);
}
});
Server Publication -
Meteor.publish("ddpPub", function () {
var self = this,
ready = false;
var userId = self.userId;
var subHandle = TestData.find({}).observeChanges({
added: function (id, fields) {
if (ready) {
self.changed("collectionTest", userId, {
type: "added",
data: {
id: id,
fields: fields
}
});
}
},
changed: function (id, fields) {
if (ready) {
self.changed("collectionTest", userId, {
type: "changed",
data: {
id: id,
fields: fields
}
});
}
},
removed: function (id) {
if (ready) {
self.changed("collectionTest", userId, {
type: "removed",
data: id
});
}
}
});
self.added("collectionTest", userId);
self.ready();
ready = true;
self.onStop(function () {
subHandle.stop();
});
});
Attached are images from me removing the documents from the DB. The websocket messages, and then my console on the client. Showing it only fires once for 5 documents.
Showing the document id's I am deleting
DDP messages in 'websocket' confirmed they get to client
Single client message in client callback showing only document changed
UPDATE: 12/15/17 - 7:17pm PST
After working on this for a couple hours, finding some related meteor posts with observe callbacks and “Meteor.call” not working inside, the solution or hack is to wrap the “Meteor.call” in a “setTimeout” with the value of 0, and it fixes it.
I tried that here, and it didn’t work, but then I tried throttle the response, and it works! Not sure if it's a reliable fix, but it's the only one I found so far.
I am not sure why this works, or what causes the problem in the first place, any explanation would be welcome.
Server Publication -
Meteor.publish("ddpPub", function () {
var self = this,
ready = false;
var userId = self.userId;
var subHandle = TestData.find({}).observeChanges({
added: function (id, fields) {
if (ready) {
console.log("ADDING PUBLICATION");
self.changed("collectionTest", userId, {
type: "added",
data: {
id: id,
fields: fields
}
});
}
},
changed: function (id, fields) {
if (ready) {
console.log("CHANGING PUBLICATION");
self.changed("collectionTest", userId, {
type: "changed",
data: {
id: id,
fields: fields
}
});
}
},
removed: function (id) {
if (ready) {
console.log("REMOVING PUBLICATION");
ratePub(id, function (data) {
console.log("OBJECT DATA IS ", data);
self.changed("collectionTest", userId, data);
});
}
}
});
self.added("collectionTest", userId);
self.ready();
ready = true;
self.onStop(function () {
subHandle.stop();
});
});
var returnPub = function (id, callback) {
console.log("RETURNING PUB ");
callback({
id: id,
type: "removed",
data: id
});
};
var ratePub = _.rateLimit(returnPub, 10);

Extend object on Meteor

When i add/edit blogPost, i've my object with all properties. My code :
Add post :
Template.postListAdmin.events({
'submit form': (e) => {
// Prevent default browser form submit
e.preventDefault();
let image = $('#js-image-uploaded'),
draft = $('[name="draft"]'),
isSmall = false,
isDrafted = false;
// If post draft, return true
if (draft.is(':checked')) isDrafted = true;
// If post image is small
// return true for add 'small' classe
if (image.height() < 80) isSmall = true;
let post = {
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
content: $('[name="content"]').val(),
draft: isDrafted
};
Meteor.call('posts.insert', post);
setTimeout(() => {
$('#js-post-form')
.toggleClass('is-hidden')
.find('input, textarea').val('');
}, 500);
}
});
Edit post :
Template.postEdit.events({
'submit form': function (e) {
e.preventDefault();
let image = $('#js-image-uploaded'),
draft = $('[name="draft"]'),
isSmall = false,
isDrafted;
if (draft.is(':checked')) isDrafted = true;
else isDrafted = false;
if (image.height() < 80) isSmall = true;
let post = {
slug: $('[name="title"]').val(),
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
dateModified: new Date(),
content: $('[name="content"]').val(),
draft: isDrafted
};
Meteor.call('posts.edit', this._id, post);
Router.go('postListAdmin');
},
});
I would like optimize my code and avoid creating my object 'post' 2x.
Do you have any idea how i can optim this ?
Thank you every boby :)
You should be able to achieve what you want to do by defining post without the let keyword.
For example:
post = {
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
content: $('[name="content"]').val(),
draft: isDrafted
};
You will have to decide how you want to handle the two instances, though, since they are not exactly the same. Also, moving the variable definition outside of either file might be helpful for organizing your code. You could use a directory on the client named utils, and add a file that contains your global variable definitions.

Publish users using id from a different collection

I'm trying to access the userIds stored in a collection and then use them to publish the details of all of the meteor.users. My publish function doesn't isn't return anything?
Meteor.publish('allUsersWithOffers', function () {
var user = Offers.find({}, {fields: {"UserId": 1}});
return Meteor.users.find({_id: user});
});
Give this a try:
Meteor.publish('allUsersWithOffers', function () {
var offers = Offers.find({}, { fields: { UserId: 1 } }).fetch();
var ids = _.pluck(offers, 'UserId');
// This is critical - you must limit the fields returned from
// the users collection! Update this as needed.
options = { fields: { username: 1, emails: 1 } };
return Meteor.users.find({ _id: { $in: ids } }, options);
});
find returns a cursor - you need to call fetch to actually get the documents.

Publish forum replies with embedded user data

I am trying to publish forum replies to a specific thread, but I would like those reply documents to include extra information about the user that posted it.
I don't want to "save" that extra information on the reply itself but rather, publish an "improved" version of it.
I am doing something similar on client-side already with mycollection.find().map() and using the map function to embedded extra information on each of the returned documents, however, Meteor publish cannot seem to publish an array, only a Cursor, so the simple map function is off limits.
Is there a way to achieve this? Maybe a "map" function that returns a Cursor?
I am not using Meteor.methods so that I can have reactivity, because with them I could just return an array and use it as normal.
Here is an example of my code (that fails, but sends gives an idea of what I need):
Meteor.publish("forumthread", function(thread){
return forumReplies.find({thread: thread}).map(function(r){
// lets fill in additional data about each replies owner
var owner = Meteor.users.findOne({_id: r.owner});
if(!owner)
return; // no owner no reply..
if(!owner.forumStats){
owner.forumStats = {};
owner.forumStats.postCount = 0;
owner.forumStats.postLikes = 0;
owner.forumStats.title = "The Newbie";
owner.forumStats.tag = "Newbie";
Meteor.users.update({_id: owner._id}, {$set:{ forumStats:owner.forumStats }});
}
r.ownerid = owner._id;
r.ownerUsername = owner.username;
r.ownerPostCount = owner.forumStats.postCount;
r.ownerPostLikes = owner.forumStats.postLikes;
r.ownerTitle = owner.forumStats.title;
r.ownerTag = owner.forumStats.tag;
return r;
});
});
Thank you.
Ended up doing this (found out that Christian Fritz also suggested it):
Meteor.publish("serverforumthread", function(thread){
check(thread, String);
var replies = forumReplies.find({thread: thread});
var users = {};
replies.map(function(r){
users[r.owner] = r.owner;
});
var userids = _.map(users, function(value, key){ return value; });
var projectedFields = {_id:1, username:1, forumStats: 1, services: 0};
var usrs = Meteor.users.find({_id:{$in: userids}}, projectedFields);
var anyUpdateToUsers = false;
usrs.map(function(owner){
var changed = false;
if(!owner.username){
owner.username = owner.emails[0].address.split("#")[0];
changed = true;
}
//owner.forumStats = undefined;
if(!owner.forumStats){
owner.forumStats = {};
owner.forumStats.postCount = 0;
owner.forumStats.postLikes = 0;
owner.forumStats.title = "the newbie";
owner.forumStats.tag = "newbie";
owner.forumStats.img = "http://placehold.it/122x122";
changed = true;
}
if(changed){
anyUpdateToUsers = true;
Meteor.users.update({_id: owner._id}, {$set:{ forumStats:owner.forumStats }});
}
});
if(anyUpdateToUsers) // refresh it
usrs = Meteor.users.find({_id:{$in: userids}}, projectedFields);
usrs.map(function(owner){
console.log(owner);
});
return [replies, usrs];
});
It works great with the following client side:
Template.forumReplyOwner.helpers({
replyOwner: function(reply){
var owner = Meteor.users.findOne({_id: reply.owner});
console.log(reply, owner);
if(!owner || !owner.forumStats) return; // oh shait!
var r = {};
r.owner = owner._id;
r.ownerUsername = owner.username;
r.ownerPostCount = owner.forumStats.postCount;
r.ownerPostLikes = owner.forumStats.postLikes;
r.ownerTitle = owner.forumStats.title;
r.ownerTag = owner.forumStats.tag;
r.ownerImg = owner.forumStats.img;
return r;
},
ownerImgTab: function(){
return {src: this.ownerImg};
}
});
However, I am now facing another problem. Even tho I am restricting the fields I am publishing from the Users collection, it is still sending down the "services" field, that contains login data that shouldnt be sent, ideas?

Resources