Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hi, I have attached an alternative to validate email accounts for users #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions email_validation/routes/loging.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* POST /login
* Sign in with email and password
* EV-01 : If the mail was not validated befere, then, the user cannot be logged-in and the script throws code 401
*/
exports.loginPost = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('password', 'Password cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });

// Check for validation erro
var errors = req.validationErrors();
if (errors) return res.status(400).send(errors);

User.findOne({ email: req.body.email }, function(err, user) {
if (!user) return res.status(401).send({ msg: 'The email address ' + req.body.email + ' is not associated with any account. Double-check your email address and try again.'});

user.comparePassword(req.body.password, function (err, isMatch) {
if (!isMatch) return res.status(401).send({ msg: 'Invalid email or password' });

// Make sure the user has been verified
if (!user.isVerified) return res.status(401).send({ type: 'not-verified', msg: 'Your account has not been verified.' });

// Login successful, write token, and send back user
res.send({ token: generateToken(user), user: user.toJSON() });
});
});
};
47 changes: 47 additions & 0 deletions email_validation/routes/signup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
var crypto = require('crypto');
var nodemailer = require('nodemailer');

/**
* POST /signup
* Every time a new user is sign up. The token is submitted insted of log-in the user.
*/
exports.signupPost = function(req, res, next) {
req.assert('name', 'Name cannot be blank').notEmpty();
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.sanitize('email').normalizeEmail({ remove_dots: false });

// Check for validation errors
var errors = req.validationErrors();
if (errors) { return res.status(400).send(errors); }

// Make sure this account doesn't already exist
User.findOne({ email: req.body.email }, function (err, user) {

// Make sure user doesn't already exist
if (user) return res.status(400).send({ msg: 'The email address you have entered is already associated with another account.' });

// Create and save the user, Remember the schema?
user = new User({ name: req.body.name, email: req.body.email, password: req.body.password });
user.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }

// Create a verification token for this user
var token = new Token({ _userId: user._id, token: crypto.randomBytes(16).toString('hex') });

// Save the verification token
token.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }

// Send the email
var transporter = nodemailer.createTransport({ service: 'Sendgrid', auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD } });
var mailOptions = { from: 'roomie.fnder.econfirmation@gmail.com', to: user.email, subject: 'Account Verification Token', text: 'Hello,\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '\/confirmation\/' + token.token + '.\n' };
transporter.sendMail(mailOptions, function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
res.status(200).send('A verification email has been sent to ' + user.email + '.');
});
});
});
});
};
4 changes: 4 additions & 0 deletions email_validation/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//To use in Postman.

app.post('/confirmation', userController.confirmationPost);
app.post('/resend', userController.resendTokenPost);
36 changes: 36 additions & 0 deletions email_validation/utils/auth/ResendTokens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* POST /resend
* This script is a mechanism when the time of token is expired. It reuses the token information and gives
* to the user a new chance to verify their e-mail account and activate their account
*/
exports.resendTokenPost = function (req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });

// Check for validation errors
var errors = req.validationErrors();
if (errors) return res.status(400).send(errors);

User.findOne({ email: req.body.email }, function (err, user) {
if (!user) return res.status(400).send({ msg: 'We were unable to find a user with that email.' });
if (user.isVerified) return res.status(400).send({ msg: 'This account has already been verified. Please log in.' });

// Create a verification token, save it, and send email
var token = new Token({ _userId: user._id, token: crypto.randomBytes(16).toString('hex') });

// Save the token
token.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }

// Send the email
var transporter = nodemailer.createTransport({ service: 'Sendgrid', auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD } });
var mailOptions = { from: 'roomie.fnder.econfirmation@gmail.com', to: user.email, subject: 'Account Verification Token', text: 'Hello,\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '\/confirmation\/' + token.token + '.\n' };
transporter.sendMail(mailOptions, function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
res.status(200).send('A verification email has been sent to ' + user.email + '.');
});
});

});
};
33 changes: 33 additions & 0 deletions email_validation/utils/auth/TokenConf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* POST /confirmation
* This script is activate when the user confirms their email.
* As soon as the user is activate, the user can be logged in.
*/
exports.confirmationPost = function (req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('token', 'Token cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });

// Check for validation errors
var errors = req.validationErrors();
if (errors) return res.status(400).send(errors);

// Find a matching token
Token.findOne({ token: req.body.token }, function (err, token) {
if (!token) return res.status(400).send({ type: 'not-verified', msg: 'We were unable to find a valid token. Your token my have expired.' });

// If we found a token, find a matching user
User.findOne({ _id: token._userId, email: req.body.email }, function (err, user) {
if (!user) return res.status(400).send({ msg: 'We were unable to find a user for this token.' });
if (user.isVerified) return res.status(400).send({ type: 'already-verified', msg: 'This user has already been verified.' });

// Verify and save the user
user.isVerified = true;
user.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
res.status(200).send("The account has been verified. Please log in.");
});
});
});
};
10 changes: 10 additions & 0 deletions email_validation/utils/auth/TokenCreat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//This script creates a Token as the user is sign-in.
//Token expires in 43200s
//NOTE: This action is already be on the main back-end prroject.
//EV-02: If a user does not activate their account, then they cannot log-in and the account is deleted.

const tokenSchema = new mongoose.Schema({
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
token: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: 43200 }
});
12 changes: 12 additions & 0 deletions email_validation/utils/schemas/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//This script is used to model the standard schema for Users.
//It´s the first script of the diagram flow.
//Where should I use the credentianls for MongoDB access?
var userSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true }, //This flag is essential for E-mail verification
roles: [{ type: 'String' }],
isVerified: { type: Boolean, default: false },
password: String,
passwordResetToken: String,
passwordResetExpires: Date
}, schemaOptions);
6 changes: 5 additions & 1 deletion utils/schemas/rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const roomDescriptionSchema = joi.string().max(750);
const roomLocationSchema = joi.string().max(50);
const roomPriceSchema = joi.number().max(1000000);
const roomOcupationSchema = joi.number().max(30).min(1);
const roomIdHostSchema = joi.number();
const roomPhotoHostSchema = joi.array();
const roomNameHostSchema =joi.string();
const roomIdHostSchema = joi.string().max(500);
const roomCorreoHostSchema = joi.string().max(20);
const roomTelefonoHostSchema = joi.number();
Expand All @@ -27,7 +30,8 @@ const createRoomSchema = {
location: roomLocationSchema.required(),
price: roomPriceSchema.required(),
ocupation: roomOcupationSchema.required(),
idHost: roomIdHostSchema,
idHost:
,
nameHost: roomNameHost,
wc: roomWcSchema,
Wifi: roomWifiSchema,
Expand Down