Skip to content

Commit

Permalink
Merge pull request #16 from renanlopescoder/v2.1.0
Browse files Browse the repository at this point in the history
v2.1.0
  • Loading branch information
renanlopescoder authored Feb 8, 2018
2 parents 957f89d + addcf17 commit 9fc3995
Show file tree
Hide file tree
Showing 12 changed files with 134 additions and 221 deletions.
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: pm2 start server.js && pm2 logs all
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

## Node API

Application in Node, Express, MongoDB and PM2 to give support to Front End development, this application serving a bunch of AJAX requests to give and manipulate data from database.
### Description
Node API is production ready and open source project in Node, Express and MongoDB

### Support
This application is hosted on Heroku and serve a bunch of AJAX requests to give and manipulate data from database and give a support to test front end applications

### Showcase

Expand All @@ -12,7 +16,6 @@ Application in Node, Express, MongoDB and PM2 to give support to Front End devel
|https://typescript-angular4.herokuapp.com/ | https://github.com/renanlopescoder/typescript-angular4 |
|http://mobx-react.herokuapp.com/ | https://github.com/renanlopescoder/mobx-react |


## Routes

#### Projects
Expand Down Expand Up @@ -73,23 +76,27 @@ Application in Node, Express, MongoDB and PM2 to give support to Front End devel
- Routes ```./src/routes```
- Models ```./src/models```
- Actions ```./src/actions```
- Services ```./src/services```
- Configurations of Express ```./config/express.js```
- Database configurations ```./config/database.js```
- Server configurations ```./server.js```

## Configuring the API locally

- Download or clone the project access the project folder with the terminal and execute the CLI <code>npm install</code>.
- Run the server <code>npm start</code> (Nodemon)
- Access in your browser <a href="http://localhost:3000">http://localhost:3000</a>
- Download or clone the project access the project folder with the terminal and execute the CLI <code>npm install</code>
- Config your database in ```./congig/database.js``` change ```mongoose.connect('mongodb://localhost/yourDatabaseName');```
- Run the server in development mode <code>npm run dev</code>
- <code>Ctrl + c</code> to exit of logs and run <code>pm2 kill</code> to kill all process of pm2
- Access in your browser <a href="http://localhost:3000/projects">http://localhost:3000/projects</a>

## API Dependencies

- Dependency express - <a href="https://www.npmjs.com/package/express">https://www.npmjs.com/package/express</a>
- Dependency body-parser - <a href="https://www.npmjs.com/package/body-parser">https://www.npmjs.com/package/body-parser</a>
- Dependency cors - <a href="https://www.npmjs.com/package/cors">https://www.npmjs.com/package/cors</a>
- Dependency express-load - <a href="https://www.npmjs.com/package/express-load">https://www.npmjs.com/package/express-load</a>
- Dependency consign - <a href="https://www.npmjs.com/package/consign">https://www.npmjs.com/package/consign</a>
- Dependency PM2 - <a href="http://pm2.keymetrics.io/">http://pm2.keymetrics.io/</a>
- Dependency mongoose - <a href="https://www.npmjs.com/package/mongoose">https://www.npmjs.com/package/mongoose</a>

By: <a href="http://renanlopes.com">Renan Lopes</a>

Expand Down
13 changes: 7 additions & 6 deletions config/express.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
const express = require('express');
const bodyParser = require('body-parser');
const load = require('express-load');
const cors = require('cors');
const consign = require('consign');
const server = express();

server.use(bodyParser.json());
server.set('secret', 'opensecret');
server.use(cors({ origin: '*' }));

load('src/models')
.then('src/actions')
.then('src/routes/auth.js')
.then('src/routes')
.into(server);
consign({cwd: process.cwd() + '/src'})
.include("models")
.then("actions")
.then("routes/auth.js")
.then("routes")
.into(server);

module.exports = server;
13 changes: 7 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
{
"name": "rest_api_node",
"version": "2.0.0",
"description": "NodeJS REST API is a open code NodeJS Back End API",
"name": "node_api",
"version": "2.1.0",
"description": "Node API is production ready and open source project in Node, Express, MongoDB and PM2",
"scripts": {
"dev": "pm2 start server.js --watch",
"preinstall": "npm i -g pm2 && pm2 install pm2-logrotate",
"dev": "pm2 start server.js --watch && pm2 logs",
"start": "node ./node_modules/.bin/pm2 start server.js"
},
"author": "Renan Lopes",
"license": "MIT",
"dependencies": {
"bcrypt": "^1.0.2",
"body-parser": "^1.15.2",
"consign": "^0.1.6",
"cors": "^2.8.3",
"express": "^4.14.0",
"express-load": "^1.1.16",
"jsonwebtoken": "^7.2.1",
"mongoose": "^4.7.1",
"nodemailer": "^4.2.0",
"pm2": "^2.9.3"
},
"engines": {
"node": "7.10.1"
"node": "8.9.4"
}
}
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ require('./config/database');
const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
console.log('Servidor Iniciado');
console.log(`Server running on port ${PORT}`);
});
66 changes: 18 additions & 48 deletions src/actions/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,21 @@ const saltRounds = 15;
const jwt = require('jsonwebtoken');
const model = mongoose.model('User');

/**
* Auth API para gerenciamento de autenticação de usuários
*
* Requires: Json Web Token, simple-encryptor, bcrypt e mongoose
* @description simple-encrytor usado para criptografar dados do usuário em localStorage e Json Web Token para autenticação do usuário no sistema.
*
* Modelo: user.js
* Nome: User
* Collection no MongoDB: users
* Atualização: EcmaScript 6
* Conceitos Aplicados: Criptografia unidirecional e bidirecional Arrow Functions e Variáveis com Escopo de Bloco.
*
*/

module.exports = (app) => {

let actions = {};
const SECRET = app.get('secret');

actions.login = (req, res) => {
model.findOne({ email: req.body.email })
.then(
(user) => {
const password = req.body.password;
const hash = user.password;
bcrypt.compare(password, hash, (error, success) => {
bcrypt.compare(req.body.password, user.password, (error, success) => {
if (error) {
console.log('Error, password mismatch with user ' + user.username);
res.sendStatus(401);
res.status(401).send({ error: error, message: 'Password mismatch'});
} else if (success) {
var token = jwt.sign({ user: user.username }, app.get('secret'),{
expiresIn: 84600
});
const token = jwt.sign({ user_id: user._id }, SECRET, { expiresIn: '3h' });
return res.status(200).json(
{
user_id: user._id,
nickname : user.nickname,
username: user.username,
photo : user.photo,
Expand All @@ -48,35 +28,25 @@ module.exports = (app) => {
);
};
});
},
(error) => {
console.log('Error, user does not exists');
res.sendStatus(401);
}
)
.catch(error => res.status(401).send({ error: error, message: 'Error, user does not exists' }))
};

actions.verifyToken = (req, res, next) => {
let token = req.get('Autorization');
if(token) {
console.log('Verificando Token');
jwt.verify(
token,
app.get('secret'),
(error, decoded) => {
if(error) {
console.log('Token Rejeitado');
res.sendStatus(401);
}
req.user = decoded;
console.log('Usuario aprovado');
next();
}
);
} else {
console.log('Token não enviado');
res.sendStatus(401);
}
const TOKEN = req.get('Authorization');
if (TOKEN) {
jwt.verify(TOKEN, SECRET, (error, decoded) => {
if (error) {
res.status(401).send({ error: error, message: 'Invalid Token' });
} else {
req.user = decoded;
next();
}
});
} else {
res.status(401).send('Token is required');
};
};

return actions;
Expand Down
70 changes: 19 additions & 51 deletions src/actions/project.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,66 +3,34 @@ const model = mongoose.model('Project');

let actions = {};

actions.list = function (req, res){
model.find({},function(error, list){
if(error){
res.status(500).json(error);
}
res.json(list);
});

actions.list = (req, res) => {
model.find({})
.then(projects => res.status(200).json(projects))
.catch(error => res.status(500).json(error))
};

actions.create = function(req, res){
model
.create(req.body).then(function(dados){
res.json(dados);
}, function(error){
console.log(error);
res.status(404).json(error);
});

actions.create = (req, res) => {
model.create(req.body)
.then(user => res.json(user))
.catch(error => res.status(500).json(error))
};

actions.searchById = function(req,res){

model
.findById(req.params.id)
.then(function(id){

res.json(id);

}, function(error){
console.log(error);
res.status(404).json(error);
});

actions.searchById = (req, res) => {
model.findById(req.params.id)
.then(project => res.status(200).json(project))
.catch(error => res.status(404).json(error))
};

actions.deleteById = function(req,res){
actions.deleteById = (req, res) => {
model.remove({_id: req.params.id})
.then(function(){
res.sendStatus(200);
}, function(error){
console.log(error);
res.status(404).json (error);
});

.then(() => res.status(200))
.catch(() => res.status(404).json(error))
};

actions.update = function(req,res){
console.log(req.body);
model
.findByIdAndUpdate(req.params.id, req.body)
.then(function(dado){

res.json(dado);

}, function(error){
console.log(error);
res.status(404).json(error);
});

actions.update = (req, res) => {
model.findByIdAndUpdate(req.params.id, req.body)
.then(project => res.status(200).json(project))
.catch(error => res.status(404).json(error))
};

module.exports = actions;
Loading

0 comments on commit 9fc3995

Please sign in to comment.