49 lines
1.1 KiB
JavaScript
49 lines
1.1 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const bcrypt = require('bcryptjs');
|
|
|
|
const Account = require('../models/accountModel');
|
|
const { saltingRounds } = require('../../config/config');
|
|
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({
|
|
message: `Invalid credentials`,
|
|
});
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|