Implement auth with jwt and add endpoints

This commit is contained in:
2020-05-08 13:12:10 +02:00
parent fce5a162d3
commit 4b5a5b2477
8 changed files with 218 additions and 3 deletions

View File

@@ -3,10 +3,11 @@ const router = express.Router();
const bcrypt = require('bcryptjs');
const Account = require('../models/accountModel');
const { saltingRounds } = require('../../config/config');
router.post('/', async (req, res) => {
const data = { ...req.body };
const hash = bcrypt.hashSync(data.password, 14);
const hash = bcrypt.hashSync(data.password, saltingRounds);
data.password = hash;
try {
@@ -22,7 +23,7 @@ router.put('/:id', async (req, res) => {
const id = req.params.id;
if (data.password) {
const hash = bcrypt.hashSync(data.password, 14);
const hash = bcrypt.hashSync(data.password, 10);
data.password = hash;
}
@@ -78,4 +79,18 @@ router.get('/:id', async (req, res) => {
}
});
router.get('/:email', async (req, res) => {
const email = req.params.email;
try {
const account = await Account.getAccountByEmail(email);
res.status(200).json(account);
} catch (error) {
res.status(500).json({
message: `Account with ${email} doesn't exist.`,
error,
});
}
});
module.exports = router;

48
api/routes/authRoute.js Normal file
View File

@@ -0,0 +1,48 @@
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/authJwt');
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);
res.status(200).json({
message: `Welcome ${user.username}!`,
token,
});
} else {
throw new Error();
}
} catch (error) {
res.status(401).json({
message: `Invalid Credentials`,
});
}
});
module.exports = router;