Meteor simpleSchema prevent field updates - meteor

Is it possible to specify that a field is not updateable using the schema itself rather than defining it in an allow/deny rule?
I am wondering because I use a quickform to allow users to edit their user details based on the users document (accounts package) and I want to prevent them from being able to change the verified state for their email address.
A rule based on user roles would be great to only allow admins and meteor itself to change the state of this field.
I'd be hoping for something like this:
emails: {
type: Array,
optional: true
},
"emails.$": {
type: Object
},
"emails.$.address": {
type: String,
regEx: SimpleSchema.RegEx.Email
},
"emails.$.verified": {
type: Boolean
allowRoles: ['admin','system'] // this does not exist
},
regards, Chris

You have a few different options.
To prevent anyone from updating a field, you can set the denyUpdate field in the flag definition (requires aldeed:collection2)
"emails.$.verified": {
type: Boolean
denyUpdate: true
},
To allow it to be updated by admin's only, you could try a custom validator that checks the userId to see if it is an admin (example requires aldeed:collection2 and alanning:roles)
"emails.$.verified": {
type: Boolean
custom: function() {
if ( this.isSet && this.isUpdate && !Roles.userIsInRole(this.userId, "admin") ) {
return "unauthorized";
}
}
},
You'd probably also want to define a message for the "unauthorized" validation error.
SimpleSchema.messages({
"unauthorized" : "You do not have permission to update this field"
})
This will display an error to the user if they try to change the field.
Alternately, you could simply unset the value provided by non-admin users and allow the rest of the update to go ahead.
"emails.$.verified": {
type: Boolean
autoValue: function() {
if ( !Roles.userIsInRole(this.userId, "admin") ) {
this.unset();
}
}
},

Related

simpl-schema: How to create an schema that validates every property of an object is of a certain schema?

Basically... I have something of the following type: record<string, User> (aka Map<String,User>). Basically, an object that can have any field, as long as it is an user.
How do I create an Schema that validates that?
There is an older question that seems to ask the same thing Can SimpleSchema express "object with custom keys and specific schema for values"? , however being asked for an older version of this library.
The accepted answer assumes the usage of Custom Validators
https://github.com/longshotlabs/simpl-schema#type
Another SimpleSchema instance, meaning Object type with this schema
const userSchema = new SimpleSchema({
username: {
type: String,
// For accounts-password, either emails or username is required, but not both. It is OK to make this
// optional here because the accounts-password package does its own validation.
// Third-party login packages may not require either. Adjust this schema as necessary for your usage.
optional: true,
},
emails: {
type: Array,
// For accounts-password, either emails or username is required, but not both. It is OK to make this
// optional here because the accounts-password package does its own validation.
// Third-party login packages may not require either. Adjust this schema as necessary for your usage.
optional: true,
},
'emails.$': {
type: Object,
},
'emails.$.address': {
type: String,
regEx: SimpleSchema.RegEx.Email,
},
'emails.$.verified': {
type: Boolean,
},
// Use this registered_emails field if you are using splendido:meteor-accounts-emails-field / splendido:meteor-accounts-meld
registered_emails: {
type: Array,
optional: true,
},
'registered_emails.$': {
type: Object,
blackbox: true,
},
createdAt: {
type: Date,
},
profile: {
type: Schema.UserProfile,
optional: true,
},
// Make sure this services field is in your schema if you're using any of the accounts packages
services: {
type: Object,
optional: true,
blackbox: true,
},
// DISCLAIMER: This only applies to the first and second version of meteor-roles package.
// https://github.com/Meteor-Community-Packages/meteor-collection2/issues/399
// Add `roles` to your schema if you use the meteor-roles package.
// Option 1: Object type
// If you specify that type as Object, you must also specify the
// `Roles.GLOBAL_GROUP` group whenever you add a user to a role.
// Example:
// Roles.addUsersToRoles(userId, ["admin"], Roles.GLOBAL_GROUP);
// You can't mix and match adding with and without a group since
// you will fail validation in some cases.
roles: {
type: Object,
optional: true,
blackbox: true,
},
// Option 2: [String] type
// If you are sure you will never need to use role groups, then
// you can specify [String] as the type
roles: {
type: Array,
optional: true,
},
'roles.$': {
type: String,
},
// In order to avoid an 'Exception in setInterval callback' from Meteor
heartbeat: {
type: Date,
optional: true,
},
});
const someOtherSchema = new SimpleSchema({
useDocument: {
type: userSchema
},
});

How to get the username in the accounts-github package

I have one user in my app (myself) and am using the accounts-github package.
When I run Meteor.users.find({}).fetch() I see this:
[ { _id: 'fX7DZvFAe6KC9QvE8',
services: { resume: [Object] },
status: { online: true, lastLogin: [Object], idle: false } } ]
It would be great if this included a username. Anyone know how this is possible?
The problem was that elsewhere in my application I called Accounts.onCreateUser which overwrites the default function, part of which is setting the profile on the user.
To fix this, I added the following to my onCreateUser:
Object.assign user,
profile: options.profile || {}
See the comments here as well: https://github.com/meteor/docs/issues/81

Meteor - Validating new user document serverside

I'm having trouble with this seemingly trivial stuff, harrrr!
I have this user document:
userData = {
account: {
type: 'free'
},
profile: {
name: 'Artem',
},
username: 'aaa#gmail.com',
password: '123'
};
Which I'm sending client-side: Accounts.createUser(userData);
Then server side I want to check if account type equals 'free'. If it doesn't - I want to abort new user creation (and hopefully throw error client side)
There are 2 functions which I've found in the docs that presumably can help me do it:
Accounts.validateNewUser
Problem: it receives 'trimmed-down' user object which doesn't contain properties other than profile, username, password, email. Thus I cannot validate account.type as it doesn't exist on user object being validated.
Accounts.onCreateUser
Problem: it is called after a generic user object is created and there is no way I can cancel inserting new document in Users collection. It absolutely requires to return a user document. If I return undefined it throws errors on server:
Exception while invoking method 'createUser' Error: insert requires an argument
It also doesn't allow to throw method errors (as it's not a method) -> thus I cannot log error client side.
You can use Accounts.validateNewUser with little change to your data structure:
userData = {
profile: {
name: 'Artem',
account : {
type : 'free'
}
},
username: 'aaa#gmail.com',
password: '123'
};
Then you should be able to access data you need.
As far as I remember there were some discussion on meteor forum about removing profile field, that's why I'm solving this kind of problems in different way. For me Meteor.users is collection which should not be changed for sake of peace in mind - it could be changed by future version of meteor. My approach require to write more code in the beginning, but later it pays off, because you have place to store data about user and Meteor.users collection has docs with minimal amount of data.
I would use jagi:astronomy#0.12.1 to create schema and custom methods. In general I would create new collection UserAccounts with schema:
UserAccount = new Astro.Class( {
name: 'UserAccount',
collection: 'UserAccounts',
fields: {
'userId' : {type: 'string'},
'type' : {type: 'string', default:'free'}
},
} )
and add schema to Meteor.users :
User = new Astro.Class( {
name: 'User',
collection: Meteor.users,
fields: {
'services' : {type: 'object'},
'emails' : {type: 'array'}
},
methods:{
account : function(){
return UserAccounts.findOne({userId:this._id})
}
}
} )
The usage looks like this:
var user = Meteor.users.findOne();
user.account().type
In summary:
Accounts.onCreateUser : always allow to create user account and always create UserAccount which corresponds to it ( with field userId)

MDG ValidatedMethod with Aldeed Autoform: "_id is not allowed by the schema" error

I'm getting the error "_id is not allowed by the schema" when trying to use an autoform to update a collection via a ValidatedMethod.
As far as I can see from this example and the official docs there is no expectation for my schema to include the _id field, and I wouldn't expect to be updating the id from an update statement, so I have no idea why this error is happening.
If I switch from using the validated method to writing directly to the collection (with a schema attached to the collection that doesn't have the id in) everything works as expected, so I'm assuming the issue is with my the validate in my ValidatedMethod.
Any idea what I'm doing wrong?
Template: customer-edit.html
<template name="updateCustomerEdit">
{{> quickForm
collection="CustomerCompaniesGlobal"
doc=someDoc
id="updateCustomerEdit"
type="method-update"
meteormethod="CustomerCompanies.methods.update"
singleMethodArgument=true
}}
</template>
Template 'code behind': customer-edit.js
Template.updateCustomerEdit.helpers({
someDoc() {
const customerId = () => FlowRouter.getParam('_id');
const instance = Template.instance();
instance.subscribe('CustomerCompany.get', customerId());
const company = CustomerCompanies.findOne({_id: customerId()});
return company;
}
});
Update Validated Method:
// The update method
update = new ValidatedMethod({
// register the name
name: 'CustomerCompanies.methods.update',
// register a method for validation, what's going on here?
validate: new SimpleSchema({}).validator(),
// the actual database updating part validate has already been run at this point
run( newCustomer) {
console.log("method: update");
return CustomerCompanies.update(newCustomer);
}
});
Schema:
Schemas = {};
Schemas.CustomerCompaniesSchema = new SimpleSchema({
name: {
type: String,
max: 100,
optional: false
},
email: {
type: String,
max: 100,
regEx: SimpleSchema.RegEx.Email,
optional: true
},
postcode: {
type: String,
max: 10,
optional: true
},
createdAt: {
type: Date,
optional: false
}
});
Collection:
class customerCompanyCollection extends Mongo.Collection {};
// Make it available to the rest of the app
CustomerCompanies = new customerCompanyCollection("Companies");
CustomerCompaniesGlobal = CustomerCompanies;
// Deny all client-side updates since we will be using methods to manage this collection
CustomerCompanies.deny({
insert() { return true; },
update() { return true; },
remove() { return true; }
});
// Define the expected Schema for data going into and coming out of the database
//CustomerCompanies.schema = Schemas.CustomerCompaniesSchema
// Bolt that schema onto the collection
CustomerCompanies.attachSchema(Schemas.CustomerCompaniesSchema);
I finally got to the bottom of this. The issue is that autoform passes in a composite object that represents the id of the record to be changed and also a modifier ($set) of the data, rather than just the data itself. So the structure of that object is along the lines of:
_id: '5TTbSkfzawwuHGLhy',
modifier:
{
'$set':
{ name: 'Smiths Fabrication Ltd',
email: 'info#smithsfab.com',
postcode: 'OX10 4RT',
createdAt: Wed Jan 27 2016 00:00:00 GMT+0000 (GMT Standard Time)
}
}
Once I figured that out, I changed my update method to this and everything then worked as expected:
// Autoform specific update method that knows how to unpack the single
// object we get from autoform.
update = new ValidatedMethod({
// register the name
name: 'CustomerCompanies.methods.updateAutoForm',
// register a method for validation.
validate(autoformArgs) {
console.log(autoformArgs);
// Need to tell the schema that we are passing in a mongo modifier rather than just the data.
Schemas.CustomerCompaniesSchema.validate(autoformArgs.modifier , {modifier: true});
},
// the actual database updating part
// validate has already been run at this point
run(autoformArgs)
{
return CustomerCompanies.update(autoformArgs._id, autoformArgs.modifier);
}
});
Excellent. Your post helped me out when I was struggling to find any other information on the topic.
To build on your answer, if for some reason you want to get the form data as a single block you can use the following in AutoForm.
type="method" meteormethod="myValidatedMethodName"
Your validated method then might look something like this:
export const myValidatedMethodName = new ValidatedMethod({
name: 'Users.methods.create',
validate(insertDoc) {
Schemas.NewUser.validate(insertDoc);
},
run(insertDoc) {
return Collections.Users.createUser(insertDoc);
}
});
NB: The Schema.validate() method then requires an Object, not the modifier as before.
I'm unclear if there are any clear advantages to either method in general.
The type="method-update" is obviously the way you want to go for updating documents because you get the modifier. The type="method" seems to be the best way to go for creating a new document. It would likely also be the best option in most cases where you're not intending to create a document from the form data.

Meteor user has no email address

Using simple schema and accounts-password. I'm trying to add in an initial account on start-up, but the email and password are not appearing.
Schemas.User = new SimpleSchema({
username: {
type: String,
regEx: /^[a-z0-9A-Z_]{3,15}$/
},
emails: {
type: [Object],
optional: true
},
"emails.$.address": {
type: String,
regEx: SimpleSchema.RegEx.Email
},
"emails.$.verified": {
type: Boolean
},
profile: {
type: Schemas.UserProfile,
optional: true
}
});
and
Meteor.startup(function () {
Meteor.users.remove({});
if (Meteor.users.find().count() == 0) {
Accounts.createUser({
username: "newuser",
emails: [{address:"test#test.com", verified:true}],
password:"mypassword"
});
}
console.log(Meteor.users.find().fetch());
}
Gives us:
[{_id: 'xxx', username:'newuser'}]
No email or password. No errors. Thoughts?
New users in this system can only be added by existing users, so I haven't been able to test the user submission form.
Accounts.createUser takes a String as an email property for the options parameter. As for the password problem, it is maybe due to the lack of a services property in your schema. Add to your Schemas.User the following property:
Schemas.User = new SimpleSchema({
// ...
services: {
type: Object,
optional: true,
blackbox: true
}
}
Finally, the Accounts.createUser documentation (see first link) states:
On the client, you must pass password and at least one of username or email — enough information for the user to be able to log in again later. On the server, you do not need to specify password, but the user will not be able to log in until it has a password (eg, set with Accounts.setPassword).
It seems to not apply in your case, but as a last resort, try to call Accounts.setPassword(userId, "mypassword") afterwards. The user's id is returned by Meteor.createUser.

Resources