2020-05-08 11:12:10 +00:00
|
|
|
const express = require('express');
|
|
|
|
const router = express.Router();
|
|
|
|
const bcrypt = require('bcryptjs');
|
|
|
|
|
|
|
|
const Account = require('../models/accountModel');
|
|
|
|
const { saltingRounds } = require('../../config/config');
|
2020-05-10 22:03:48 +00:00
|
|
|
const { generateToken } = require('../../helpers/generateToken');
|
2020-05-08 11:12:10 +00:00
|
|
|
|
|
|
|
router.post('/register', async (req, res) => {
|
2020-05-09 12:58:22 +00:00
|
|
|
const data = req.body;
|
2020-05-08 11:12:10 +00:00
|
|
|
data.password = bcrypt.hashSync(data.password, saltingRounds);
|
|
|
|
|
|
|
|
try {
|
|
|
|
const [user] = await Account.addAccount(data);
|
|
|
|
const token = generateToken(user);
|
|
|
|
res.status(201).json({ user, token });
|
|
|
|
} catch (error) {
|
|
|
|
res.status(500).json({
|
|
|
|
message: `Failed to add new account.`,
|
|
|
|
error,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
router.post('/login', async (req, res) => {
|
|
|
|
let { email, password } = req.body;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const user = await Account.getAccountByEmail(email);
|
|
|
|
|
|
|
|
if (bcrypt.compareSync(password, user.password)) {
|
|
|
|
const token = generateToken(user);
|
2020-05-09 12:58:22 +00:00
|
|
|
delete user.password;
|
2020-05-08 11:12:10 +00:00
|
|
|
res.status(200).json({
|
2020-05-09 12:58:22 +00:00
|
|
|
user,
|
2020-05-08 11:12:10 +00:00
|
|
|
token,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
throw new Error();
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
res.status(401).json({
|
2020-05-10 22:03:48 +00:00
|
|
|
message: `Invalid credentials`,
|
2020-05-08 11:12:10 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
module.exports = router;
|