Skip to content

Commit

Permalink
first github commit after split
Browse files Browse the repository at this point in the history
  • Loading branch information
evabat committed Mar 15, 2020
1 parent 436402e commit 5ca8adf
Show file tree
Hide file tree
Showing 12 changed files with 679 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/package-lock.json
/.env

# testing


# production


# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

#IDE
.idea
npm-debug.log*
yarn-debug.log*
yarn-error.log*
5 changes: 5 additions & 0 deletions config/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
mongoURI: process.env.MONGODB_URI,
secretOrKey: "secret"
};

24 changes: 24 additions & 0 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const mongoose = require("mongoose");
const User = mongoose.model("users");
const keys = require("../config/keys");

const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;

module.exports = passport => {
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
})
);
};
92 changes: 92 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");

const users = require("./routes/users");
const paths = require("./routes/paths");

const app = express();

// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));

// Passport middleware
app.use(passport.initialize());

// Passport config
require("./config/passport")(passport);

// Path model
require('./models/Path');

// Routes
app.use("/api/users", users);

require('./routes/paths')(app);



const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server up and running on port ${port} !`));




// // index.js
//
// const express = require('express');
// const mongoose = require('mongoose');
// const MongoClient = require('mongodb').MongoClient;
//
// // mongoose.set('debug', true);
//
// // IMPORT MODELS
// require('./models/Path');
//
//
// const app = express();
// mongoose.Promise = global.Promise;
// mongoose.connect((process.env.MONGODB_URI || `mongodb+srv://admin:[email protected]/dbProject?retryWrites=true&w=majority`), {useNewUrlParser: true, useUnifiedTopology: true});
// const bodyParser = require('body-parser');
//
//
// app.use(bodyParser.json());
//
// //IMPORT ROUTES
// require('./routes/paths')(app);
//
//
// if (process.env.NODE_ENV === 'production') {
// app.use(express.static('../atrappos-client/build'));
//
// const path = require('path');
// app.get('*', (req,res) => {
// res.sendFile(path.resolve(__dirname, '../atrappos-client', 'build', 'index.html'))
// })
//
// }
//
// const PORT = process.env.PORT || 5000;
// app.listen(PORT, () => {
// console.log(`app running on port ${PORT}`)
// });

37 changes: 37 additions & 0 deletions models/Path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// /models/Path.js

const mongoose = require('mongoose');
const {Schema} = mongoose;

const featureSchema = new Schema({
_featureId: Schema.Types.ObjectId,
type: { type: String },
properties: {
hardship: { type: String },
difficulty: { type: String },
category: { type: String },
},
geometry: {
type: { type: String },
coordinates: {type: Array}
}
});


const pathSchema = new Schema({
_id: Schema.Types.ObjectId,
userId: { type: String },
type: { type: String },
name: { type: String },
description: { type: String},
features: [featureSchema],
created: { type: Date },
edited: [{ type: Date}],
device: { type: String }
});





module.exports = Path = mongoose.model('paths', pathSchema);
25 changes: 25 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const mongoose = require("mongoose");
const Path = require("../models/Path");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});

module.exports = User = mongoose.model("users", UserSchema);
30 changes: 30 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "atrappos-server",
"version": "1.0.0",
"description": "back-end for atrappos map app",
"main": "index.js",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"concurrently": "^5.0.1",
"express": "^4.17.1",
"is-empty": "^1.2.0",
"jsonwebtoken": "^8.3.0",
"moment": "^2.24.0",
"mongoose": "^5.8.0",
"nodemon": "^2.0.1",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"validator": "^10.9.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1 ",
"server": "nodemon index.js",
"client": "npm run start --prefix ../atrappos-client",
"dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\"",
"start": "node index.js"
},
"author": "evabat",
"license": "ISC"
}
148 changes: 148 additions & 0 deletions routes/paths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// /routes/pathRoute.js

const moment = require('moment');

const mongoose = require('mongoose');
const jwt = require("jsonwebtoken");

// Load Path model
const Path = require("../models/Path");

module.exports = (app) => {
app.get(`/api/paths`, async (req, res) => {
try {
const paths = await Path.find({});
return res.status(200).send(paths);
} catch (err) {
return res.status(500).json({ message: err.message })
}
});

app.get(`/api/path`, async (req, res) => {
const id = req.query.id;
try {
const path = await Path.findById(id)
return res.status(200).send(path);
} catch (err) {
return res.status(500).json({ message: err.message })
}
});

app.post(`/api/path`, async (req, res) => {
//get the token from the header if present
const token = req.headers["x-access-token"] || req.headers["authorization"];
//if no token found, return response (without going to the next middelware)
if (!token) return res.status(401).send("Access denied. No token provided.");
try {
//if can verify the token, set req.user and pass to next middleware
const decoded = jwt.decode(token.replace("Bearer ", ""));
const currentTime = Date.now() / 1000; // to get in milliseconds
if (decoded.exp < currentTime) {
res.status(401).send("Unauthorized token");
} else {
let tmpPath = req.body;
tmpPath.userId = decoded.id;
tmpPath._id = mongoose.Types.ObjectId();
let path = new Path(tmpPath);
path.created = moment();
path.edited = [];
path.save(function (err, path) {
if (err) return console.error(err);
console.log(path.name + " saved to paths collection.");
return res.status(201).send({
error: false,
path
})
});
}
} catch (ex) {
//if invalid token
res.status(400).send("Invalid token.");
}
});

app.put(`/api/path`, async (req, res) => {
//get the token from the header if present
const token = req.headers["x-access-token"] || req.headers["authorization"];
//if no token found, return response (without going to the next middleware)
if (!token) return res.status(401).send("Access denied. No token provided.");
try {
//if can verify the token, set req.user and pass to next middleware
const decoded = jwt.decode(token.replace("Bearer ", ""));
const currentTime = Date.now() / 1000; // to get in milliseconds
if (decoded.exp < currentTime) {
res.status(401).send("Unauthorized token");
} else {
let path = req.body;
const id = req.query.id;
let edited = path.edited;
edited.push(moment());
path.edited = edited;
if (!id) {
res.status(400).send("Bad request");
} else {
Path.findByIdAndUpdate(id, {$set:path},function (err) {
if (err) return console.error(err);
console.log(path.name + " modified and saved to paths collection.");
return res.status(201).send({
error: false,
path
})
});
}
}
} catch (ex) {
//if invalid token
res.status(400).send("Invalid token.");
}

});



// app.put(`/api/path/:id`, async (req, res) => {
// const {id} = req.params;
//
// let path = await Path.findByIdAndUpdate(id, req.body);
//
// return res.status(202).send({
// error: false,
// path
// })
//
// });

app.delete(`/api/path`, async (req, res) => {
//get the token from the header if present
const token = req.headers["x-access-token"] || req.headers["authorization"];
//if no token found, return response (without going to the next middleware)
if (!token) return res.status(401).send("Access denied. No token provided.");
try {
//if can verify the token, set req.user and pass to next middleware
const decoded = jwt.decode(token.replace("Bearer ", ""));
const currentTime = Date.now() / 1000; // to get in milliseconds
if (decoded.exp < currentTime) {
res.status(401).send("Unauthorized token");
} else {
const id = req.query.id;
if (!id) {
res.status(400).send("Bad request");
} else {
Path.findByIdAndDelete(id,function (err) {
if (err) return console.error(err);
console.log("The path with id " + id + " was deleted from collection.");
return res.status(201).send({
error: false,
id
})
});
}
}
} catch (ex) {
//if invalid token
res.status(400).send("Invalid token.");
}

});

};
Loading

0 comments on commit 5ca8adf

Please sign in to comment.