Exemple #1
0
}, function (req, res, next) {

  var form = req.body;

  if (!validator.isEmail(form['email'])) {
    res.json({'status': '422', 'message':'Email address invalid'});
  }

  form['email'] = validator.normalizeEmail(form['email']);
  form['message'] = validator.escape(form['message']);

  next();

}, function (req, res, next) {
Exemple #2
0
auth.post('/api/auth/signInWithEmail', bodyParser, async (ctx) => {
    const {email, path} = ctx.request.body;
    if (!validator.isIn(path, ['/', '/users/me']) // hard-code white-list redirect paths
        || !validator.isEmail(email)) {
        ctx.throw(400);
    }

    const emailToken = base58.encode(crypto.randomBytes(16));
    if (!emailTokenCache.set(emailToken, {email: validator.normalizeEmail(email), path})) {
        ctx.throw(500);
    }

    const cbUrl = `${process.env.HOST_URL}/et/${emailToken}`;
    sparkPost.transmissions.send({
        transmissionBody: {
            content: {
                from: {
                    name: "cutlog",
                    email: "*****@*****.**"
                },
                subject: 'e-mail sign-in',
                reply_to: 'Amit Portnoy <*****@*****.**>',
                text: `
Sign-in to cutlog with the following link:

${cbUrl}
`,
                html: `
<div>Sign-in to cutlog with the following link:
<br><br>
<a href="${cbUrl}">${cbUrl}</a>
</div>
`
            },
            recipients: [{address: {email}}]
        }
    }, function (err, res) {
        if (err) {
            console.log('Whoops! Something went wrong');
            console.error(err);
        } else {
            console.log(res.body);
        }
    });

    // next if anyone calls /et/<emailToken> before exp it will be redirected to path
    console.log('passwordless sent: ' + emailToken);
    ctx.status = 202; //(Accepted)
});
Exemple #3
0
        getUser: function (email, password, done) {
            var username = validator.normalizeEmail(email);
            User.findByUsername(username, function (err, user) {
                if(err) return done(err);
                if(!user) return done();

                user.validatePassword(password, function (err, valid) {
                    if(err) return done(err);
                    if(!valid) return done();

                    done(null, {
                        id: user.id
                    });
                });
            });
        },
Exemple #4
0
	function(err, results) {
	    if (err) {
		next(err);
	    } else {
		var document = results[0];
		var bridges = results[1];
	
		if (document) {
		    if ( ! hasPermissionToEdit( req.user, document )) {
			res.status(500);
			next(new Error('No permission to edit that user.'));
			return;
		    } else {
			if (document.email)
	    		    document.gravatar = crypto.createHash('md5').update(validator.normalizeEmail(document.email)).digest("hex");
			
			if (req.user._id.equals(document._id))
			    document.pronouned = "me";
			else
			    document.pronouned = document.name;
			
			if (document.birthday) {
			    document.formattedBirthday = moment(new Date(document.birthday)).format('MMMM D, YYYY');
			}
			
			res.format({
			    html: function(){
				console.log(document);
				res.render('user/edit', { userId: req.params.id,
							  user: req.user,
							  bridges: bridges,
							  script: "user/profile",
							  person: document,
							  whyVisible: "Visible to you because " + hasPermissionToView( req.user, document ),
							  editable: hasPermissionToEdit(req.user, document),
							  title: 'Profile' } );
			    },
			});
		    }
		}
		else {
		    res.status(404).json({});
		}
	    }
	});
  return new Promise((resolve, reject) => {
    let newUser = _newUser;

    newUser = {
      firstname: newUser.firstname || undefined,
      lastname: newUser.lastname || undefined,
      gender: newUser.gender || undefined,
      birt: new Date(`${newUser.birthMonth}/${newUser.birthDay}/${newUser.birthYear}`) != 'Invalid Date' || undefined,
      username: validator.escape(newUser.username.trim()),
      email: validator.escape(newUser.email.trim()),
      password1: newUser.password1,
      password2: newUser.password2,
      legals: newUser.legals,
      about: newUser.about || undefined,
      country: newUser.country || undefined,
      error: [],
    };
    if (newUser.username.length === 0 ||
      newUser.username.length < 3 ||
      newUser.username.length > 40) {
      newUser.error.push('Check username length');
    } else {
      newUser.username = newUser.username.toLowerCase();
    }

    if (!validator.isEmail(newUser.email)) {
      newUser.error.push('Use a valid Email');
    } else {
      newUser.email = validator.normalizeEmail(newUser.email, {
        lowercase: true,
        remove_dots: true,
        remove_extension: true,
      });
    }

    if (newUser.password1 !== newUser.password2) {
      newUser.error.push('The passwords must be equal');
    }

    if (newUser.password1.length < 8) {
      newUser.error.push('The password needs to be 8 characters at least');
    }
    // (newUser.error.length) ? reject(newUser.error) : resolve(newUser)
    resolve(newUser);
  });
    create: function (req, res, next) {
        var email          = req.body.email || '',
            emailCheck     = validator.isEmail(email),
            password       = req.body.password || '',
            passwordCheck  = validator.isLength(password, {min: 6, max: 60}),
            firstName      = validator.whitelist(req.body.first_name, 'a-zA-Zа-яА-ЯёЁ') || '',
            firstNameCheck = validator.isLength(firstName, {min: 2, max: 60});

        /* secondName     = validator.whitelist(req.body.secondName, 'a-zA-Zа-яА-ЯёЁ') || '',
         middleName     = validator.whitelist(req.body.middleName, 'a-zA-Zа-яА-ЯёЁ') || '';*/

        if (emailCheck && passwordCheck && firstNameCheck) {
            email = validator.normalizeEmail(email);
            UsersModel.findOne({email: email}, function (error, data) {
                if (error) return Response.error(res, 500, error);
                if (data) {
                    //Пользователь существует
                    Response.warning(res, 2, {user: 1});
                } else {
                    var passwordSalt = AuthHelpers.getSalt();
                    password = AuthHelpers.encryptPassword(password, passwordSalt);
                    UsersModel.create({
                        email: email,
                        firstName: firstName,
                        password: password,
                        passwordSalt: passwordSalt
                    }, function (error, data) {
                        if (error) Response.error(res, 500, error);
                        Response.success(res, data);
                    });
                }
            });

        } else {
            Response.warning(res, 1, {
                email: email,
                emailCheck: emailCheck,
                password: password,
                passwordCheck: passwordCheck,
                firstName: firstName,
                firstNameCheck: firstNameCheck
            });
        }
    },
Exemple #7
0
    function validateSignup(firstname, lastname, username, email, password) {

        if (validator.isNull(firstname) ||
            validator.isNull(lastname) ||
            validator.isNull(username) ||
            validator.isNull(email) ||
            validator.isNull(password)) {
            console.log("One or more of the fields is/are NULL");
            return false;
        }

        firstname = validator.trim(firstname);
        lastname = validator.trim(lastname);
        var name = validator.trim(firstname + lastname);
        if (!validator.isAlpha(name)) {
            console.log("name: " + name + " is alpha? " + validator.isAlpha(name));
            return false;
        }

        username = validator.trim(username);
        if (!validator.isAlphanumeric(username)) {
            console.log("username: "******" is alphanumeric? " + validator.isAlphanumeric(username));
            return false;
        }

        email = validator.normalizeEmail(email);
        if (!validator.isEmail(email)) {
            console.log("email: " + email + " is email? " + validator.isEmail(email));
            return false;
        }

        // TODO: check if email already exists
        // done on the front end

        if ((!validator.isAlphanumeric(password)) && (password.length > 3)) {
            console.log("password: "******" is alphanumeric? " + validator.isAlphanumeric(password) + " length is greater than 3? " + password.length > 3);
            return false;
        }

        console.log("No errors!");
        return true;
    }
Exemple #8
0
    }, (email, password, done) => {

        //Clean input
        validator.escape(email);
        validator.escape(password);

        if (!validator.isEmail(email)) return done(null, false, { message: 'Not a valid email address' });

        validator.normalizeEmail(email);

        //Check if user exists
        User.findUser(email, (exists, err) => {
            if (!exists) {
                //User does not exist, exit
                console.log('USER DOESNT EXIST: ' + email);

                return done(null, false, { message: 'User does not exist' })
            } else {
                console.log('SIGNING IN USER' + email)

                //User exists, check if password is valid
                const user = new User(email, password);
                user.checkValidPassword(password, (isValidPass, err) => {
                    if (!err) {
                        if (isValidPass) {
                            console.log("AUTHENTICATED");
                            return done(null, user);
                        } else {

                            return done(null, false, { message: 'Invalid Password' });
                        }
                    }
                });
            }
        });
    }));
Exemple #9
0
    it('should include new email', function () {
	user.should.have.property('email');
	validator.normalizeEmail(user.email).should.equal( validator.normalizeEmail(updatedData.email) );
    });
Exemple #10
0
        function(err, connection){
            if (err) {
                return cb(err);
            }

            console.log("\n[DB] Connected to database !\n");
            connection.execute(
                'insert into SITEUSERS ( ' +
                '   user_email, ' +
                '   user_password, ' +
                '   user_role, ' +
                '   user_firstname, '+
                '   user_lastname '+
                ') ' +
                'values (' +
                '    :user_email, ' +
                '    :user_password, ' +
                '    \'BASE\', ' +
                '    :user_firstname, '+
                '    :user_lastname '+
                ') ' +
                'returning ' +
                '   user_id, ' +
                '   user_email, ' +
                '   user_role, ' +
                '   user_firstname, '+
                '   user_lastname '+
                'into ' +
                '   :user_rid, ' +
                '   :user_remail, ' +
                '   :user_rrole, '+
                '   :user_rfirstname, '+
                '   :user_rlastname'
                ,
                {
                    user_email: validator.normalizeEmail(user.user_email),
                    user_firstname: user.user_firstname,
                    user_password: user.hashedPassword,
                    user_lastname:user.user_lastname,
                    user_rid: {
                        type: oracledb.NUMBER,
                        dir: oracledb.BIND_OUT
                    },
                    user_remail: {
                        type: oracledb.STRING,
                        dir: oracledb.BIND_OUT
                    },
                    user_rrole: {
                        type: oracledb.STRING,
                        dir: oracledb.BIND_OUT
                    },
                    user_rfirstname: {
                        type: oracledb.STRING,
                        dir: oracledb.BIND_OUT
                    },
                    user_rlastname: {
                        type: oracledb.STRING,
                        dir: oracledb.BIND_OUT
                    }
                },
                {
                    autoCommit: true
                },
                function(err, results){
                    if (err) {
                        connection.release(function(err) {
                            if (err) {
                                console.error(err.message);
                            }
                        });

                        return cb(err);
                    }

                    cb(null, {
                        user_id: results.outBinds.user_rid[0],
                        user_email: results.outBinds.user_remail[0],
                        role: results.outBinds.user_rrole[0],
                        user_firstname: results.outBinds.user_rfirstname[0],
                        user_lastname: results.outBinds.user_rlastname[0]
                    });

                    connection.release(function(err) {
                        if (err) {
                            console.error("[DB] " + err.message);
                        } else {
                            console.log("\n[DB] Disconnected from the database !\n");
                        }
                    });
                });
        }
Exemple #11
0
		users.forEach( function(user) {
		    if (user.email)
	    		user.gravatar = crypto.createHash('md5').update(validator.normalizeEmail(user.email)).digest("hex");
		});
Exemple #12
0
	function(err, results) {
	    if (err) {
		next(err);
	    } else {
		var document = results[0];
		var bridges = results[1];

		if (document) {
		    if ( ! hasPermissionToEdit( req.user, document )) {
			res.status(403);
			next(new Error('No permission to access other users.'));
			return;			
		    } else {	    
			if (req.user._id.toString() == id)
			    document.pronouned = "me";
			else
			    document.pronouned = document.name;			    
			
			var hash = {};
			
			if (req.body.displayName)
			    document.displayName = hash.displayName = validator.toString(req.body.displayName);	    
			else
			    document.displayName = hash.displayName = '';		
			
			if (req.body.visibility)
			    if (validator.isIn(req.body.visibility, ["none", "users", "everyone"]))
				document.visibility = hash.visibility = req.body.visibility;
			
			if ((req.body.email) && (validator.isEmail(req.body.email)))
			    document.email = hash.email = validator.normalizeEmail(req.body.email);
			else
			    document.email = hash.email = '';		
			
			if ((req.body.website) && (validator.isURL(req.body.website)))
			    document.website = hash.website = req.body.website;
			else
			    document.website = hash.website = '';	
			
			if (req.body.birthday)
			    document.birthday = hash.birthday = validator.toDate(req.body.birthday);
			else
			    document.birthday = '';
			
			if (document.birthday) {
			    document.formattedBirthday = moment(new Date(document.birthday)).format('MMMM D, YYYY');
			}	    
			
			if (req.body.biography)
			    document.biography = hash.biography = validator.toString(req.body.biography);
			else
			    document.biography = hash.biography = '';
			
			if (req.body.location)
			    document.location = hash.location = validator.toString(req.body.location);
			
			if (document.email)
	    		    document.gravatar = crypto.createHash('md5').update(validator.normalizeEmail(document.email)).digest("hex");	    
			
			// Only superusers can edit flags
			if (req.user.superuser) {
			    if (req.body.isInstructor) 
				document.isInstructor = hash.isInstructor = true;
			    else
				document.isInstructor = hash.isInstructor = false;
			    
			    if (req.body.isAuthor) 
				document.isAuthor = hash.isAuthor = true;
			    else
				document.isAuthor = hash.isAuthor = false;
			    
			    if (req.body.isGuest) 
				document.isGuest = hash.isGuest = true;
			    else
				document.isGuest = hash.isGuest = false;		    
			    
			    if (req.body.superuser) 
				document.superuser = hash.superuser = true;
			    else
				document.superuser = hash.superuser = false;		    		    
			}
			
			mdb.User.update( {_id: new mongo.ObjectID(id)}, {$set: hash},
					 function(err, d) {
					     
					     if (err)
						 res.send(500);
					     else {	
						 res.render('user/profile', { userId: req.params.id,
									      user: req.user,
									      updated: true,
									      bridges: bridges,
									      script: "user/profile",
									      person: document,
									      editable: true,
									      title: 'Profile' } );
					     }
					 });
		    }
		}
		else {
		    res.status(404).json({});
		}
	    }
	});
Exemple #13
0
	function(err, results) {
	    if (err) {
		next(err);
	    } else {
		var document = results[0];
		var bridges = results[1];
		
		if (!document) {
		    res.status(404).render('404', { status: 404, url: req.url });
		    return;
		}
		
		var viewerPermission = hasPermissionToView( req.user, document );
		if ( ! viewerPermission ) {
		    next(new Error('No permission to access other users.'));
		    return;			
		} else {
		    // Add one view to the count of profileViews
		    mdb.User.update({_id: new mongo.ObjectID(id)},
				    { $inc: { profileViews: 1 } });

		
		    if (document.email)
	    		document.gravatar = crypto.createHash('md5').update(validator.normalizeEmail(document.email)).digest("hex");

		    if (document.birthday) {
			document.formattedBirthday = moment(new Date(document.birthday)).format('MMMM D, YYYY');
		    }	    
	    
		    if (req.user._id.equals(document._id))
			document.pronouned = "me";
		    else
			document.pronouned = document.name;		
		    
		    if (!hasPermissionToEdit(req.user, document)) {
			document.googleOpenId = undefined;
			document.courseraOAuthId = undefined;
			document.githubId = undefined;
			document.twitterOAuthId = undefined;
			document.apiKey = "";
			document.apiSecret = "";
			document.password = "";
		    }
		    
		    res.format({
			html: function(){
			    res.render('user/profile', { userId: req.params.id,
							 user: req.user,
							 script: "user/profile",
							 person: document,
							 bridges: bridges,
							 whyVisible: "Visible to you because " + viewerPermission,
							 editable: hasPermissionToEdit(req.user, document),
							 title: 'Profile' } );
			},
			
			json: function(){
			    res.json(document);
			}
		    });
		}
            }
	});
 normalizeEmail: function (str, options) {
   return validator.normalizeEmail(str, typeof options === 'object' ? options : undefined);
 },
module.exports.cleanseEmail = function(email) {
  if ( typeof email !== 'string' || !(v.isEmail(email)) ) {
    return '';
  }
  return v.normalizeEmail(email);
};