Skip to content

Commit

Permalink
Merge pull request #4 from theParadox42/auth
Browse files Browse the repository at this point in the history
Merge Breaking Changes
  • Loading branch information
theParadox42 authored Feb 7, 2020
2 parents 26220d5 + 353313f commit 8104019
Show file tree
Hide file tree
Showing 26 changed files with 2,180 additions and 159 deletions.
6 changes: 6 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DB=localhost
DB_USER=public
DB_PASS=123
PORT=8081
SECRET=EnCry&ting_InPr0gre&#+Do-N@t.mE&S=it|Up,Th%nK$.
ACCESS_CONTROL_ALLOW_ORIGIN=*
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Files to ignore
node_modules
.DS_Store
.manifest
.manifest
.env
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
language: node_js
node_js:
- 10
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/app.js"
}
]
}
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"files.exclude": {
"**/.git": false
}
}
28 changes: 26 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,26 @@
# escape-from-earth-backend
Backend part of escape from earth
# Escape From Earth Backend

[![Build Status](https://travis-ci.org/theParadox42/EFE-Backend.svg?branch=auth)](https://travis-ci.org/theParadox42/EFE-Backend)

This is the backend part of [escape from earth](https://escapefromearth.tk) that handles the community section of it. Changes are currently underway. `v1` is the version in use, but is about to be deprecated. `v2` is about to be released and brings a lot of great changes including user authentication, liking, disliking, and flagging levels, plus security boosts. The versions are available at escape-from-earth.herokuapp.com/v1%20OR%20v2

A api documentation is not released, so if you feel like you want to understand it, just contact me and I can guide you from there.

You are welcome to submit an issue or open up a pull request if you want.

Feel free to contact me [here](https://paradox42.tech/p/contact) if you have any questions or concerns.

## Setting Up On a Local Device
- Clone or download however desired onto a computer, with a terminal
- Make sure `node.js` and `npm` are installed
- Run `npm install`
- Create a file called `.env`
- Fill that file with the following info
```txt
DB=test_db
DB_USER=[EFE Mongo Atlas Username]
DB_PASS=[EFE Mongo Atlas Password]
PORT=3000
SECRET=W&@tEv%r_&ecR#t+Y0u.C{0O$e,I%-gR8!
ACCESS_CONTROL_ALLOW_ORIGIN=*
```
165 changes: 48 additions & 117 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,119 +1,50 @@
// Dependencies
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var http = require("http");
//==================
//== Dependencies ==
//==================
var _ = require("dotenv").config(),
express = require("express"),
app = express(),
mongoose = require("mongoose"),
mongooseConfig = require("./config/mongoose"),
levelRoutes = require("./routes/levels"),
authRoutes = require("./routes/users"),
indexRoutes = require("./routes/index"),
v1Routes = require("./deprecated/v1/app"),
passport = require("passport"),
LocalStrategy = require("passport-local").Strategy,
BearerStrategy = require("passport-http-bearer").Strategy,
bearerConfig = require("./config/passport-bearer"),
User = require("./models/user"),
cors = require("./middleware/cors"),
bodyParser = require("body-parser");

// Mongoose
mongoose.connect("mongodb+srv://public:123@cluster0-baim8.gcp.mongodb.net/community_levels?retryWrites=true", { useNewUrlParser: true })
var Schema = mongoose.Schema;
var levelSchema = new Schema({
title: String,
type: String,
map: String,
level: [String],
objects: Object,
creator: String,
difficulty: Number
})
var Level = mongoose.model("Level", levelSchema);

// CORS
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
app.use(bodyParser.urlencoded({extended:true}));

// Get
app.get("/", function(req, res){
res.redirect("https://escapefromearth.tk")
})
app.get("/levels", function(req, res){
Level.find({}, function(err, levels){
if(err) {
console.log("Error Getting Levels: " + err);
res.send("Error");
} else {
res.send(levels);
}
})
});
app.get("/levels/new", function(req, res){
res.render("newLevel.ejs");
});

// Post
app.post("/levels/new", function(req, res){
var b = req.body;
var newLevel = {
title:b.title||"Untitled Level",
objects: b.objects||{},
type: b.type||"null",
map: b.map||"",
level: b.level||[],
creator: b.creator||"Anonymous",
difficulty: Math.min(Math.max(b.difficulty||1,1),10)
}
if(b._id){
Level.find({_id:b._id}, function(err, levels){
if(err) {
console.warn("Error finding match")
console.warn(err);
return;
}
if(!levels.length){
Level.create(newLevel, function(err, newLvl){
if(err){
console.warn("Error adding level")
console.warn(err);
} else {
res.send(newLvl);
}
});
} else {
Level.updateOne({_id:b._id}, {$set: newLevel}, function(err, updatedLevel){
if(err){
console.warn("Error Updating Level")
console.warn(err);
} else {
res.send(updatedLevel);
}
});
}
})
} else {
Level.create(newLevel, function(err, newLvl){
if(err){
console.warn("Error adding level")
console.warn(err);
} else {
res.send(newLvl);
}
});
}
});

// Run
var app_port = process.env.PORT || 8080;
app.listen(app_port, process.env.IP, function(){
console.log("API app started on port "+app_port);
})

/* took up too many Heroku hours
setInterval(function(){
http.get("http://escape-from-earth.herokuapp.com");
}, 250000)
*/

mongoose.connect(mongooseConfig.string, mongooseConfig.constructor);

// Passport Setup
app.use(passport.initialize())
passport.use(new LocalStrategy(User.authenticate()));
passport.use(new BearerStrategy(bearerConfig))
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// CORS Stuff
app.use(cors);

// Body Parser
app.use(bodyParser.urlencoded({ extended: true }));

// Routes
app.use("/v1", v1Routes);
app.use("/v2", authRoutes);
app.use("/v2/levels", levelRoutes);
app.use(indexRoutes);


//=================
//==== RUN APP ====
//=================
var appPort = process.env.PORT || 8080;
app.listen(appPort, process.env.IP, function(){
console.log(`Listening on port ${appPort}`);
});
11 changes: 11 additions & 0 deletions config/mongoose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const env = process.env;
// Configures it for mongo connection
module.exports = {
string: `mongodb+srv://${env.DB_USER}:${env.DB_PASS}@cluster0-baim8.gcp.mongodb.net/${env.DB}?retryWrites=true`,
constructor: {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
}
};
20 changes: 20 additions & 0 deletions config/passport-bearer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

var jwt = require("jsonwebtoken"),
User = require("../models/user");

module.exports = function (token, done) {

var decoded = jwt.verify(token, process.env.SECRET);

User.findOne({ _id: decoded.id, "tokens.token": token }, function (err, foundUser) {

if (err) {
return done(err)
}
if (!foundUser) {
return done(null, false);
}
return done(null, foundUser, token);
});

};
90 changes: 90 additions & 0 deletions deprecated/v1/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@

// I am NOT proud of this coding right here.


// Dependencies
var mongoose = require("mongoose");
var express = require("express");
var router = express.Router({ mergeParams: true });

// Mongoose
var Schema = mongoose.Schema;
var oldLevelSchema = new Schema({
title: String,
type: String,
map: String,
level: [String],
objects: Object,
creator: String,
difficulty: Number
})
var OldLevel = mongoose.model("OldLevel", oldLevelSchema);

// Get
router.get("/", function (req, res) {
res.send("Deprecated Routes")
})
router.get("/levels", function (req, res) {
OldLevel.find({}, function (err, levels) {
if (err) {
console.log("Error Getting Levels: " + err);
res.send("Error");
} else {
res.send(levels);
}
})
});

// Post New Level
router.post("/levels/new", function (req, res) {
var b = req.body;
var newLevel = {
title: b.title || "Untitled Level",
objects: b.objects || {},
type: b.type || "null",
map: b.map || "",
level: b.level || [],
creator: b.creator || "Anonymous",
difficulty: Math.min(Math.max(b.difficulty || 1, 1), 10)
}
if (b._id) {
OldLevel.find({ _id: b._id }, function (err, levels) {
if (err) {
console.warn("Error finding match")
console.warn(err);
return;
}
if (!levels.length) {
OldLevel.create(newLevel, function (err, newLvl) {
if (err) {
console.warn("Error adding level")
console.warn(err);
} else {
res.send(newLvl);
}
});
} else {
OldLevel.updateOne({ _id: b._id }, { $set: newLevel }, function (err, updatedLevel) {
if (err) {
console.warn("Error Updating Level")
console.warn(err);
} else {
res.send(updatedLevel);
}
});
}
})
} else {
OldLevel.create(newLevel, function (err, newLvl) {
if (err) {
console.warn("Error adding level")
console.warn(err);
} else {
res.send(newLvl);
}
});
}
});

module.exports = router;

Loading

0 comments on commit 8104019

Please sign in to comment.