Add authentication endpoints with logic

This commit is contained in:
ruihildt 2019-08-01 08:55:37 +02:00
parent 6c562ee7f6
commit d97221e522
5 changed files with 114 additions and 2 deletions

View File

@ -47,12 +47,15 @@ Sleep Tracker is intended for anyone interested in improving their sleep and hea
| average_mood | float | |
## API Endpoints
- `POST /api/users` - add a new user
- `POST /api/auth/register` - add a new user
- `POST /api/auth/login` - login with user/password
- `GET /api/users/:id` - fetch a user
- `PUT /api/users/:id` - update a user
- `GET /api/users/:id/sessions` - fetch list of all sessions by user id
- `POST /api/users/:id/sessions` - add a session y user id
- `POST /api/users/:id/sessions` - add a session by user id
- `GET /api/users/:id/sessions/:id` - fetch a single session by id
- `PUT /api/users/:id/sessions/:id` - update a session by id
- `DELETE /api/users/:id/sessions/:id` - delete a session by id

View File

@ -2,10 +2,14 @@ const express = require("express");
const helmet = require('helmet');
const cors = require('cors');
const authRouter = require('../services/auth/authRouter');
const server = express();
server.use(helmet());
server.use(express.json());
server.use(cors());
server.use('/api/auth', authRouter);
module.exports = server;

View File

@ -0,0 +1,43 @@
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, 10);
user.password = hash;
Users.add(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.findBy({ 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;

View File

@ -0,0 +1,37 @@
require("dotenv").config();
const jwt = require('jsonwebtoken');
const jwtKey = process.env.JWT_SECRET;
module.exports = {
authenticate,
generateToken
};
function authenticate(req, res, next) {
const token = req.get('Authorization');
if (token) {
jwt.verify(token, jwtKey, (err, decoded) => {
if (err) return res.status(401).json(err);
req.decoded = decoded;
next();
});
} else {
return res.status(401).json({
error: 'No token provided, must be set on the Authorization Header',
});
}
}
function generateToken(user) {
const payload = {
username: user.username
};
const options = {
expiresIn: '3d'
};
return jwt.sign(payload, jwtKey, options);
}

View File

@ -0,0 +1,25 @@
const db = require('../../data/dbConfig');
module.exports = {
add,
findBy,
findById,
};
function findBy(filter) {
return db('users')
.where(filter);
}
async function add(user) {
const [id] = await db('users')
.insert(user);
return findById(id);
}
function findById(id) {
return db('users')
.where({ id })
.first()
.select('id', 'email', 'username');
}