Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ########## user_fns.js
- const hashPassword = (password) => {
- bcrypt.hash(password, saltRounds, (err, hash) => {
- if(err){
- console.log(err)
- } else {
- // console.log(hash)
- return hash
- }
- })
- }
- const getUserByEmail = (email) => {
- return Promise.try(() => {
- return database("users").where({ email: email });
- }).then(function(results){
- if(results.length !== 0){
- console.log('there are results from checkUser_EmailExists, results object is:', results)
- return results
- } else {
- console.log('there are no results from checkUser_EmailExists, results object is:', results)
- return results
- }
- })
- .catch(function(err) {
- throw('error on attempt to checkUser_EmailExists', err)
- })
- }
- const createUser = (username, email, hashed_password) => {
- // our default usertype is 'general-hasNot-applied'
- return Promise.try(() => {
- database('users').insert([
- { username: username,
- email: email,
- hashed_password: hashed_password,
- user_type: 'general-hasNot-applied'
- }
- ])
- .catch(function(err) {
- throw('error on attempt to createUser', err)
- })
- })
- }
- // ######### excerpt from the API file that uses the above functions
- return Promise.try(() => {
- // Here, we return the result of calling our own function. That return value is a Promise.
- return User_fns.getUserByEmail(req.body.email);
- }).then((user) => {
- // B - if user obj does not exist, we can safely create one
- // an empty user object appears as empty array: []
- if (user === undefined || user.length == 0) {
- // array empty or does not exist
- console.log('user obj is empty or does not exist');
- // safe to create user, b/c this one we searched for does not exist.
- // - B1. hash pw.
- console.log('pw avail?', req.body.password);
- var password = req.body.password;
- var hashed_password = User_fns.hashPassword(password);
- console.log('hashed_password 123?', hashed_password)
- User_fns.createUser(req.body.username, req.body.email, hashed_password)
- req.flash('success', 'Thanks for registering.')
- res.render('pages/register', {
- data: req.body, // { message, email }
- errors: errors.mapped(),
- env: process.env.NODE_ENV
- })
- // - B2. insert user into users table.
- // passing in the request objects from form, and hashed_password
- // should even pass in some of their info, such as username, so its clear that it worked
- // - B3. flash confirmation
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement