Skip to content
Snippets Groups Projects
Commit cc7553b4 authored by MrJoshE's avatar MrJoshE
Browse files

Made database use async/await pattern and fixed deleting parkling locations

parent 4064a205
No related branches found
No related tags found
No related merge requests found
REACT_APP_GOOGLE_MAPS_API_KEY = "AIzaSyBjY11PT3iGwoczzs6zNw7ot0rsWCVWBDU" DB_URL=mongodb+srv://user:WsfePqVVojP4lgZk@locationservice.dqljyov.mongodb.net/ParkingLocations?retryWrites=true&w=majority
REACT_APP_MONGO_URI_LOCAL = "mongodb://localhost:27017/ParkingLocations" PORT=3002
USERNAME= "user" JWT_SECRET=pZnf1tK5NNWfgv6NlWpHVCk/+pFQxIzIdKec8JTn+GA=
PASSWORD= "WsfePqVVojP4lgZk" \ No newline at end of file
\ No newline at end of file
Source diff could not be displayed: it is too large. Options to address this: view the blob.
...@@ -7,19 +7,12 @@ ...@@ -7,19 +7,12 @@
"author": "Jason J Dookarun", "author": "Jason J Dookarun",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"assert": "^2.0.0",
"axios": "^1.3.5",
"body-parser": "^1.18.3", "body-parser": "^1.18.3",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"express": "^4.18.2", "express": "^4.18.2",
"geolib": "^3.3.3",
"jest": "^29.5.0",
"jsonwebtoken": "^9.0.0",
"jwt-simple": "^0.5.6", "jwt-simple": "^0.5.6",
"mongoose": "^5.3.16", "mongoose": "^7.0.3",
"morgan": "^1.9.1", "cors": "^2.8.5"
"node-geocoder": "^4.2.0",
"nodemon": "^1.18.4"
}, },
"scripts": { "scripts": {
"start": "node src/App.js" "start": "node src/App.js"
......
const express = require('express'); const express = require('express');
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const { MONGO_URI_LOCAL, API_KEY} = APIKeyAccess(); const cors = require('cors');
require('dotenv').config(); require('dotenv').config();
const app = express(); const app = express();
const port = 3000;
const ParkingLocation = require('./model/ParkingLocation'); const ParkingLocation = require('./model/ParkingLocation');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken'); const jwt = require('jwt-simple');
const geolib = require('geolib');
const axios = require('axios');
const { MongoClient, ServerApiVersion } = require('mongodb');
const username = process.env.USERNAME;
const password = process.env.PASSWORD;
function APIKeyAccess() {
const API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;
//const MONGO_URI_LOCAL = process.env.MONGO_URI_LOCAL;
// const MONGO_URI = "mongodb://localhost:27017/ParkingLocations";
return { API_KEY };
}
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(cors());
const MONGO_URI = `mongodb+srv://${username}:${password}@locationservice.dqljyov.mongodb.net/ParkingLocations?retryWrites=true&w=majority`; const port = process.env.PORT;
const JWT_ALGORITHM = 'HS512';
mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('🤖: Successfully connected to:', MONGO_URI);
}).catch((x) => {
console.error(x);
console.log('⛔️ Database Error: An error has occured, please try again later');
});
const user = { id: 123, isAdmin: true };
const token = jwt.sign(user, 'secret', { algorithm: 'HS512' });
console.log('🤖 Admin Token:', token)
app.get('/parking-locations', async (request, response) => { app.get('/location/parking-locations', async (request, response) => {
try { try {
const parkingLocations = await ParkingLocation.find({}); const parkingLocations = await ParkingLocation.find({});
console.log(`🤖: Successfully retrieved all ${parkingLocations.length} parking locations:`); console.log(`🤖: Successfully retrieved all ${parkingLocations.length} parking locations:`);
...@@ -58,7 +32,7 @@ function isAdmin(request, response, next) { ...@@ -58,7 +32,7 @@ function isAdmin(request, response, next) {
return; return;
} }
try { try {
const user = jwt.verify(token, 'secret'); const user = jwt.decode(token, process.env.JWT_SECRET, false, JWT_ALGORITHM);
if (user && user.isAdmin) { if (user && user.isAdmin) {
console.log('🤖: User is admin, proceed.') console.log('🤖: User is admin, proceed.')
request.user = user; request.user = user;
...@@ -72,7 +46,7 @@ function isAdmin(request, response, next) { ...@@ -72,7 +46,7 @@ function isAdmin(request, response, next) {
} }
} }
app.post('/parking-locations', isAdmin, async (request, response) => { app.post('/location/parking-locations', isAdmin, async (request, response) => {
try { try {
const { Title, Description,city, street_address, postcode, lat, lon, spaces_available, total_spaces } = request.body; const { Title, Description,city, street_address, postcode, lat, lon, spaces_available, total_spaces } = request.body;
...@@ -102,21 +76,46 @@ app.post('/parking-locations', isAdmin, async (request, response) => { ...@@ -102,21 +76,46 @@ app.post('/parking-locations', isAdmin, async (request, response) => {
}); });
app.delete('/parking-locations/:id', isAdmin, async (request, response) => { app.delete('/location/parking-locations/:id', async (request, response) => {
try { try {
const parkingLocation = await ParkingLocation.findById(request.params.id); const parkingLocation = await ParkingLocation.findByIdAndDelete(request.params.id);
if (!parkingLocation) { if (!parkingLocation) {
response.status(404).json({ error: '⛔️: Parking spot not found.' }); response.status(404).json({ error: '⛔️: Parking spot not found.' });
return; return;
} }
await parkingLocation.remove();
response.json({ message: '🤖: Parking spot deleted.' }); response.json({ message: '🤖: Parking spot deleted.' });
} catch (x) { }
catch (x) {
console.error(x); console.error(x);
response.status(500).json({ error: '⛔️: Failed to delete parking spot, please try again later.' }); response.status(500).json({ error: '⛔️: Failed to delete parking spot, please try again later.' });
} }
}); });
app.listen(port, () => {
console.log(`🤖: Now tuning into http://localhost:${port}`); (async ()=>{
});
// Connect to the MongoDB database
const databaseUrl = process.env.DB_URL;
if (!databaseUrl) {
console.error('⚡️[server]: Database url not found. Please set the DB_URL environment variable.');
return;
}
try {
console.log("Connecting to database: " + databaseUrl);
await mongoose.connect(databaseUrl);
}
catch (e) {
console.log('⛔️ Database Error: An error has occured, please try again later');
console.log(e);
// Do not continue if we cannot connect to the database
return;
}
console.log('🤖: Successfully connected to:', databaseUrl);
app.listen(port, () => {
console.log(`🤖: Now tuning into http://localhost:${port}`);
});
})();
const jwt = require('jsonwebtoken'); const jwt = require('jwt-simple');
const user = { id: 0101010101, isAdmin: true }; const user = { id: 0101010101, isAdmin: true };
const token = jwt.sign(user, 'secret'); const token = jwt.encode(user, 'secret');
console.log(token); console.log(token);
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment