So I am trying to hide the password object from showing. Here's my code, I am using bcrypt to ash the password. I am hiding the return objectBut I am not getting my expected results. What am I doing wrong, please help. Greatly appreciate it.
Thanks.
var express = require('express')
var router = express.Router()
var User = require('../Models/User.js')
var bcrypt = require('bcrypt')
router.get('/:resource', function(req, res, next){
var resource = req.params.resource
if (resource == 'user'){
User.find(null, function(err, users){
if(err) {
res.json({
confimration: 'error',
message: err
})
return
}
res.json({
confimration: 'success',
message: users
})
return
})
}
})
router.post('/:resource', function(req, res, next){
var resource = req.params.resource
var data = req.body
var password = data.password
var hashed = bcrypt.hashSync(password, 10)
data['password'] = hashed
if(resource == "user") {
User.create(data, function(err, user){
if(err){
res.json({
confirmation: 'fail',
message: err
})
return
}
res.json({
confirmation: 'success',
result: user
})
return
})
}
})
module.exports = router
var mongoose = require('mongoose')
var UserSchema = new mongoose.Schema({
firstName: {type: String, lowercase: true, trim: true, default: ''},
lastName: {type: String, lowercase: true, trim: true, default: ''},
email: {type: String, lowercase: true, trim: true, default: ''},
city: {type: String, default: ''},
password: {type: String, default: ''},
timestamp: {type:Date, default: Date.now}
})
UserSchema.methods.summary = function() {
var summary = {
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
timestamp: this.timestamp,
id: this._id,
city: this.city
}
return summary
}
module.exports = mongoose.model('UserSchema', UserSchema)
{
_id: "57f460235805b52762605df2",
__v: 0,
timestamp: "2016-10-05T02:06:27.829Z",
password: "$2a$10$DIHrMO8WcRmOkIVj93SSQ.LFe5vPYH6R3xrfsSuql.v2jfU2mcO.C",
city: "new york",
email: "4",
lastName: "4",
firstName: "4"
}
for the router.get you could use a projection field. I don't know why you have null. but this find searches for all the docs in users collection and excludes the password field for each doc returned. does this help with the router.get?
if (resource == 'user'){
User.find({},{password: 0}, function(err, users){
if(err) {
res.json({
confimration: 'error',
message: err
})
return
}
res.json({
confimration: 'success',
message: users
})
return
})
}
Related
I'm learning the MERN stack and trying to create an authentication, but now I have a problem, whenever I'm trying to register, I have an error 'TypeError: User.create is not a function'.
I think that I have a problem with user model or export. Please help
INDEX.JS
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const dotenv = require("dotenv");
const app = express();
const User = require("./models/User");
dotenv.config({ path: "./.env" });
app.use(express.json());
app.use(cors());
mongoose.connect(process.env.MBD_CONNECT, { useNewUrlParser: true }, (err) => {
if (err) return console.error(err);
console.log("Connected to MongoDB");
});
app.post("/api/registr", async (req, res) => {
console.log(req.body);
try {
const user = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password,
});
res.json({ status: "ok" });
} catch (err) {
console.log(err);
res.json({ status: "error", error: "Duplicate email" });
}
});
app.post("/api/login", async (req, res) => {
const user = await User.findOne({
email: req.body.email,
password: req.body.password,
});
if (user) {
return res.json({ status: "ok", user: true });
} else {
return res.json({ status: "error", user: false });
}
});
app.listen(3001, () => {
console.log("SERVER RUNS PERFECTLY!");
});
USER.JS (MODEL)
const mongoose = require("mongoose");
const User = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
const model = mongoose.model("UserData", User);
module.exports = User;
You're exporting the schema, not the model. create is a method of mongoose Model class, see document here.
const model = mongoose.model("UserData", User);
module.exports = User; // <------ problem here
It should be:
const model = mongoose.model("UserData", User);
module.exports = model;
Your model file please update with the following code snip
const mongoose = require("mongoose");
const User = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
}, { collection : 'UserData'});
const model = mongoose.model("UserData", User);
module.exports = User;
I am going through the full stack developer certification and creating an authentication app from devChallenges.io and I want the user to able to edit their profile and pass in the new profile image as well as their name, bio, phone number and password in the form data however, I get the error Missing required parameter - public_id. Here is my code below.
// #route POST /profile/edit/:id
// #desc edit profile
// #access Private
app.put('/profile/edit/:id', upload.single('image'), auth, async (req, res) => {
const { name, bio, phone, password } = req.body;
try {
let user = await AuthUser.findById(req.params.id);
// Delete image from cloudinary
await cloudinary.uploader.destroy(user.cloudinary_id);
// Upload image to cloudinary
let result;
if (req.file) {
result = await cloudinary.uploader.upload(req.file.path);
}
const data = {
name: name || user.name,
avatar: result.secure_url || user.avatar,
bio: bio || user.bio,
phone: phone || user.phone,
password: password || user.password,
cloudinary_id: result.public_id || user.cloudinary_id,
};
// Encrypt password
const salt = await bcrypt.genSalt(10);
data.password = await bcrypt.hash(password, salt);
// Update
user = await User.findByIdAndUpdate(req.params.id, data, { new: true });
return res.json(user);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
models/user.js
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
default: '',
},
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
avatar: {
type: String,
},
bio: {
type: String,
default: '',
},
phone: {
type: String,
default: '',
},
cloudinary_id: {
type: String,
},
});
module.exports = AuthUser = mongoose.model('AuthUser', UserSchema);
I've been working on a Nodejs+Express+Mongoose API that handles user registration/login, everything works perfectly when a user signs up, but when the user wants to login it says it can't find the user. Let me show you the code:
module.exports.registerUser = (req, res) => {
var user = new User();
user.email = req.body.email;
user.name = req.body.name;
user.setPassword(req.body.password);
user.save((err) => {
var token;
token = user.generateJwt();
res.status(200);
res.json({
'token': token,
'user': user,
});
});
};
When I register (I'm testing this with Postman) I get this message, showing everything it's OK:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0ODg1MDcwNjUsImlhdCI6MTQ4ODQyMDY2NX0.GD0NehQ1EYEnOKx2OJWALpkHB8u5N_9Zjm1dcuEdl7I",
"user": {
"__v": 0,
"name": "Stack Overflow",
"email": "stackoverflow#stackoverflow.com",
"_id": "58b77f39cf5e8d5f3ffdb4ff"
}
}
The password gets hashed, that's why the JSON doesn't contain it.
And this is the code for user login:
module.exports.loginUser = (req, res) => {
var password = req.body.password;
var email = req.body.email;
User.findOne({'email': email}, (err, user) => {
if (err) {
res.status(500).json(err);
}
if (user) {
if (!user.validPassword(password)) {
res.status(401).send({
message: 'Wrong password.'
});
} else {
token = user.generateJwt();
res.status(200);
res.json({
'token': token,
'user': user
});
}
} else {
res.status(404).send({
message: 'No user was found.'
});
}
});
}
But every time I hit the login button on postman with the same password and email, I get this:
{
"message": "No user was found."
}
And this is the user schema:
'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret');
var userSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true
},
age: {
type: Number,
required: false
},
schoolID: {
type: String,
required: false,
unique: false
},
university: {
type: String,
required: false
},
area: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Area'
},
project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Project'
},
hash: String,
salt: String
});
userSchema.methods.setPassword = (password) => {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
};
userSchema.methods.validPassword = (password) => {
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
return this.hash === hash;
};
userSchema.methods.generateJwt = () => {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 1);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000),
}, secret.secret);
};
var User = mongoose.model('User', userSchema);
module.exports = User;
I can't find the solution to this problem, because the way I see it, everything should be working just nice. Any ideas on why this isn't working?
Update:
This is for checking the email is being sent correctly:
{
"message": "No user was found. User: stackoverflow#stackoverflow.com password: stackoverflow"
}
hi I wanna see on the screen User all information but I cannot add user in mongodb . User's location information in Locations Schema.But I dont know how to get location information(i.e city,town...) to input UserSchema.This is my codes:
User Schema :
var userSchema = Mongoose.Schema({
name:{type: String,require:true},
surname: {type: String,require:true},
tel: {type: String,require:true},
age: {type: String,require:true},
mevki_id: {type: String,require:true},
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
});
Create User Function :
this.createUser = function (req, res, next) {
var lok=new Location({il:req.params.il,ilce:req.params.ilce});
lok.save(function(err){
var user=new User({name:req.params.name,surname:req.params.surname,tel:req.params.tel,age:req.params.age,mevki_id:req.params.mevki_id,location_id:user});
user.save(function(err){
user.location_id=lok;
});
return res.send({})
});
}
Thnks :)
//define this as your schema in your file
var userSchema = new Schema({
name: {type: String, required: true},
surname: {type: String, required: true},
tel: {type: Number, required: true},
age: {type: Number, required: true},
mevki_id: {type: String, required: true},
location_id:{type:String,required:true}
});
var CollectionModel_user = conn.model('users', userSchema)
return function (req, res, next) {
req.Collection_user = CollectionModel_user;
next();
}
// create a route which can create a route in your
// app.js or main.js file that will create a new
// collection in your mongo.
router.all('/user/create', function (req, res) {
var create = req.Collection_user;
var name = req.body.name;
var surname = req.body.surname;
var tel = req.body.tel;
var age = req.body.age;
var mevki_id = req.body.mevki_id;
var location_id = req.body.location_id;
var record = new create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
location_id: location_id
});
if (name.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});
I am unsure as to why I am getting an error for POST-ing a form. I am using mongoose to connect to mongodb and using Jade as my view engine. I am trying to POST an update and not a new account into the db, and using a cookie to pull the user's info. So it is the Edit User Profile page. Everything works on the Jade file and looks right, just when I hit the submit button it goes to a:
Cannot POST /editUserProfile
My mongoose User file:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt-nodejs'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
email: { type: String, required: true, lowercase:true, index: { unique: true } },
password: { type: String, required: true },
firstName: {type: String, required: true},
lastName: {type: String, required: true},
phone: {type: Number, required: true},
birthday: {type: Date, required: true}
});
UserSchema.pre('save', function(next) {
var user = this;
console.log("email exists");
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
My route file:
exports.editUserProfile = function(req, res) {
User.findById(req.signedCookies.userid, function(err,user) {
if(err) {
res.send(err);
} else {
console.log(JSON.stringify(user));
res.render('editUserProfile', {title: 'Weblio',
ufirstName: user.firstName,
ulastName: user.lastName,
uemail: user.email,
uphone: user.phone,
ubirthday: user.birthday
});
//, user: user.firstName, - taken out after title
}
});
};
exports.editUserProfilePost = function(req, res) {
var updateUser = new User ({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone,
birthday: new Date(req.body.birthday)
});
updateUser.save(function(err){
console.log("here 3");
if(!err) {
console.log("here3a");
res.render('userProfile', {title: 'Weblio'});
} else {
console.log("here 1a");
(new Error('Incorrect POST'));
return res.render('editUserProfileError', {title: 'Weblio'});
}
});
};
Jade file:
extends layout
block content
div.centerContent
form.validateForm(method="POST", action="/editUserProfile")
legend Edit Profile
input(type="text", name="firstName", maxlength="20", placeholder=ufirstName, value=ufirstName)
br
input(type="text", name="lastName", maxlength="20", placeholder=ulastName, value=ulastName)
br
input(type="email", name="email", maxlength="20", placeholder=uemail, value=uemail)
br
input(type="number", name="phone", maxlength="20", placeholder=uphone, value=uphone)
br
input(type="date", name="birthday", placeholder=ubirthday, value=ubirthday)
br
input.btn.btn-primary(type="submit", name="Update", value="Save")
a(href="/userProfile")
button.btn(type="button") Cancel
This is my app.js file: I have a bunch of other things in there but the Register part is getting POST-ed so I don't think the app.js has any problems.
app.get('/editUserProfile', user.editUserProfile);
app.post('/editUserProfile', user.editUserProfilePost);
Updated:
exports.editUserProfilePost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid,{
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone,
birthday: new Date(req.body.birthday)
}, function(err) {
if(!err) {
console.log("post2");
res.render('userProfile', {title: 'Weblio'});
} else {
console.log("post3");
(new Error('Incorrect POST'));
return res.render('editUserProfileError', {title: 'Weblio'});
}
});
};