backend/api/routes/authRoute.js

49 lines
1.1 KiB
JavaScript
Raw Normal View History

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');
router.post('/register', async (req, res) => {
const data = req.body;
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);
delete user.password;
res.status(200).json({
user,
token,
});
} else {
throw new Error();
}
} catch (error) {
res.status(401).json({
2020-05-10 22:03:48 +00:00
message: `Invalid credentials`,
});
}
});
module.exports = router;