· 8 years ago · Aug 07, 2018, 11:42 AM
1::1 - - [07/Aug/2018:09:20:19 +0000] "POST /users/signup HTTP/1.1" - - "-" "PostmanRuntime/7.2.0"
2Executing (default): SELECT "user_id", "username", "name", "firstname", "email", "type", "location", "password", "createdAt", "updatedAt" FROM "users" AS "users" LIMIT 1;
3
4/* CREATE an account */
5 app.post('/users/signup', (req, res) => {
6
7 db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] }).then(user => {
8
9 if (err) {
10 return res.send(err);
11 }
12 if (user) {
13 if (user.email == req.body.email) {
14 return res.send("This email is already taken.")
15 }
16 return res.send("This username is already taken.")
17 }
18 else {
19
20 const data = {
21 username: req.body.username,
22 name: req.body.name,
23 firstname: req.body.firstname,
24 email: req.body.email,
25 location: req.body.location,
26 type: req.body.type,
27 password: req.body.password
28 };
29
30 db.users.create({
31 username: data.username,
32 name: data.name,
33 firstname: data.firstname,
34 email: data.email,
35 location: data.location,
36 type: data.type,
37 password: data.password
38
39 }).then(newUser => {
40 res.send("newUser saved to database")
41 // `req.user` contains the authenticated user.
42 //TODO : res.redirect('/profile/' + req.body.username);
43 })
44 .catch(err => {
45 console.log(err);
46 res.status(400).send("unable to save this newUser to database");
47 })
48
49 }
50
51}).catch(err => {
52 console.log(err);
53 res.status(400).send("signup failed");
54})
55
56const bcrypt = require("bcrypt-nodejs");
57
58module.exports = (sequelize, DataTypes) => {
59 // TABLE USERS
60 const Users = sequelize.define('users', {
61
62 user_id: {
63 type: DataTypes.INTEGER,
64 primaryKey: true,
65 autoIncrement: true
66 },
67 username: {
68 type: DataTypes.STRING,
69 allowNull: false,
70 unique: true
71 },
72 name: {
73 type: DataTypes.STRING,
74 allowNull: false
75 },
76 firstname: {
77 type: DataTypes.STRING,
78 allowNull: false
79 },
80 email: {
81 type: DataTypes.STRING,
82 allowNull: false,
83 unique: true,
84 validate: {
85 isEmail: true
86 }
87 },
88 type: {
89 type: DataTypes.STRING,
90 allowNull: false,
91 },
92 location: {
93 type: DataTypes.STRING
94 },
95 password: {
96 type: DataTypes.STRING,
97 allowNull: false
98 }
99 });
100
101 // methods ======================
102 // generating a hash
103 Users.generateHash = function (password) {
104 return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
105 };
106
107 // checking if password is valid
108 Users.validPassword = function (password) {
109 return bcrypt.compareSync(password, this.password);
110 };
111
112 //hashing a password before saving it to the database
113 Users.beforeCreate('save', function (next) {
114 var user = this;
115 bcrypt.hash(user.password, 10, function (err, hash) {
116 if (err) {
117 return next(err);
118 }
119 user.password = hash;
120 next();
121 })
122 });
123
124 return Users;
125};
126
127// load all the things we need
128var LocalStrategy = require('passport-local').Strategy;
129var db = require('../db')
130
131// expose this function to our app using module.exports
132module.exports = function (passport) {
133
134 var User = db.users;
135 // =========================================================================
136 // passport session setup ==================================================
137 // =========================================================================
138 // required for persistent login sessions
139 // passport needs ability to serialize and unserialize users out of session
140
141 // used to serialize the user for the session
142 passport.serializeUser(function (user, done) {
143 done(null, user.id);
144 });
145
146// used to deserialize the user
147passport.deserializeUser(function (id, done) {
148 User.find({
149 where: { user_id: user_id }
150 })
151 .then(function (user) {
152 done(err, user);
153 }).catch(function (err) {
154 return done(err);
155 })
156});
157
158
159 // =========================================================================
160 // LOCAL LOGIN =============================================================
161 // =========================================================================
162 // we are using named strategies since we have one for login and one for signup
163 // by default, if there was no name, it would just be called 'local'
164
165 passport.use('local-login', new LocalStrategy({
166 // by default, local strategy uses username and password, we will override with email
167 usernameField: 'email',
168 passwordField: 'password',
169 passReqToCallback: true // allows us to pass back the entire request to the callback
170 },
171 function (req, email, password, done) { // callback with email and password from our form
172
173 // find a user whose email is the same as the forms email
174 // we are checking to see if the user trying to login already exists
175 User.findOne({ email : email }, function (err, user) {
176 // if there are any errors, return the error before anything else
177 if (err)
178 return done(err);
179
180 // if no user is found, return the message
181 if (!user)
182 return done(null, false, { message: 'User not found.' }); // req.flash is the way to set flashdata using connect-flash
183 // if the user is found but the password is wrong
184 if (!user.validPassword(password))
185 return done(null, false, { message: 'Incorrect password.' }); // create the loginMessage and save it to session as flashdata
186
187 // all is well, return successful user
188 return done(null, user);
189 });
190
191 }));
192
193};
194
195User.findOne({
196 email: email
197 })
198 .then(function(user) {
199 if (!user)
200 return done(null, false, {
201 message: 'User not found.'
202 }); // req.flash is the way to set flashdata using connect-flash
203 // if the user is found but the password is wrong
204 if (!user.validPassword(password))
205 return done(null, false, {
206 message: 'Incorrect password.'
207 }); // create the loginMessage and save it to session as flashdata
208 })
209 .catch(function(err) {
210 return done(err);
211 })
212
213db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] })
214 .then(user=>{})
215 .catch(err=>{})