sleep-tracker-backend/services/auth/authRouter.js

45 lines
1006 B
JavaScript

require("dotenv").config();
const router = require('express').Router();
const bcrypt = require('bcryptjs');
const { generateToken } = require('../auth/authenticate');
const Users = require('../users/usersModel');
router.post('/register', (req, res) => {
let user = req.body;
const hash = bcrypt.hashSync(user.password, process.env.SECRET, 10);
user.password = hash;
Users.addUser(user)
.then(saved => {
res.status(201).json(saved);
})
.catch(error => {
res.status(500).json(error);
});
});
router.post('/login', (req, res) => {
let { username, password } = req.body;
Users.findUserBy({ username })
.first()
.then(user => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user);
res.status(200).json({
message: `Welcome ${user.username}!`,
token
});
} else {
res.status(401).json({ message: 'Invalid Credentials' });
}
})
.catch(error => {
res.status(500).json(error);
});
});
module.exports = router;