I am trying to build a user registration forum for a web app.
To refactor my code I created a folder named api and defined some routes in index.js (/api/routes/index.js).
Now I wanted to route my signup form to this route in (/api/routes/index.js) so that the data can go to user_sign_up function which is defined in (api/controllers/users.js)
my app.js looks like:
// some code
var routesApi = require('./api/routes/index');
app.use('/api', routesApi);
// some code
my (/api/routes/index) looks like:
// some code
var ctrlevents = require('../controllers/users');
router.post('/registeruser', ctrlevents.user_sign_up);
// some code
module.exports = router;
In server folder of my app, I have views folder under which all .html files are present.
How do I define routes for action attribute in signup form?
my users.js looks like:
module.exports.user_sign_up = (req, res) => {
// some code
};
I tried:
<form method="POST" action="/registeruser">
got this:
enter image description here
Following is working but getting 500 status.
<form method="POST" action="/api/registeruser">
Adding user_sign_up function:
/* GET signup data */
module.exports.user_sign_up = (req, res) => {
Name: req.body.username;
email: req.body.email;
password: req.body.password;
cpassword: req.body.cpassword;
console.log('ghfhghgh');
console.log(email);
console.log(password);
console.log(cpassword);
req.checkBody('Name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('cpassword', 'Passwords do not match').equals(req.body.password);
let errors = req.validationErrors();
if (err) {
res.render('register', {
errors:errors
});
}
else {
let newUser = new User({
Name:Name,
email:email,
password:password
})
}
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) {
console.log(err);
}
newUser.password = hash;
newUser.save((err) => {
if(err) {
console.log(err);
return;
}
else {
req.flash('success', 'Welcome to TechPath');
req.redirect('/blog');
}
})
});
})
};
As I understand, you want the action attribute in your sign up form. Since you already created a route registeruser which also has controller user_sign_up, just pass registeruser to your form as action. It should be working.
<form method="POST" action="/registeruser">
</form>
Edit:
I created a similar structure to yours, my code works well. Try to compare your code and my code and keep me updated if your issue is resolved or not.
I think you have to assign value using = sign
Name = req.body.username;
email = req.body.email;
password = req.body.password;
cpassword = req.body.cpassword;
Related
I am a beginner working with node and I am attempting to allow for user registration on a project. However, anytime I press the register button on my page I receive this error:
ReferenceError: bcrypt is not defined
at model.<anonymous> (/Users/hossamalsheikh/Documents/Personal Projects/Web Apps/Gaming/models/User.js:29:5)
at callMiddlewareFunction (/Users/hossamalsheikh/Documents/Personal Projects/Web Apps/Gaming/node_modules/kareem/index.js:482:23)
at model.next (/Users/hossamalsheikh/Documents/Personal Projects/Web Apps/Gaming/node_modules/kareem/index.js:58:7)
at _next (/Users/hossamalsheikh/Documents/Personal Projects/Web Apps/Gaming/node_modules/kareem/index.js:106:10)
at /Users/hossamalsheikh/Documents/Personal Projects/Web Apps/Gaming/node_modules/kareem/index.js:507:38
at processTicksAndRejections (internal/process/task_queues.js:79:11)
I don't understand what the issue could be. I gave both downloaded and required the bcryptjs module. Here is my code:
// Modules required to run the application
const express = require('express');
const bcrypt = require('bcryptjs');
// Creates 'mini app'
const router = express.Router();
// User model
const User = require('../models/User');
// Login Page
router.get('/login', function(req, res){
res.render("./home/login");
});
// Registration Page
router.get('/register', function(req, res){
res.render("./home/register");
});
// Registration
router.post('/register', function(req, res){
const { name, email, password, password2 } = req.body;
let errors = [];
// Check requried fields
if(!name || !email || !password || !password2){
errors.push({ msg: 'Please fill in all feilds' });
}
//Check passwords match
if(password !== password2){
errors.push({ msg: "Passwords do not match" });
}
// Check password length
if(password.length < 6){
errors.push({ msg: "Password should be at least six characters long" });
}
// Checks for any errors and prevents registration/redirection
if(errors.length > 0){
res.render('./home/register', {
errors,
name,
email,
password,
password2
});
}
else{
// Validation passed
User.findOne({ email: email })
.then(function(user){
if(user){
// User exists
errors.push({ msg: "Email is already registered" });
res.render('./home/register', {
errors,
name,
email,
password,
password2
});
} else {
const newUser = new User({
name: name,
email: email,
password: password
});
// Hash Password
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
if(err){
throw err;
}
// Sets the password to the hashed password
newUser.password = hash;
newUser.save().then(function(user){
res.send('/users/login');
}).catch(function(err){
console.log(err);
});
});
});
}
});
}
});
module.exports = router;
Thank you for any assistance.
In my Node.js/MERN app, I get error 250 2.0.0 OK 1590267554 o18sm275551eje.40 - gsmtp & something went wrong when I register my user for authentication and receive an email with EMPTY body. I am using the code from https://blog.bitsrc.io/email-confirmation-with-react-257e5d9de725
I can see user is added to mongodb database with confirmed set to false. Why am I not getting the complete email with confirmation?
Please find my attached code for my MERN application. I would really appreciate a reply! Thank you!
Register
Register route in users which takes you to login and on React side OnSubmit starts chain of sending and confirming email.
router.post("/register", type, function (req, res, next) {
// var tmp_path = req.file.path;
if(!req.file){
console.log("File missing");
}
/** The original name of the uploaded file
stored in the variable "originalname". **/
// var target_path = 'uploads/' + req.file.originalname;
// /** A better way to copy the uploaded file. **/
// var src = fs.createReadStream(tmp_path);
// var dest = fs.createWriteStream(target_path);
// src.pipe(dest);
// fs.unlink(tmp_path);
// src.on('end', function() { res.render('complete'); });
// src.on('error', function(err) { res.render('error'); });
// Form validation
const { errors, isValid } = validateRegisterInput(req.body);
const url = req.protocol + '://' + req.get('host')
// Check validation
if (!isValid) {
return res.status(400).json(errors);
}
//Checks email against registered emails in database
registeredemails.findOne({ email: req.body.email}).select("email").lean().then(result => {
if (!result) {
return res.status(400).json({email: "Email not provided"});
}
});
User.findOne({ email: req.body.email }).then(user =>
{
if (user) {return res.status(400).json({ email: "Email already exists" })
}
else if(!user){
const newUser = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password,
fileimg: url + '/public/' + req.file.filename
});
// // Hash password before saving in database
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(newUser =>
sendEmail(newUser.email),
templates.confirm(newUser._id)
)
.then(() => res.json({ msg: msgs.confirm }))
.catch(err => console.log(err))
}
)}
)}
else if (user && !user.confirmed) {
sendEmail(user.email, templates.confirm(user._id))
.then(() => res.json({ msg: msgs.resend })).catch(err => console.log(err))
}
// The user has already confirmed this email address
else {
res.json({ msg: msgs.alreadyConfirmed })
}
}).catch(err => console.log(err))
sendemail as used in the MEDIUM articles
const nodemailer = require('nodemailer');
const { CLIENT_ORIGIN } = require('../../config')
// const mg = require('nodemailer-mailgun-transport');
// The credentials for the email account you want to send mail from.
const credentials = {
secure: true,
service: 'Gmail',
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
// These environment variables will be pulled from the .env file
// apiKey: 'b61286bf9e28b149fac32220f0c7349f-e5e67e3e-00a38515',
// domain: 'sandbox0b8a7f0ebcc74c0d8161304f24909bd2.mailgun.org'
}
}
// Getting Nodemailer all setup with the credentials for when the 'sendEmail()'
// function is called.
const transporter = nodemailer.createTransport(credentials)
// exporting an 'async' function here allows 'await' to be used
// as the return value of this function.
module.exports = async (to, content) => {
// The from and to addresses for the email that is about to be sent.
const contacts = {
from: process.env.MAIL_USER,
to // An array if you have multiple recipients.
// subject: 'React Confirm Email',
// html: `
// <a href='${CLIENT_ORIGIN}/confirm/${id}'>
// click to confirm email
// </a>
// `,
// text: `Copy and paste this link: ${CLIENT_ORIGIN}/confirm/${id}`
}
// Combining the content and contacts into a single object that can
// be passed to Nodemailer.
const email = Object.assign({}, content, contacts)
// This file is imported into the controller as 'sendEmail'. Because
// 'transporter.sendMail()' below returns a promise we can write code like this
// in the contoller when we are using the sendEmail() function.
//
// sendEmail()
// .then(() => doSomethingElse())
//
// If you are running into errors getting Nodemailer working, wrap the following
// line in a try/catch. Most likely is not loading the credentials properly in
// the .env file or failing to allow unsafe apps in your gmail settings.
await transporter.sendMail(email, function(error, info){
if(error)
{
return console.log(error);
}
else
{
return console.log(info.response);
}
})
}
templates.confirm as used in Medium article
onst { CLIENT_ORIGIN } = require('../../config')
// This file is exporting an Object with a single key/value pair.
// However, because this is not a part of the logic of the application
// it makes sense to abstract it to another file. Plus, it is now easily
// extensible if the application needs to send different email templates
// (eg. unsubscribe) in the future.
module.exports = {
confirm: id => ({
subject: 'React Confirm Email',
html: `
<a href='${CLIENT_ORIGIN}/confirm/${id}'>
click to confirm email
</a>
`,
text: `Copy and paste this link: ${CLIENT_ORIGIN}/confirm/${id}`
})
}
I am creating a registration using Express Validator and for some reason, I am getting a reference error that the profileimage is not defined. Another thing, in my code, in declaring the variable profileimage, it remains grayed out (visual studio Code) and later in my code, it says that profileimage is declared but never read. If anyone could have a look at my code and help me spot something I might have missed, I would really appreciate it. Thank you.
register.pug
extends layout
block content
h2.page-header Register
p Please register using the form below.
if errors
each error, i in errors
div.alert.alert-danger #{error.msg}
form(method="post", action="/users/register", enctype="multipart/form-data")
.form-group
label Name
input.form-control(name="name", type="text", placeholder="Enter Name")
.form-group
label Email
input.form-control(name="email", type="email", placeholder="Enter Email")
.form-group
label User Name
input.form-control(name="username", type="text", placeholder="Enter User Name")
.form-group
label Password
input.form-control(name="password", type="password", placeholder="Enter Password")
.form-group
label Confirm Password
input.form-control(name="password2", type="password", placeholder="Confirm Password")
.form-group
label Profile Image
input.form-control(name="profileimage", type="file")
input.btn.btn-primary(type="submit", mame="submit", value="Register")
users.js
const express = require("express");
const router = express.Router();
const multer = require("multer");
const upload = multer({ dest: "./uploads" });
const User = require("../models/user");
/* GET users listing. */
router.get("/", function(req, res, next) {
res.send("respond with a resource");
});
router.get("/register", function(req, res, next) {
res.render("register", { title: "Register" });
});
router.get("/login", function(req, res, next) {
res.render("login", { title: "Login" });
});
router.post("/register", upload.single("profileimage"), function(
req,
res,
next
) {
let name = req.body.name;
let email = req.body.email;
let username = req.body.username;
let password = req.body.password;
let password2 = req.body.password2;
if (req.file) {
console.log("Uploading File...");
let profileimage = req.file.filename;
} else {
console.log("No File Uploaded");
let profileimage = "noimage.jpg";
}
// Form Validator
req.check("name", "Name Field is Required").notEmpty();
req.check("email", "Email Field is Required").notEmpty();
req.check("email", "Email is not valid").isEmail();
req.check("username", "User Name Field is Required").notEmpty();
req.check("password", "Password Field is Required").notEmpty();
req.check("password2", "Passwords do not match").equals(req.body.password);
// Check errors
let errors = req.validationErrors();
if (errors) {
res.render("register", {
errors: errors
});
} else {
let newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileimage
});
User.createUser(newUser, function(err, user) {
if (err) throw err;
console.log(user);
});
res.location("/");
res.redirect("/");
}
});
module.exports = router;
user.js
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/nodeauth", { userNewUrlParser: true });
const db = mongoose.connection;
// User Schema
let UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
profileimage: {
type: String
}
});
let User = (module.exports = mongoose.model("User", UserSchema));
module.exports.createUser = function(newUser, callback) {
newUser.save(callback);
};
By changing let to var in users.js and resetting the nodejs server, I was able to get the code to work. I hope this helps someone with a similar issue.
I create a loginapp in nodejs but i want to verify if the email(or username) il already in the database.
router.post('/register', function(req, res) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
req.checkBody('username', 'Please enter a username').notEmpty();
req.checkBody('email', 'pls enter a email adress').notEmpty().isEmail();
req.checkBody('password', 'pls enter a password').notEmpty();
req.checkBody('password2', 'the password dont match').equals(req.body.password);
var errors = req.validationErrors();
if(errors) {
res.render('register',{
errors:errors,
})
} else {
var newUser = new User({
email:email,
username: username,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'u create an accoun, u can log');
res.redirect('/users/login');
}
})
How can a do a verify why an error msg if the email is already in the database ?
You can call findOne on the collection with the specified email. It resolves to null if no document matches. You can use that so as to detect whether or not there is already a user with the same email in the database.
You didn't provide the relevant part of the code to guess the architecture of you database, but you're probably going to use something like the following:
const { MongoClient } = require('mongodb');
const email = 'john#doe.com';
// wraps everything in an async function
(async () => {
// connect to database
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const users = client.db('your-db-name').collection('users');
// look for an existing user
let possibleDuplicate = await users.findOne({email});
if (possibleDuplicate===null) {
// email is not taken
// do something...
} else {
// email is taken
// do something...
}
})()
I have this two codes. first one uses multer to save a user with an image. For each user, it saves the uploaded image with a particular name in the avatar field and the same name for the image. if no image is uploaded then save noimage.png as a name in the avatar field.
The second one decodes a base64 string to a picture and saves it to the specific path but every time an image is uploaded is being overwritten.
Is it possible to implement both codes to have the functionality of the first one but decoding the image from a base64 string?
The base64 string is the result of a cropped image. I want the user to be able to crop an area of the image to display it as the avatar.
Thanks in advance.
// Register Proccess
router.post('/register', upload.single('avatar'), function(req, res){
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
const password2 = req.body.password2;
const date = new Date();
if(req.file){
var avatar = req.file.filename;
} else {
var avatar = 'noimage.png';
}
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
let {errors, validationResults} = require('express-validator');
if(errors){
res.render('register', {
errors:errors
});
} else{
let newUser = new User({
username:username,
email:email,
password:password,
date: date,
avatar: avatar
});
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
if(err){
console.log(err);
}
newUser.password = hash;
newUser.save(function(err){
if(err){
console.log(err);
return;
} else {
req.flash('success','You are now registered and can log in');
res.redirect('/');
}
});
});
});
})
});
Second code
var upload = multer();
router.post('/crop', upload.single('avatar'), function(req, res) {
let img = req.body.cropped;
let image = img.split(';base64,').pop();
fs.writeFile("public/images/uploads/out.png", image, {encoding: 'base64'}, function(err) {
console.log('File created');
if(err){
console.log(err);
return;
} else {
res.redirect('/crop');
}
});
});