Here is my code for my index.js. Now I made an express server to be able to use /register for my creating an account. All the data that I insert into front end is coming over fine.
I'm able to connect and see rows if I use a different code. And it goes to my query database just fine and all the values are fine, but it returns invalid column name and the column name returning is saying it is invalid and is the stuff I input on the front end. So am I doing something wrong with the SQL query in the index? The table is already made. Any help on what I'm doing wrong.
Like if I put test on the username and register it returns Invalid column name 'test'
const express = require("express");
const cors = require("cors");
const app = express();
app.use(express.json({
type: ['application/json', 'text/plain']
}));
app.use(cors());
const { Connection, Request } = require("tedious");
// Create connection to database
const config = {
authentication: {
options: {
userName: "username", // update me
password: "password" // update me
},
type: "default"
},
server: "dragonfitness.database.windows.net", // update me
options: {
database: "dragonfitness", //update me
encrypt: true
}
};
const connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
console.log("Server Running and Connected")
}
});
app.post("/register", (req, res)=> {
const firstname = req.body.firstname;
const lastname = req.body.lastname;
const username = req.body.username;
const password = req.body.password;
const email = req.body.email;
queryDatabase(firstname, lastname, username, password, email);
})
connection.connect();
function queryDatabase(firstname, lastname, username, password, email ) {
console.log("testing");
var sql = "INSERT dbo.user_info(first_name, last_name, user_name, password, email) VALUES ("+firstname+", "+lastname+", "+username+", "+password+", "+email+")"
console.log('query========='+sql)
// Read all rows from table
const request = new Request(sql,
(err, result) => {
if (err) {
console.error(err.message);
} else {
console.log('worked');
}
}
);
connection.execSql(request);
}
app.listen(1433, () => {
console.log("running server");
});
Instead of concatenating string values in your sql commands, you should use Parametrized Queries.
See the following example:
function inputParameters() {
// Values contain variables idicated by '#' sign
const sql = `INSERT INTO ${table} (uniqueIdCol, intCol, nVarCharCol) VALUES (#uniqueIdVal, #intVal, #nVarCharVal)`;
const request = new Request(sql, (err, rowCount) => {
if (err) {
throw err;
}
console.log('rowCount: ', rowCount);
console.log('input parameters success!');
outputParameters();
});
// Setting values to the variables. Note: first argument matches name of variable above.
request.addParameter('uniqueIdVal', TYPES.UniqueIdentifier, 'ba46b824-487b-4e7d-8fb9-703acdf954e5');
request.addParameter('intVal', TYPES.Int, 435);
request.addParameter('nVarCharVal', TYPES.NVarChar, 'hello world');
connection.execSql(request);
}
Related
i am trying to create login register page with using PERN Stack and jwt
i have a database(vetmed) which consist of
CREATE TABLE veterinaryInfo(
vetId uuid PRIMARY KEY DEFAULT
uuid_generate_v4(),
vetName VARCHAR(30) NOT NULL,
vetSurname VARCHAR(30) NOT NULL,
branch_Name VARCHAR(50) NOT NULL,
address VARCHAR(100) NOT NULL ,
email VARCHAR(30) NOT NULL,
phone VARCHAR(11) NOT NULL,
password VARCHAR(255) NOT NULL);
Here is my jwt.Auth.js code:
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const pool = require('../db');
const validInfo = require('../middleware/validInfo');
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');
//authorizeentication
router.post('/register', validInfo, async (req, res) => {
try {
//1. destructure the req.body ( )
const { name, surname, branch, address_, mail, phone_, password_ } =
req.body;
// 2. check if user exist ( if exist then throw error)
const user = await pool.query(
'SELECT * FROM veterinaryInfo WHERE email = $1',
[mail]
);
//res.json(user.rows);
if (user.rows.length !== 0) {
// user already exist
return res.status(401).send('user already exist');
}
// 3. Bcrypty the user password
const saltRound = 10;
const salt = await bcrypt.genSalt(saltRound);
const bcryptPassword = await bcrypt.hash(password_, salt);
// 4. enter the new user inside the database
let newUser = await pool.query(
'INSERT INTO veterinaryInfo(vetName, vetSurname, branch_Name,address,email,phone,password) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *',
[name, surname, branch, address_, mail, phone_, bcryptPassword]
);
//res.json(newUser.rows[0]);
// 5 generating our jwt token
const token = jwtGenerator(newUser.rows[0].vetId);
res.json({ token });
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
});
//login route
router.post('/login', validInfo, async (req, res) => {
try {
// 1. destructure the req.body
const { name, surname, branch, address_, mail, phone_, password_ } =
req.body;
// 2. check if user doesn't exist (if not then throw error)
const user = await pool.query(
'SELECT * FROM veterinaryInfo WHERE email = $1',
[mail]
);
if (user.rows.length === 0) {
return res.status(401).json('Password or Email is incorrect');
}
// 3. check if incoming password is the same the database password
const validPassword = await bcrypt.compare(
password_,
user.rows[0].password
);
// console.log(validPassword);
if (!validPassword) {
return res.status(401).json('Password or Email is incorrect');
}
// 4. give them the twt token
const token = jwtGenerator(user.rows[0].vetId);
return res.json({ token });
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
router.get('/is-verify', authorization, async (req, res) => {
try {
res.json(true);
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
});
module.exports = router;
In postman i can create a new register successfully, i can use login and is-verify method succesfully. However,
Here is my dashboard.js code :
const router = require('express').Router();
const authorization = require('../middleware/authorization');
const pool = require('../db');
router.get('/', authorization, async (req, res) => {
try {
const user = await pool.query(
'SELECT * FROM veterinaryInfo WHERE vetId = $1',
[req.user]
);
//res.json(user.rows[0]);
// res.json('hello');
res.json(user.rows[0]);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
module.exports = router;
In postman with http://localhost:5000/dashboard/ when i write the token value on the header which relative to login and is-verify. i can not access the vetId from res.json(user.rows[0])
Here is my jwtGenerator.js code:
const jwt = require('jsonwebtoken');
require('dotenv').config();
//Look at file server/routes/dashboard.js to see the change code for this code
function jwtGenerator(vetId) {
const payload = {
user: vetId,
};
/*function jwtGenerator(vetId) {
const payload = {
user: {
id: vetId,
},
};*/
return jwt.sign(payload, process.env.jwtSecret, { expiresIn: '1h' });
}
module.exports = jwtGenerator;
authorization.js code :
const jwt = require('jsonwebtoken');
require('dotenv').config();
//this middleware will on continue on if the token is inside the local storage
module.exports = async (req, res, next) => {
try {
// Get token from header
const jwtToken = req.header('token');
// Check if not token
if (!jwtToken) {
return res.status(403).json('not authorize');
}
// Verify token
//it is going to give use the user id (user:{id: user.id})
const payload = jwt.verify(jwtToken, process.env.jwtSecret);
//console.log(jwtToken);
req.user = payload.user;
console.log(req.user);
next();
}catch (err) {
console.error(err.message);
res.status(403).json('not authorize');
}
};
index.js code :
const express = require('express');
const app = express();
const cors = require('cors');
app.use(express.json()); // req body
app.use(cors());
//ROUTES
//register and login routes
app.use('/auth', require('./routes/jwtAuth')); // activate routes
app.use('/dashboard', require('./routes/dashboard')); // dashboard route
app.listen(5000, () => {
console.log('server is running on port 5000');
});
the output is
[nodemon] restarting due to changes...
[nodemon] starting `node index index.js`
server is running on port 5000
{}
invalid input syntax for type uuid: "{}"
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
I am creating a Login/Registration Form Using Nodejs. I am hashing the password entered by the user using bcrypt.js but when I assign the password to a variable so that I push that to the database I get this error "Promise { pending }".
I am learning nodejs and react so I do not know too much about this can someone help me.
Thanks!
The Code That I am running is:
################################
const express = require('express');
const app = express();
const mysql = require('mysql2');
const bcrypt = require('bcryptjs');
const cors = require('cors');
// Need this to make api request from backend
app.use(cors());
/**using this express will format the data automatically in json format */
app.use(express.json()); /**Use This Otherwise you get the req.body undefined */
const port = 3001;
const securePassword = async (password) => {
const passwordHash = await bcrypt.hash(password, 4);
return passwordHash;
};
const db = mysql.createConnection({
user: 'root',
host: 'localhost',
password: 'newpassword',
database: 'INSTAGRAM',
});
// Getting Data From Signup Form of React
app.post('/signup', (req, res) => {
const emailaddress = req.body.emailaddress;
const fullname = req.body.fullname;
const username = req.body.username;
const password = req.body.password;
const hashPass = securePassword(password);
console.log(hashPass);
// Checking If Use Already Exist
db.query(
'SELECT * FROM USER WHERE username = ? OR email = ? ',
[username, emailaddress],
(err, result) => {
if (err) {
res.send({ err: err });
} else {
if (result.length > 0) {
res.send({ message: 'Username/Email Already Exist' });
} else {
db.query(
'INSERT INTO USER (username, fullname, email, password) VALUES (?, ?, ?, ?)',
[username, fullname, emailaddress, hashPass],
(err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
}
}
}
);
});
// Starting the server on port 3001
app.listen(port, () => {
console.log(`SERVER STARTED ${port}`);
});
First of all for better and more professional coding try to break your code into multiple functions in multiple .js files .
then you should pass a function to validate the inputs otherwise any data can be passed to db without being validated .
and then you can use this codes for user Registration :
app.js file :
const express = require('express');
const app = express();
const userRouter = require('./routes/user.routes');
app.use(express.json());
app.use('/user', userRouter);
user.routes file :
const express = require('express');
const userRouter = express.Router();
const {httpHandleSignUp} = require('../controllers/user/user.controller');
userRouter.post('/signup', httpHandleSignUp);
module.exports = userRouter
and then for handling Registration you can create a controller file and first of all check the inputs :
httpHandleSignUp controller code :
async function handleSignUp(req, res) {
const values = req.body
const errors = await validateInputs(values, res);
if(errors.length == 0) {
await addUserToDB(values, res);
} else {
res.json(errors)
}
}
you can use any validation you want like code below :
async function validateInputs(values, res) {
let errors = [];
if(!values.name || !values.email || !values.password) {
errors.push('missing required inputs');
}
if(!/\S+#\S+\.\S+/.test(values.email)) { // regex : string#string.string
errors.push('invalid email address ');
}
if(values.password.length < 8) {
errors.push('entered password is too short !');
}
if(await checkDbForEmail(values.email)) {
errors.push('a user with this email already registered !');
}
// TODO : add more validation
return errors;
}
and also you need to a function to check db for already registered users which used in above function :
async function checkDbForEmail(email) {
return await user.findOne({
email: email
});
}
now if there is NO errors the user will be added to DB by this function :
async function addUserToDB(values, res) {
bcrypt.hash(values.password, saltRounds)
.then(hashedPass => {
user.create({
name: values.name,
email: values.email,
password: hashedPass
}, (err, user) => {
res.json({
ok : 'user added to db successfully',
data: {
name: user.name,
email: user.email
}
});
});
})
.catch( (err) => console.log(err));
}
tip: this code works with mongo you may need to changes DB functions.
I am new to node.js and i am trying to create the reset password module for my app. I got stuck on a problem where I wanted to access the result outside of a query.
router.post('/forgot',(req,res)=>{
const db = require('../db.js');
if (req.body.email !== undefined) {
var emailAddress = req.body.email;
// TODO: Using email, find user from your database.
db.query('SELECT * FROM users WHERE email = ?',[emailAddress],(err,results,fields)=>{
if(err){
console.log('Error in pulling the information of the user from the database');
}
var userid = results[0].id;
console.log(userid);
});
var payload = {
id: userid, // User ID from database
email: emailAddress
};
console.log(payload);
} else {
res.send('Email address is missing.');
}
});
I want to get the value of userid which i got from my database and pass it to my outside variable payload and store it in the
id: userid
I did my research on other similar question but was not clear on this topic so any help will be highly appreciated. Thankyou
You're using a callback function here to get the result of your query, what this means is after the query is run it will go ahead and go through the function in the parameter the (err, results, fields) => { ... }, so you could either build your payload inside that callback function, where you would already have the userid on results[0].id or call another function inside that callback with the userid as a parameter.
Something like this
router.post('/forgot', (req, res) => {
const db = require('../db.js');
if (req.body.email !== undefined) {
var emailAddress = req.body.email;
// TODO: Using email, find user from your database.
db.query('SELECT * FROM users WHERE email = ?', [emailAddress], (err, results, fields) => {
if (err) {
console.log('Error in pulling the information of the user from the database');
}
var userid = results[0].id;
console.log(userid);
buildPayload(userid, emailAddress)
});
} else {
res.send('Email address is missing.');
}
});
buildPayload(userId, emailAddress) {
var payload = {
id: userId, // User ID from database
email: emailAddress
};
console.log(payload);
// whatever else you need to do
}
My problem is that I can't call a model instance method on the document returned from a findOne() query, even though I can successfully call the instance method on the same document before I save it to the collection.
First, the usual require()s, followed by schema creation:
var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const pwHash = require('password-hash');
const dbAddress = 'mongodb://localhost/18-652_Ramp_Up_Project';
const projectDb = mongoose.createConnection(dbAddress);
const exampleUserSchema = new mongoose.Schema({
username: String,
password: String,
});
// Instance methods of the User class:
exampleUserSchema.methods.checkPw = function(pwToAuthenticate) {
return pwHash.verify(pwToAuthenticate, this.password);
};
// Retrieve the document corresponding to the specified username.
exampleUserSchema.statics.findOneByUsername = function(username) {
return new Promise((resolve, reject) => {
projectDb.collection('exampleUsers').findOne(
{username: username},
(err, existingUser) => {
if (err) throw(err);
return resolve(existingUser ? existingUser : null);
}
);
});
};
// Constructor (through mongo);
const ExampleUser = projectDb.model('ExampleUser', exampleUserSchema, 'exampleUsers');
Now the interesting part: I can create a new user and call the instance method on it successfully:
// Create a test user and try out the
const hashedPw = pwHash.generate('fakePassword');
ExampleUser.create({username: 'fakeUsername', password: hashedPw}, (err, newUser) => {
console.log(newUser.checkPw('fakePassword')); // --> true
console.log(newUser.checkPw('password123')); // --> false
newUser.save((err) => {
console.log('New user ' + newUser.username + ' saved.'); // --> New user fakeUsername saved.
});
});
But when I try to call it on the document returned from a findOne() query, it's "not a function":
/* POST user login info. */
router.post('/login', (req, res, next) => {
// Try to look up the user in the database.
ExampleUser.findOneByUsername(req.body.username) // Static method works.
.then((existingUser) => {
console.log(existingUser);
if (existingUser && existingUser.checkPw(req.body.password)) { // Instance method doesn't.
console.log('Access granted.');
} else {
console.log('Access denied.');
}
});
});
module.exports = router;
This produces:
POST /example/login 200 22.587 ms - 14
{ _id: 5b3d592d8cd2ab9e27915380,
username: 'fakeUsername',
password: 'sha1$ea496f95$1$6a01df977cf204357444e263861041c622d816b6',
__v: 0 }
(node:40491) UnhandledPromiseRejectionWarning: TypeError: existingUser.checkPw is not a function
at ExampleUser.findOneByUsername.then (/Users/cameronhudson/Documents/GitHub/18-652_Ramp_Up_Project/routes/exampleUsers.js:52:42)
at process._tickCallback (internal/process/next_tick.js:68:7)
I use Passport.js in Node.js to create a login system. Everything is ok, but I do not know how to reset user password when they forget their password or they want to change it.
User model in MongoDB
var UserSchema = new Schema({
email: String,
username: String,
provider: String,
hashed_password: String,
salt: String,
});
Didn't really like the idea of hitting my database to store tokens, especially when you want to be creating and verifying tokens for many actions.
Instead I decided to copy how Django does it:
convert timestamp_today to base36 as today
convert user.id to base36 as ident
create hash containing:
timestamp_today
user.id
user.last_login
user.password
user.email
salt the hash with a hidden secret
create a route like : /change-password/:ident/:today-:hash
We test the req.params.timestamp in order to simply test if it's valid for today, cheapest test first. fail first.
Then we find the user, fail if it doesn't exist.
Then we generate the hash again from above, but with the timestamp from req.params
The reset link becomes invalid if :
they remember their password and login (last_login changes)
they're actually still logged in and:
just change their password (password changes)
just change their email (email changes)
tomorrow arrives (timestamp changes too much)
This way:
you're not storing these ephemeral things in your database
when the purpose of the token is to change the state of a thing, and that things state changed, then the purpose of the token is no longer securely relevant.
I tried to use node-password-reset as Matt617 suggested but didn't really care for it. It's about the only thing that's coming up in searches currently.
So some hours digging around, I found it easier to implement this on my own. In the end it took me about a day to get all the routes, UI, emails and everything working. I still need to enhance security a bit (reset counters to prevent abuse, etc.) but got the basics working:
Created two new routes, /forgot and /reset, which don't require the user to be logged in to access.
A GET on /forgot displays a UI with one input for email.
A POST on /forgot checks that there is a user with that address and generates a random token.
Update the user's record with the token and expiry date
Send an email with a link to /reset/{token}
A GET on /reset/{token} checks that there is a user with that token which hasn't expired then shows the UI with new password entry.
A POST on /reset (sends new pwd and token) checks that there is a user with that token which hasn't expired.
Update the user's password.
Set the user's token and expiry date to null
Here's my code for generating a token (taken from node-password-reset):
function generateToken() {
var buf = new Buffer(16);
for (var i = 0; i < buf.length; i++) {
buf[i] = Math.floor(Math.random() * 256);
}
var id = buf.toString('base64');
return id;
}
Hope this helps.
EDIT:
Here's the app.js. Note I'm keeping the entire user object in the session. I plan on moving to couchbase or similar in the future.
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var bodyParser = require('body-parser');
var http = require('http');
var https = require('https');
var fs = require('fs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var app = express();
app.set('port', 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var cookies = cookieSession({
name: 'abc123',
secret: 'mysecret',
maxage: 10 * 60 * 1000
});
app.use(cookies);
app.use(favicon());
app.use(flash());
app.use(morgan());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app;
passport.use(new LocalStrategy(function (username, password, done) {
return users.validateUser(username, password, done);
}));
//KEEP ENTIRE USER OBJECT IN THE SESSION
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
//Error handling after everything else
app.use(logErrors); //log all errors
app.use(clientErrorHandler); //special handler for xhr
app.use(errorHandler); //basic handler
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on HTTP port ' + app.get('port'));
});
EDIT:
Here are the routes.
app.get('/forgot', function (req, res) {
if (req.isAuthenticated()) {
//user is alreay logged in
return res.redirect('/');
}
//UI with one input for email
res.render('forgot');
});
app.post('/forgot', function (req, res) {
if (req.isAuthenticated()) {
//user is alreay logged in
return res.redirect('/');
}
users.forgot(req, res, function (err) {
if (err) {
req.flash('error', err);
}
else {
req.flash('success', 'Please check your email for further instructions.');
}
res.redirect('/');
});
});
app.get('/reset/:token', function (req, res) {
if (req.isAuthenticated()) {
//user is alreay logged in
return res.redirect('/');
}
var token = req.params.token;
users.checkReset(token, req, res, function (err, data) {
if (err)
req.flash('error', err);
//show the UI with new password entry
res.render('reset');
});
});
app.post('/reset', function (req, res) {
if (req.isAuthenticated()) {
//user is alreay logged in
return res.redirect('/');
}
users.reset(req, res, function (err) {
if (err) {
req.flash('error', err);
return res.redirect('/reset');
}
else {
req.flash('success', 'Password successfully reset. Please login using new password.');
return res.redirect('/login');
}
});
});
Here the implementation of airtonix
const base64Encode = (data) => {
let buff = new Buffer.from(data);
return buff.toString('base64');
}
const base64Decode = (data) => {
let buff = new Buffer.from(data, 'base64');
return buff.toString('ascii');
}
const sha256 = (salt, password) => {
var hash = crypto.createHash('sha512', password);
hash.update(salt);
var value = hash.digest('hex');
return value;
}
api.post('/password-reset', (req, res) => {
try {
const email = req.body.email;
// Getting the user, only if active
let query = AccountModel.where( {username: email, active: true} );
query.select("_id salt username lastLoginDate");
query.findOne((err, account) => {
if(err) {
writeLog("ERROR", req.url + " - Error: -1 " + err.message);
res.status(500).send( { error: err.message, errnum: -1 } );
return;
}
if(!account){
writeLog("TRACE",req.url + " - Account not found!");
res.status(404).send( { error: "Account not found!", errnum: -2 } );
return;
}
// Generate the necessary data for the link
const today = base64Encode(new Date().toISOString());
const ident = base64Encode(account._id.toString());
const data = {
today: today,
userId: account._id,
lastLogin: account.lastLoginDate.toISOString(),
password: account.salt,
email: account.username
};
const hash = sha256(JSON.stringify(data), process.env.TOKENSECRET);
//HERE SEND AN EMAIL TO THE ACCOUNT
return;
});
} catch (err) {
writeLog("ERROR",req.url + " - Unexpected error during the password reset process. " + err.message);
res.status(500).send( { error: "Unexpected error during the password reset process :| " + err.message, errnum: -99 } );
return;
}
});
api.get('/password-change/:ident/:today-:hash', (req, res) => {
try {
// Check if the link in not out of date
const today = base64Decode(req.params.today);
const then = moment(today);
const now = moment().utc();
const timeSince = now.diff(then, 'hours');
if(timeSince > 2) {
writeLog("ERROR", req.url + " - The link is invalid. Err -1");
res.status(500).send( { error: "The link is invalid.", errnum: -1 } );
return;
}
const userId = base64Decode(req.params.ident);
// Getting the user, only if active
let query = AccountModel.where( {_id: userId, active: true} );
query.select("_id salt username lastLoginDate");
query.findOne((err, account) => {
if(err) {
writeLog("ERROR", req.url + " - Error: -2 " + err.message);
res.status(500).send( { error: err.message, errnum: -2 } );
return;
}
if(!account){
writeLog("TRACE", req.url + " - Account not found! Err -3");
res.status(404).send( { error: "Account not found!", errnum: -3 } );
return;
}
// Hash again all the data to compare it with the link
// THe link in invalid when:
// 1. If the lastLoginDate is changed, user has already do a login
// 2. If the salt is changed, the user has already changed the password
const data = {
today: req.params.today,
userId: account._id,
lastLogin: account.lastLoginDate.toISOString(),
password: account.salt,
email: account.username
};
const hash = sha256(JSON.stringify(data), process.env.TOKENSECRET);
if(hash !== req.params.hash) {
writeLog("ERROR", req.url + " - The link is invalid. Err -4");
res.status(500).send( { error: "The link is invalid.", errnum: -4 } );
return;
}
//HERE REDIRECT TO THE CHANGE PASSWORD FORM
});
} catch (err) {
writeLog("ERROR",req.url + " - Unexpected error during the password reset process. " + err.message);
res.status(500).send( { error: "Unexpected error during the password reset process :| " + err.message, errnum: -99 } );
return;
}
});
In my application I'm using passport-local with this Account model
import mongoose from 'mongoose';
import passportLocalMongoose from 'passport-local-mongoose';
const Schema = mongoose.Schema;
let accountSchema = new Schema ({
active: { type: Boolean, default: false },
activationDate: { type: Date },
signupDate: { type: Date },
lastLoginDate: { type: Date },
lastLogoutDate: { type: Date },
salt: {type: String},
hash: {type: String}
});
accountSchema.plugin(passportLocalMongoose); // attach the passport-local-mongoose plugin
module.exports = mongoose.model('Account', accountSchema);
create a random reset key in your DB, persist it with a timestamp. then create a new route that accepts the reset key. verify the timestamp before changing the password to the new password from the route.
never tried this but i ran across this some time ago which is similar to what you need:
https://github.com/substack/node-password-reset
Maybe this article could help:
Password Reset Emails In Your React App Made Easy with Nodemailer
i am not a professional or expert but this worked for me ,well if you are sending password reset email u, while using passport authentication then use
// here User is my model enter code here`
User.findOne({ username: req.body.email }, (err, user) => {
user.setPassword( req.body.password, function(err, users) => {
User.updateOne({ _id: users._id },{ hash: users.hash, salt: users.salt },
(err,result) => {
if (err) {
} else {
}
})
})
})
now here use id to update if you email instead of id in updateOne() it wont work