Skip to content

Commit ece5970

Browse files
committed
user controller finished
1 parent 14bc569 commit ece5970

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

server/controllers/userController.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,61 @@
1+
// middleware functions create a new user and verify users
2+
13
const Users = require('../models/userModels');
4+
5+
const userController = {};
6+
const bcrypt = require('bcryptjs');
7+
8+
userController.createUser = (req, res, next) => {
9+
const { username, password } = req.body;
10+
// error handling if username or password is missing
11+
if (!username || !password) {
12+
return next('Missing username or password in userController.createUser');
13+
}
14+
const projects = [];
15+
// create user using username and password
16+
Users.create({ username, password, projects }, (err, newUser) => {
17+
if (err) {
18+
return next({
19+
log: `Error in userController.createUser: ${err}`,
20+
message: {
21+
err: `Error in userController.createUser. Check server logs for details`
22+
}
23+
});
24+
} else {
25+
// this id property will be used in other middleware for cookie
26+
res.locals.id = newUser.id;
27+
return next();
28+
}
29+
});
30+
};
31+
32+
// verifyUser - Obtain username and password from the request body, locate
33+
// the appropriate user in the database, and then authenticate the submitted password against the password stored in the database.
34+
35+
userController.verifyUser = (req, res, next) => {
36+
const { username, password } = req.body;
37+
Users.findOne({ username }, (err, user) => {
38+
if (err) {
39+
return next({
40+
log: `Error in userController.verifyUser: ${err}`,
41+
message: {
42+
err: `Error in userController.verifyUser, check server logs for details`
43+
}
44+
});
45+
} else {
46+
// bcrypt compare function checks input password against hashed password
47+
bcrypt.compare(password, user.password).then(isMatch => {
48+
if (isMatch) {
49+
// if password matches, save user id for following middleware
50+
res.locals.id = user.id;
51+
return next();
52+
} else {
53+
// if password does not match, redirect to ?
54+
res.redirect('/login');
55+
}
56+
});
57+
}
58+
});
59+
};
60+
61+
module.exports = userController;

server/models/sessionModel.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,4 @@ const sessionSchema = new Schema({
66
createdAt: { type: Date, expires: 3600, default: Date.now }
77
});
88

9-
const Session = mongoose.model('Sessions', sessionSchema);
9+
module.exports = mongoose.model('Sessions', sessionSchema);

0 commit comments

Comments
 (0)