aboutsummaryrefslogtreecommitdiff
path: root/server/controllers
diff options
context:
space:
mode:
authorMateja <mail@matejamaric.com>2021-07-10 22:57:13 +0200
committerMateja <mail@matejamaric.com>2021-07-10 22:57:13 +0200
commit54677c68f50b7c105a1f6cc5e9593877781fc8d6 (patch)
tree8998a76fdd76ca1170dc89cbf70423aeaf0efb0c /server/controllers
parentfd0fafa68d638b729a506ba668165e29eea71a49 (diff)
downloadmevn-ecommerce-54677c68f50b7c105a1f6cc5e9593877781fc8d6.tar.gz
mevn-ecommerce-54677c68f50b7c105a1f6cc5e9593877781fc8d6.zip
Implemented JWT authentication using Passport.js
Diffstat (limited to 'server/controllers')
-rw-r--r--server/controllers/user.js47
1 files changed, 47 insertions, 0 deletions
diff --git a/server/controllers/user.js b/server/controllers/user.js
new file mode 100644
index 0000000..e3c1078
--- /dev/null
+++ b/server/controllers/user.js
@@ -0,0 +1,47 @@
+const bcrypt = require('bcryptjs');
+const jwt = require('jsonwebtoken');
+
+const User = require('../models/User');
+const {masterKey} = require("../config/env");
+
+module.exports = {
+
+ register(req, res) {
+ if (req.body.password !== req.body.confirmPassword)
+ res.json({status: "Passwords do not match!"});
+ else {
+ const newUser = new User({
+ firstname: req.body.firstname,
+ lastname: req.body.lastname,
+ email: req.body.email,
+ password: bcrypt.hashSync(req.body.password)
+ });
+
+ newUser.save()
+ .then(() => res.json({status: "User successfully registered!"}))
+ .catch(err => res.json({
+ status: "Error when registering user!",
+ error: err
+ }));
+ }
+ },
+
+ login(req, res) {
+ User.findOne({email: req.body.email}, (err, user) => {
+ if (err)
+ res.json({status: "Database error.", error: err});
+
+ if (!bcrypt.compareSync(req.body.password, user.password))
+ res.json({status: "Wrong credentials!"});
+ else {
+ const payload = {sub: user._id};
+ const token = jwt.sign(payload, masterKey, {expiresIn: "1d"});
+ res.json({
+ status: "Successfully logged in!",
+ token
+ });
+ }
+ });
+ }
+
+};