Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,20 @@
> Request (Get All: /locations , Get One: /locations/:id)
> Delete: /locations/:id
> ```
## .ENV

Le fichier .env contient une variable MONGO_URI avec le lien de la database MongoDB, ainsi qu'une variable SECRET_JWT avec une clé qui dans mon cas a été secret

## Pour utiliser l'API
lancer index.js
Puis sur insomnia
Pour se register : ajouter un body JSON à la requête
Pour se log mettez le même body JSON qui a été registered
Tout utilisateur créé est user //il n'est pas possible de créé un admin
Puis copier le token qui est retourné
Ajouter une Authorization "Bearer Token" et coller le token pour les autres fonction qui nécessite d'etres connecter

## SonarCloud

https://sonarcloud.io/summary/new_code?id=tristrat_secure-web-dev-workshop3

16 changes: 13 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
const express = require('express')
const locationController = require('./locations/locations.controller')
const userController = require('./user/users.controller')
const app = express()
const port = 3000
const mongoose = require('mongoose')
require('dotenv').config()
require('./strategy/strategy.local');
require('./strategy/strategy.jwt');
require('./middleware/middleware.strategy');
const bodyParser = require('body-parser')


app.use(bodyParser.json())
app.use(locationController)

app.listen(port, () => {
app.use(userController)
app.listen(port, async () => {
await mongoose.connect(process.env.MONGO_URI);
console.log("Connect");
console.log(`API listening on port ${port}, visit http://localhost:${port}/`)
})
})
61 changes: 55 additions & 6 deletions locations/locations.controller.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,61 @@
// This file is used to map API calls (Presentation Layer) with the
// Business-Logic layer

const router = require('express').Router()
const locationsService = require('./locations.service')
const Location = require("./locations.model")
const {addLocation} = require("./locations.service");

require('../strategy/strategy.jwt');

router.get('/', (req, res) => {
return res.status(200).send("Hello World")
})

router.get('/locations', async(req, res) => {
const locations = await Location.find()
return res.status(200).send(locations)
})

router.get('/locations/:id', async(req,res) =>{
try{
const location = await locationsService.findOne(req.params['id'])
return res.status(200).send(location)
}catch(e){
if(e.message==="Not found"){
return res.status(404).send(e.toString())
}
return res.status(500).send("Bad request")
}
})

router.get('/locations', (req, res) => {
return res.status(200).send({locations: []})
router.post('/locations', async (req,res, next) =>{
try{
const location = locationsService.addLocation({...req.body, endDate:new Date(req.body.endDate), startDate: new Date(req.body.startDate)})
return res.status(200).send(location)
}catch(e) {
return res.stat
}
})


module.exports = router
router.delete('/locations/:id', async (req,res)=>{
try{
const location = await locationsService.deleteById(req.params.id)
return res.status(200).send(location)
}catch(e){
if(e.message==="Not found"){
return res.status(404).send(e.toString())
}
return res.status(500).send("Bad request")
}
})
router.put('/locations/:id', async (req,res)=>{
try{
const location = await locationsService.updateLocation(req.params.id, {...req.body, endDate:new Date(req.body.endDate), startDate: new Date(req.body.startDate)})
return res.status(200).send(location)
}catch(e){
if(e.message==="Not found"){
return res.status(404).send(e.toString())
}
return res.status(500).send("Bad request")
}
})
module.exports = router
52 changes: 48 additions & 4 deletions locations/locations.service.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,53 @@
// This file holds the Business-Logic layer, interacting with Data Layer

const Location = require('./locations.model')

function findAll () {
return [1,2,3,4]
async function findAll () {
try {
const response = await Location.find();
return response;
} catch (error) {
console.log("location doesn't exist");
console.log(error);
}
}

async function findOne(id){
const location = await Location.findById(id)
if(!location)
throw new Error("Not found")
return location;
}

function addLocation(data){
try{
const location = new Location(data)
location.save()
}catch(e){
throw new Error("Wrong data")
}
return location
}

function deleteByID(id){
const location = Location.findById( {_id : id})
if(!location)
throw new Error("Not found")
else
Location.deleteOne({_id: id})
return location
}


function updateLocation(id, update){
const location = Location.findOne({ _id: id });
if(!location)
throw new Error("Not found")
else
Location.updateOne({_id:id})
return location
}

module.exports.updateLocation = updateLocation;
module.exports.findOne = findOne
module.exports.findAll = findAll
module.exports.addLocation = addLocation;
module.exports.deleteById = deleteByID;
32 changes: 32 additions & 0 deletions locations/locations.service.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

const locationsService = require('./locations.service')
const Location = require('./locations.model')

jest.mock('./locations.model')

describe('Location FindAll',()=>{
it('Should call model find',async()=>{
Location.find.mockResolvedValue([1,2,3,4])
await locationsService.findAll()
expect(Location.find).toHaveBeenCalledTimes(1)
})
})


describe('Location FindOne',() =>{
it('Should get a Location',async ()=>{
jest.resetAllMocks()
const mockLocation = {_id: '12345678', filmName: 'fifi brin dacier'}
Location.findById.mockResolvedValue(mockLocation)
expect(await locationsService.findOne('12345678')).toEqual(mockLocation)
expect(Location.findById).toHaveBeenCalledWith('12345678')///rajouter un reset du conteur
})
it('Should get an error',async ()=>{
jest.resetAllMocks()
const mockLocation = null
Location.findById.mockResolvedValue(mockLocation)
expect(async ()=> await locationsService.findOne('12345678')).rejects.toThrow()
expect(Location.findById).toHaveBeenCalledTimes(1)
})
})

8 changes: 8 additions & 0 deletions middleware/middleware.strategy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const roleMiddleware = (allowedRoles = []) => (req, res, next) => {
if (!allowedRoles || allowedRoles === []) return;
if (!req.user?.role) return res.status(401).send(); // No user
if (!allowedRoles.includes(req.user.role)) return res.status(403).send(); // No role
next();
}

module.exports.roleMiddleware = roleMiddleware;
Loading