Getting [object, Object] instead of whole user data. What does that mean? - javascript

I am getting the [object,Object ] in my server terminal instead of whole user data . I do not know what does that mean... I think I did all perfectly but still unable to get the whole data. I specified of sailjs server.
How to get whole user data instead of [object,Object]?
module.exports = {
/**
* Check the provided email address and password, and if they
* match a real user in the database, sign in to Medool.
*/
login: function (req, res) {
// Try to look up user using the provided email address
User.findOne({
email: req.param('email')
}, function foundUser(err, user) {
if (err)
return res.negotiate(err);
if (!user)
return res.notFound();
// Compare password attempt from the form params to the encrypted password
// from the database (`user.password`)
require('machinepack-passwords').checkPassword({
passwordAttempt: req.param('password'),
encryptedPassword: user.encryptedPassword
}).exec({
error: function (err) {
return res.negotiate(err);
},
/*
If the password from the form params doesn't checkout w/ the encrypted
password from the database...
*/
incorrect: function () {
return res.notFound();
},
success: function () {
// Store user id in the user session
console.log("User form the login check" +user)
req.session.me = user.helpsterId;
console.log(req.session.me);
// All done- let the client know that everything worked.
return res.ok();
}
});
});
}
};
Output when lifted server is [object, Object]in console

Try it,
console.log(user);
console.log(JSON.stringify(user));
console.log("User form the login check" +user);
and write the result for us.

Related

Firebase Sign Up with username. Cliend Side + Security Rules or Backend?

I have implemented a Firebase SignUp with username, email and password. Basically what I am doing is:
1- Create user with email and password (if the username and email are not used by other users)
2- Add the username to the user
Like this:
firebase
.createUserWithEmailAndPassword(email, password)
.then((currentUser) => {
// Get the username from the input
const username = this.usernameInput.current.getText();
// Create a user with this username and the current user uid in the db
firebase.createUserWithUsername(username, currentUser.user.uid); // <----------
})
.catch((err) => {
// ...
});
And my createUserWithUsername function basically do this:
createUserWithUsername = (username, userId) => {
/*
Create a document in the usernames collection
which uid (of the document itself, not a field) is the given username.
*/
// Pass username to lowercase
username = username.toLowerCase();
// Initial user's data
const data = {
email: this.auth.currentUser.email,
username,
};
return this.db
.collection("usernames")
.doc(username)
.set({ userId })
.then(() => {
this.db.collection("users").doc(userId).set(data);
})
.catch((err) => {
console.log(err);
throw err;
});
/*
Pd: As firestore automatically removes empty documents, we have to
assign them a field. The user's id is a good option, because it will help us to
update usernames faster, acting like a 'Foreign Key' in a NoSql DB.
*/
};
My question is? Is it wrong to leave this code on the client side? Can it be a security problem? Do I need to move this to a cloud function / backend?
This is my firestore security rule for the usernames collection:
match /usernames/{username} {
function isUsernameAvailable() {
return !exists(/databases/$(database)/documents/usernames/$(username));
}
allow read: if true;
allow write, update: if isSignedIn() && isUsernameAvailable();
// TODO - Allow delete?
}
I would really appreciate any guide for this. Thank you.

How can I solve alert reference errors in Javascript?

I got this error
"type error alert is not a function ".
So I created an alert function but got this error
reference error alert is not defined
when I try to execute its function
function alertMessage(messageObject) {
alert(messageObject);
return true;
}
app.post("/login", function(req, res) {
const username = req.body.username;
const password = req.body.password
User.findOne({
email: username
},
function(err, foundUser) {
if (foundUser) {
if (foundUser.password !== password) {
alertMessage("Password Is Incorrect");
} else {
if (foundUser) {
if (foundUser.password === password) {
res.render("compose");
}
}
};
};
});
});
From app.post, I'm guessing this is code running in Node.js via Express.js. Node.js doesn't have an alert function, that's something browsers provide. In app.post you're replying to a response from the browser. If there's a login error, you need to send a reply to the post saying there's a login error. It looks like your code is expecting to present a page in response to the post (rather than being called via ajax), so you'd render a page saying the login failed. (You might consider using ajax instead, so the page doesn't have to refresh in this case, but that's beside the point.)

how can i set accounts state as logged-In in meteor?

I'm using custom LDAP verification method to autenticate users for my application. What I have done is , i have users collection where i will first find the userId and if its true i will then call "ldapLogin" method which will authenticate users with LDAP server. Then i want to make the status of Meteor accounts as logged-In for the userId.
login.js
Template.login.events({
'click #loginbtn': function (e) {
username = $('.ui.form').find('#loginform_username').val();
password = $('.ui.form').find('#loginform_password').val();
var dn=<DN info>;
var sys_password=<password>;
if( username!="" || password!=""){
var count=Meteor.users.find({username:username}).count(); //check for users already exist or not
if(count==1){
Meteor.call('loginLdap',dn,username,sys_password,function (error, result) {
if (error)
console.log(error.reason);
Session.set('userLogin',result);
});
var employeeLogin=Session.get('userLogin');
if(employeeLogin){
/*
*how to change the login status with only passing username
*/
}
}else alert("User not found!\n Please check your username or contact your Manager.");
}else alert("Username/Password field can not be empty!");
As i have verified password i want the login to be carried only passing username. Is this possible to do in Meteor Accounts package?
You can login users using a Meteor.call with just the userId. On the server, I do the following:
Meteor.methods({
'landingLogin'(userId) {
const stampedLoginToken = Accounts._generateStampedLoginToken();
Accounts._insertLoginToken(userId, stampedLoginToken);
return stampedLoginToken;
}
});
Then on the client:
Meteor.call('landingLogin', userId, (error, result) => {
if (error) {
} else {
Meteor.loginWithToken(result.token);
};
});

Parse Server / JS SDK, error 206 when saving a user object

I am having trouble using the Parse Server JS SDK to edit and save a user.
I am signing in, logging in and retrieving the user just fine, I can call without exception user.set and add/edit any field I want, but when I try to save, even when using the masterKey, I get Error 206: Can t modify user <id>.
I also have tried to use save to direcly set the fields, same result.
A interesting thing is that in the DB, the User's Schema get updated with the new fields and types.
Here is my update function:
function login(user, callback) {
let username = user.email,
password = user.password;
Parse.User.logIn(username, password).then(
(user) => {
if(!user) {
callback('No user found');
} else {
callback(null, user);
}
},
(error) => {
callback(error.message, null);
}
);
}
function update(user, callback) {
login(user, (error, user) => {
if(error) {
callback('Can t find user');
} else {
console.log('save');
console.log('Session token: ' + user.getSessionToken());
console.log('Master key: ' + Parse.masterKey);
user.set('user', 'set');
user.save({key: 'test'}, {useMasterKey: true}).then(
(test) => {
console.log('OK - ' + test);
callback();
}, (err) => {
console.log('ERR - ' + require('util').inspect(err));
callback(error.message);
}
);
}
});
}
And a exemple of the error:
update
save
Session token: r:c29b35a48d144f146838638f6cbed091
Master key: <my master key>
ERR- ParseError { code: 206, message: 'cannot modify user NPubttVAYv' }
How can I save correctly my edited user?
I had the exact same problem when using Parse Server with migrated data from an existing app.
The app was created before March 2015 when the new Enhanced Sessions was introduced. The app was still using legacy session tokens and the migration to the new revocable sessions system was never made. Parse Server requires revocable sessions tokens and will fail when encountering legacy session tokens.
In the app settings panel, the Require revocable sessions setting was not enabled before the migration and users sessions were not migrated to the new system when switching to Parse Server. The result when trying to edit a user was a 400 Bad Request with the message cannot modify user xxxxx (Code: 206).
To fix the issue, I followed the Session Migration Tutorial provided by Parse which explain how to upgrade from legacy session tokens to revocable sessions. Multiple methods are described depending on your needs like enableRevocableSession() to enable these sessions on a mobile app, if you're only having a web app, you can enforce that any API requests with a legacy session token to return an invalid session token error, etc.
You should also check if you're handling invalid session token error correctly during the migration to prompt the user to login again and therefore obtain a new session token.
I had the same error and neither useMasterKey nor sessionToken worked for me either. :(
Here's my code:
console.log("### attempt 1 sessionToken: " + request.user.getSessionToken());
var p1 = plan.save();
var p2 = request.user.save(null, {sessionToken: request.user.getSessionToken()});
return Parse.Promise.when([p1, p2]).then(function(savedPlan) {
...
}
I see the matching session token in log output:
2016-08-21T00:19:03.318662+00:00 app[web.1]: ### attempt 1 sessionToken: r:506deaeecf8a0299c9a4678ccac47126
my user object has the correct ACL values:
"ACL":{"*":{"read":true},"PC7AuAVDLY":{"read":true,"write":true}}
I also see a bunch of beforeSave and afterSave logs with user being "undefined". not sure whether that's related.
beforeSave triggered for _User for user undefined:
I'm running latest parser-server version 2.2.18 on Heroku (tried it on AWS and results are the same)
function login(logInfo, callback) {
let username = logInfo.email,
password = logInfo.password;
Parse.User.logIn(username, password).then(
(user) => {
if(!user) {
callback('No user found');
} else {
callback(null, user);
}
},
(error) => {
callback(error.message, null);
}
);
}
function update(userInfo, data, callback) {
login(userInfo, (error, user) => {
if(error) {
callback('Can t find user');
} else {
getUpdatedData(user.get('data'), data, (error, updateData) => {
if(error) {
callback(error);
} else {
user.save({data: updateData}, /*{useMasterKey: true}*/ {sessionToken: user.get("sessionToken")}).then(
(test) => {
callback();
}, (err) => {
callback(error.message);
}
);
}
});
}
});
}
For some reason, retrying to use sessionToken worked.
This is not how asynchronous functions work in JavaScript. When createUser returns, the user has not yet been created. Calling user.save kicks off the save process, but it isn't finished until the success or error callback has been executed. You should have createUser take another callback as an argument, and call it from the user.save success callback.
Also, you can't create a user with save. You need to use Parse.User.signUp.
The function returns long before success or error is called.

Meteor: check email does not exist in Meteor.users collection before creating an account

I have a form where users enter their email address and password into a join form. This creates the account but I now want to develop it further.
client.js:
Template.joinForm.events({
'submit .form-join': function(e, t) {
e.preventDefault();
var email = t.find('#email').value,
password = t.find('#password').value,
username = Random.id(),
array = [],
profile = {
nameOfArray: array
};
Accounts.createUser({
email: email,
username: username,
password: password,
profile: profile
}, function(error) {
if (error) {
alert(error);
} else {
Router.go('/');
}
});
}
});
Before creating a user account, how do you:
Check if the email variable from the joinForm does not already exist in the Meteor.users collection. Processing this on the server?
If email does exist, then reject user creation?
I have seen the new function and wondering if I can use this http://docs.meteor.com/#/full/accounts_validatenewuser
Accounts.validateNewUser(function (user) {
// pseudo if statement code
if (email not exist) {
// 1. create the user account and then
Accounts.sendVerificationEmail(userId, [email])
} else {
throw new Meteor.Error(403, "email address is already registered");
}
});
Thank you for reading this.
I'm unclear as to whether to use Accounts.createUser or Accounts.onCreateUser and which code should be on the client, and which on the server. My aim is to build the account securely, therefore, deny any other modification privileges during this process from the console.
The extra empty array nameOfArrayis now created on the server if the account is allowed to be created, ie, passing the validateNewUser function. Of course, you can add more validation checks for example, password length.
client.js:
Template.joinForm.events({
'submit .form-join': function(e, t) {
e.preventDefault();
var email = t.find('#email').value,
password = t.find('#password').value,
username = Random.id();
Accounts.createUser({
email: email,
username: username,
password: password,
profile: profile
}, function(error) {
if (error) {
alert(error.reason);
} else {
Router.go('/');
}
});
}
});
server.js:
Accounts.onCreateUser(function(options, user) {
var newEmail = user.emails[0].address;
console.log(newEmail);
var emailAlreadyExist = Meteor.users
.find({"emails.address": newEmail}, {limit: 1})
.count() > 0;
console.log(emailAlreadyExist + ' already exists');
if (emailAlreadyExist === true) {
throw new Meteor.Error(403, "email already registered");
} else {
profile = options.profile;
profile.nameOfArray = [];
user.profile = profile;
return user;
}
});
I've found that Accounts.createUser has it's own validation built in and checks for already existing email/login.
Meteor docs: Accounts.createUser:
If there are existing users with a username or email only differing in
case, createUser will fail.
Thus Accounts.onCreateUser doesn't even fire if Accounts.createUser email/login validation throws error.
The Accounts.validateNewUser function requires users to validate their email after submitting. It's basically that step where, after you sign up for something, before you can sign in you have to enter a code that's sent to you on your email or mobile device -- basically, it ensures that the user is who they say they are. It's what might prevent you from signing up with the email totallyfake#totally_not_a_real_place.com.
If I'm reading your question right, you're more interested in seeing if an email is unique than in seeing if the user actually owns that email account. You can do this with Accounts.onCreateUser, which runs on the server:
Called whenever a new user is created. Return the new user object, or throw an Error to abort the creation.
The full process will look something like this. On the client, exactly what you have:
Template.joinForm.events({
'submit .form-join': function(e, t) {
e.preventDefault();
var email = t.find('#email').value,
password = t.find('#password').value,
username = Random.id(),
array = [],
profile = {
nameOfArray: array
};
Accounts.createUser({
email: email,
username: username,
password: password,
profile: profile
}, function(error) {
if (error) {
alert(error);
} else {
Router.go('/');
}
});
}
});
Then, on the server, before the user is actually created, it will run the user through your onCreateUser function, and whatever you return will be inserted into the users collection:
Accounts.onCreateUser(function(options, user) {
var email = user.emails[0];
if (!email) { throw new Meteor.Error("You must provide a non-empty email"); // this may actually not be necessary -- createUser might do it for you
if (Meteor.users.find({emails: email}) {
throw new Meteor.Error("A user with email " + email + " already exists!");
}
... // whatever other transformation you might want
return user;
});
You might also check out the accounts-ui package, since depending on how much you want to do vary from a vanilla implementation of user accounts, a lot may already be done for you.
The Accounts.validateNewUser is used to check if the fields of the user object comply with the desired format, returning true or false accordingly.
To check if the email is already registered, I think you should include this verification in the Accounts.onCreateUser function (http://docs.meteor.com/#/full/accounts_oncreateuser).
Without having tested the code, you can try something like this:
Accounts.validateNewUser(function (user) {
// Check compliance of the user object fields, using check http://docs.meteor.com/#/full/check
});
Accounts.onCreateUser(function(options, user) {
if (options.profile){
user.profile = options.profile;
}
if (Meteor.users.find({email: user.email}).fetch == 0) {
if(Accounts.validateNewUser(user)){
Accounts.sendVerificationEmail(userId, [email]);
return user;
} else {
throw new Meteor.Error(403, "Error checking user fields");
} else {
throw new Meteor.Error(403, "email address is already registered");
}
}

Categories