confirming if an email already exists in a MongoDB database - javascript

I wrote this code to check if an email already exists in the database:
async store (req,res) {
const email = req.body.email;
let user = await User.findOne ({ email: email });
if (user) {
console.log('Already exist.')
};
(...)
}
But it's not working: I can store the info in the User collection but it's email is not verified.
I'm using Mongoose.
What I'm doing wrong?

You need to use exec() at the end to actually run the query:
let user = await User.findOne({ email: email }).exec();
Also, since you're using await, make sure the containing function is marked async.
I am limited in the information I can give you because you just say "It's not working". That doesn't tell me anything. Do you run it and nothing happens? Does it give you an error? People on this site don't like to hear the words: "it's not working".

You haven't described your use case, but if you're looking to avoid email collisions, using mongoose, when you define the object's schema, you can use the unique: true option. It will then reject any new or updated User that submits an already stored email.

Related

How to use an action code and then get the current user with firebase?

I am designing 2 pages for a user signing up. The first page is where the user enters their email only. I then perform this code.
await createUserWithEmailAndPassword(auth, email.value, bcrypt.hashSync(email.value, 6))
.then(async (userCredential) => {
sendEmailVerification(userCredential.user)
loading = false
navigate('/verifyEmail')
})
.catch((error) => {
log.error(`Error registering user: ${error}`)
errorMessage = error.message
isEmailInvalid = true
loading = false
})
This sends the user a verification email, which they then click on to set their password and name:
let oobCode = ''
oobCode = window.location.href.split('oobCode=')[1].split('&')[0]
const email = window.location.href.split('email=')[1].split('/')[0]
let user = auth.currentUser
await applyActionCode(auth, oobCode)
.then(async (result) => {
console.log(auth.currentUser)
Promise.all([
updateProfile(auth.currentUser, {displayName: firstName + ' ' + lastName}),
updatePassword(auth.currentUser, password),
])
console.log('Welcome', firstName, lastName)
await setUser('local', undefined, auth.currentUser)
})
However at this point, auth.currentUser will be null if the user has clicked on this link on a different browser. A quick workaround would be to create a user with password 'password' and then sign them in after applying the action code. However this has a big security flaw obviously, my current idea just encrypts their email as a temporary password in hopes they cannot guess it and sign in.
I guess my question is, how do I update the user upon applying an action code? If I can't do this what flow of operations should I change?
My question is, how do I update the user upon applying an action code?
If the user is using another browser it is not possible since he/she does not know the password.
If I can't do this what flow of operations should I change?
IMHO you are overcomplexifying the onboarding process. The common approach is to create the account with the password being chosen by the user (which, in your case, should happen in the first screen) and send the email for verification.
In parallel you deny access to the Firebase back-ends (DBs, Cloud Storage, etc.) to users with non verified email via the Security Rules.
Upon email verification you sign in the user:
If it is from the same browser the users is actually already signed in (side effect of the use of createUserWithEmailAndPassword()
If it is in a different browser the user just has to enter his email and password (which he/she knows)

Node Js Checking if user email is already exits

Hi New Here and learning node js with express i want a way to check if the user email is
already exits in database i am trying to do this like this
const emailExits = user.findOne({ email: req.body.email });
if(emailExits) return res.status(400).send('Email already exits');
but every time i type any email that is not in database just tell email already exit how ever
the email is never stored in database
if you have any good way to do this please tell what is wrong
.findOne() is asynchronouse, you need to put an .then() at the end, use a callback or use async / await
try {
const emailExits = await user.findOne({ email: req.body.email });
if(emailExits) return res.status(400).send('Email already exits');
}catch(err){
console.log(err);
}
Dont forget to put async infront of your handler function
user.findOne(...) is an asynchronous operation, your code tries to access emailExist variable before the value is assigned to it, thus returning undefined. There are few ways to handle async code, i.e.
return user.findOne({ email: req.body.email })
.then(email => {
if(user) return res.status(400).send('Email already exits');
//do something if user does not exist
return ...
})
.catch(err=> new Error(err))
Keep in mind you need to return each value though

Quickblox: Change password of other user in Javascript

I'm doing a javascript app with Quickblox and I'm having one problem. I want to have a recover user password function and I have thought that an special user could change another one password. For that I'm using this:
var params = {password: newPassword, old_password: oldPassword };
QB.users.update(userId, params, function (error, response) {
//...
});
The function only works if I use the same userId of the user connected. I know that there is a forgot password function that is sending mails in Quickblox, however, I would like to not send any mail. What I can do? How can I use QB.users.update properly?
Lot of thanks in advance and best regards
You can't change a password of another users, only yours.
You can try to use admin account's credentials to change other user's password

Parse - why does user.getSessionToken() return undefined

I'm using cloud function to fetch user's sessionToken. The documentation says, this method only returns correct value when a user object is fetched with the master key. However, even if I use the master key, I still get the undefined result. What's wrong with my code?
Parse.Cloud.define("hello", function(request, response) {
Parse.Cloud.useMasterKey();
Parse.Promise.as().then(function(){
var query = new Parse.Query(Parse.User);
return query.first({useMasterKey:true});
}).then(function(user){
return user.fetch({useMasterKey:true});
}).then(function(user){
response.success(user.getSessionToken());
});
});
That won't work because the user is not logged in when you fetch him via cloud code. For getSessionToken to work you need to already have a logged in user. Because, otherwise how would CloudCode know which session of your user you want to get? (if he is logged in multiple devices) Also your code is returning the first user in the database, is that realy what you want?
Either way, you need to log the user in via cloud code and then return the session token. However I had some trouble doing that without the password (just by calling user.logIn(), it should work so give it a try) so the only solution I found was to change the password of the user and then log him in. Why do you need to fetch the user's session token? If you don't mind changing the user's password you can do something like:
var password; //create new random passowrd
query.first({useMasterKey: true}).then(function(user){
user.set("password", password);
return user.save();
}).then(function(user){
return Parse.User.logIn(user.get("username"), password);
}).then(function(user){
return user.getSessionToken();
});

how to store signup data into redis with node.js

i want to store signup data it contains name and email and password.
i will store this data in mongodb like this
db.save({"name":"xxxx","email":"xxxxx","password":'xxxxxxxx'},function(err,result){});
when user login ,they surely give their email id or username with password so i will find this user exist in db or not by using like this
db.find({'email:'xxxxxxx','password':'xxxxxxxxx'},function(err,result){});
i have tried to do same in redis,by like this
db.hmset('key' name xxxxx email xxxx pass xxxxxx,function(){});
it is stored but how can i check email id usename already exist becz user will give email and password only.if i know key then only i can find that data.even if i know key i can get only data i could not be found data already exist ot not like mongodb
how can i solve this?
You could store your users both in a Set and a Hash for details.
You can then check in the Set if a user exists with: http://redis.io/commands/sismember
I think you should break things down into chunks instead of trying to do everything with one query. So, for example, to add a new user, first check if the user exists:
(My example assumes a Mongoose User Model has been defined)
User.findOne({$or : [{'email': req.body.email}, {'username': req.body.username}],
function(err, result) {
if (err) {next(err);}
if (result) {
// you found an existing user
res.send(309, {'message':'Error: User exists'});
} else {
// no user found
var user = new User({
'email': req.body.email,
'username': req.body.username,
'password': req.body.password,
'and-so-on': req.body.moredata
});
user.save(function(err){
if (err) {next(err);}
res.send(200, {'message':'User Registered Successfully'});
});
}
Honestly though, I wouldn't recommend writing a user authentication system from scratch, because it is pretty limiting in todays world of auth methods. I personally use Passport, because it gives you the ability to use multiple auth systems with your app, including Facebook, Twitter, and so on and so forth.

Categories

Resources