I just switched from parse to parse server with AWS and Mongolab. Currently I try to write some verifications to the cloud part in main.js in the server.
After adding the code below, which is a verification before saving to the class "posts". I want it to check if the username of the logged in user is equal to a specified value. However, after adding this I even con not login to my app with any of my users I used to log in. It says wrong password or username.
Parse.Cloud.beforeSave('posts', function (req, res) {
var uname = 'xxxxx';
var user = Parse.User.current();
user.fetch().then(function(fetchedUser){
uname = fetchedUser.getUsername();
},
);
if (uname != 'michael') {
res.error('This user is not allowed');
} else {
res.success();
}
});
I also use the cloud code below but it is working fine:
Parse.Cloud.beforeSave('tweets', function (req, res) {
if (req.object.get('name') != 'jeniffer') {
res.error('This user is not allowed');
} else {
res.success();
}
});
There are two main issues with the code. First, Parse.User.current() cannot be used with parse-server
and second, the promises syntax are a little wrong. Try this instead:
Parse.Cloud.beforeSave('posts', function (req, res) {
req.user.fetch().then(function(fetchedUser){
var uname = fetchedUser.getUsername();
if (uname !== 'michael') {
res.error('This user is not allowed');
} else {
res.success();
}
}, function(err) {
res.error(err);
});
});
Also, posts
sounds like a strange collection name. Should probably be Post
.