Add security layer.

This commit is contained in:
2020-09-26 12:41:12 +02:00
parent 5e6da61ccb
commit fae622aafc
8 changed files with 159 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
const express = require('express');
const bodyParser = require('body-parser');
const applicationController = require('./controller/applicationCtrl');
const userController = require('./controller/userCtrl');
const port = 3000;
@@ -9,5 +10,6 @@ app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/apps', applicationController);
app.use('/users', userController);
app.listen(port, () => console.log('Mock is listening at port ', port, '\n'));

View File

@@ -0,0 +1,21 @@
const router = require('express').Router();
const Jwt = require('../jwtService');
const userService = require('../service/userService');
const passwordService = require('../service/passwordService');
// Develop routes here
router.post('/login', (request, response) => {
const loginRequest = request.body;
// If login is incorrect, the "getUser" function will return "undefined".
// So if "user" is not "undefined", this proofs that login is correct.
const user = userService.getUser(loginRequest.login);
if (!!loginRequest && !!user && passwordService.areSamePasswords(loginRequest.password, user.password)) {
const tokenPayload = { login: loginRequest.login };
response.json(Jwt.buildToken(tokenPayload));
} else {
response.status(403).send();
}
});
module.exports = router;

19
src/js/jwtService.js Normal file
View File

@@ -0,0 +1,19 @@
const jwt = require('jsonwebtoken');
class Jwt {
buildToken(tokenPayload) {
return jwt.sign(tokenPayload, 'secret', {expiresIn: '1h'});
}
isTokenValid(token) {
try {
jwt.verify(token, 'secret');
} catch (exception) {
return false;
}
return true;
}
}
const jwtInstance = new Jwt();
module.exports = jwtInstance;

View File

@@ -5,7 +5,6 @@ const mongoConfig = configuration.database;
class MongoClient {
constructor() {
mongodb.MongoClient.connect(mongoConfig.url, (error, client) => {
console.log(error);
if (error !== null) {
throw new Error(`Unable de connect to Mongo database: ${error}`);
}

View File

@@ -0,0 +1,16 @@
const bcrypt = require('bcrypt');
const saltRounds = 10;
class PasswordService {
hashPassword(password) {
const salt = bcrypt.genSaltSync(saltRounds);
return bcrypt.hashSync(password, salt);
}
areSamePasswords(plainTextPassword, hashedPassword) {
return bcrypt.compareSync(plainTextPassword, hashedPassword);
}
}
const singleton = new PasswordService();
module.exports = singleton;

View File

@@ -0,0 +1,19 @@
const Repository = require('../repository/repository');
const passwordService = require('./passwordService');
const userRepository = new Repository('users');
class UserService {
getUser(login) {
return login === 'toto'
? {login: 'toto', password: passwordService.hashPassword('pwd')}
: undefined;
}
isAuthenticated() {
return false;
}
}
const singleton = new UserService();
module.exports = singleton;