Skip to content

Feature ended work #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
package-lock.json
package-lock.json
.env
29 changes: 29 additions & 0 deletions FINAL REPORT README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
**FINAL REPORT**

The Final Task was finished

You can see the Postman Document for API access in
## **[API DOCUMENT](https://documenter.getpostman.com/view/10683014/TzecD5dB#91cd7156-7c27-5154-c562-ed94ff92ad2a)**

I use the the next APIs:

- [NASA API](https://api.nasa.gov/)
- [API del Servicio de Normalización de Datos Geográficos de Argentina](https://datosgobar.github.io/georef-ar-api/)

Mi personal Github for this work is [here](https://github.com/ucusita/jwt-refresh-token-node-js-mongodb/).

**I make seven (7) endpoints that must consume external service APIs .**

**I respect the structure used for the endpoint.** I used:

* Routes.
* Controllers.
* Services.
* Environment variables for sensitive data (like API keys or DB access).

**In one of the three endpoints, i saved the response to a Mongodb collection called apinasas.** For this I used MongoDB Atlas.

**The endpoints are protected with a JWT Token.**
Only the endpoints append to the initial code allow users with the role "user" to use the endpoint.
The rest of the endpoints allow the use.

36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
This is a fork of the original project. It's intended to set as a codebase for the final task for the students of the course 4 of Pilar Tecno.

## **[You're now facing the Final Task](https://www.youtube.com/watch?v=Jxk9DqdYsJ4)**



You have the freedom to use any free or open API for your project. You may use as many as you need/want.

Some suggestions are:

- [NASA API](https://api.nasa.gov/)
- [The Audio DB](https://www.theaudiodb.com/api_guide.php)
- [The cat facts](https://alexwohlbruck.github.io/cat-facts/docs/)
- [API del Servicio de Normalización de Datos Geográficos de
Argentina](https://datosgobar.github.io/georef-ar-api/)

You can browse more API's [here](https://public-apis.io/).

Keep in mind some API's will need some registration and/or are free for trial purposes only.

**The final task consists in you making three or more endpoints that must consume one external service API (like the ones listed before).**

**It is required that you pay special attention to the structure used for the endpoint.** Make sure to use:

* Routes.

* Controllers.

* Services.

* Environment variables for sensitive data (like API keys or DB access).

**In one of the three endpoints you code, it is required that you save the response to a Mongodb collection.** You can use MongoDB Atlas for easy setup, or a local instance if you want.

**It is required that the endpoints are protected with a JWT Token.** The endpoints should only allow users with the role "user" to use the endpoint.

# Node.js JWT Refresh Token with MongoDB example
JWT Refresh Token Implementation with Node.js Express and MongoDB. You can know how to expire the JWT, then renew the Access Token with Refresh Token.

Expand Down
15 changes: 15 additions & 0 deletions app/config/Schema/apod.schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const Schema = require('mongoose').Schema;
const mongoose = require('mongoose');

const apodSchema = new Schema({
date: String,
explanation: String,
media_type: String,
service_version: String,
title: String,
url: String,
creation_date: { type: Date, default: Date.now },
last_modified_date: { type: Date, default: Date.now }
});

module.exports = mongoose.model('apinasa', apodSchema);
8 changes: 4 additions & 4 deletions app/config/auth.config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
module.exports = {
secret: "bezkoder-secret-key",
// jwtExpiration: 3600, // 1 hour
// jwtRefreshExpiration: 86400, // 24 hours
jwtExpiration: 3600, // 1 hour
jwtRefreshExpiration: 86400, // 24 hours

/* for test */
jwtExpiration: 60, // 1 minute
jwtRefreshExpiration: 120, // 2 minutes
// jwtExpiration: 30, // 1 minute
// jwtRefreshExpiration: 120, // 2 minutes
};
19 changes: 15 additions & 4 deletions app/config/db.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
require('dotenv').config();

const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASSWORD;
const dbName = process.env.DB_NAME;
const dbUri = `mongodb+srv://${dbUser}:${dbPass}@cluster0.xj3as.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const mongooseOptions =
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
};

module.exports = {
HOST: "localhost",
PORT: 27017,
DB: "bezkoder_db"
};
dbUri, mongooseOptions
}
4 changes: 2 additions & 2 deletions app/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ exports.signup = (req, res) => {
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
password: bcrypt.hashSync(req.body.password, 8)
});

user.save((err, user) => {
Expand Down Expand Up @@ -63,7 +63,7 @@ exports.signup = (req, res) => {

exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
username: req.body.username
})
.populate("roles", "-__v")
.exec(async (err, user) => {
Expand Down
61 changes: 61 additions & 0 deletions app/controllers/gis.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const axios = require('axios').default;
const querystring = require('querystring');
const apiKey = process.env.API_KEY;
const apodMongoService = require('../services/database/apod.mongo.service');

async function getCities(req, res){
axios.get(`https://apis.datos.gob.ar/georef/api/provincias`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

async function getCitiesFilter(req, res){
const query = {
nombre: req.query.nombre
};
const axiosParams = querystring.stringify({...query});
axios.get(`https://apis.datos.gob.ar/georef/api/provincias?${axiosParams}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

async function getDepartmentFilter(req, res){
const query = {
provincia: req.query.provincia,
max : 100,
campos: "completo"
};
const axiosParams = querystring.stringify({...query});
axios.get(`https://apis.datos.gob.ar/georef/api/departamentos?${axiosParams}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

async function getLocalitiesFilter(req, res){
const query = {
provincia: req.query.provincia,
max : 100
};
const axiosParams = querystring.stringify({...query});
axios.get(`https://apis.datos.gob.ar/georef/api/localidades?${axiosParams}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

module.exports = {getCities, getCitiesFilter, getDepartmentFilter, getLocalitiesFilter};
60 changes: 60 additions & 0 deletions app/controllers/nasa.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const axios = require('axios').default;
const querystring = require('querystring');
const apiKey = process.env.API_KEY;
const apodMongoService = require('../services/database/apod.mongo.service');

async function getIndex(req, res){
res.json({message: 'This is the Nasa root route'});
}

async function getPictureOfTheDay(req, res){
const query = {
start_date: req.query.start_date,
end_date: req.query.end_date
};
const axiosParams = querystring.stringify({api_key: apiKey, ...query});
console.log(axiosParams);
axios.get(`https://api.nasa.gov/planetary/apod?${axiosParams}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

async function getMarsPicture(req, res){
const query = {
earth_date: req.query.earth_date
};
const axiosParams = querystring.stringify({api_key: apiKey, ...query});
axios.get(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?${axiosParams}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

async function savePictureOfTheDate(req, res){
const query = {
date: req.query.date
};
const axiosParams = querystring.stringify({api_key: apiKey, ...query});
console.log(axiosParams);
axios.get(`https://api.nasa.gov/planetary/apod?${axiosParams}`)
.then((response) => {
savePictureOfTheDay(response.data, res);
})
.catch(err => {
res.status(500).json(err);
});
}

async function savePictureOfTheDay(req, res){
const response = await apodMongoService.saveNasa(req);
res.json(response);
}

module.exports = {getIndex, getPictureOfTheDay, getMarsPicture, savePictureOfTheDay, savePictureOfTheDate};
37 changes: 35 additions & 2 deletions app/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
const nasaController = require('../controllers/nasa.controller');
const gisController = require('../controllers/gis.controller');

exports.allAccess = (req, res) => {
res.status(200).send("Public Content.");
};
Expand All @@ -6,10 +9,40 @@ exports.userBoard = (req, res) => {
res.status(200).send("User Content.");
};

/* Personal Develop Area */
exports.apiaBoard = (req, res) => {
nasaController.getPictureOfTheDay(req, res);
};

exports.apibBoard = (req, res) => {
nasaController.getMarsPicture(req, res);
};

exports.apicBoard = (req, res) => {
nasaController.savePictureOfTheDate(req, res);
};

exports.apidBoard = (req, res) => {
gisController.getCities(req, res);
};

exports.apieBoard = (req, res) => {
gisController.getCitiesFilter(req, res);
};

exports.apifBoard = (req, res) => {
gisController.getDepartmentFilter(req, res);
};

exports.apigBoard = (req, res) => {
gisController.getLocalitiesFilter(req, res);
};
/* End of Personal Develop Area */

exports.adminBoard = (req, res) => {
res.status(200).send("Admin Content.");
res.status(200).send("Admin Content. You can´t access to another contents.");
};

exports.moderatorBoard = (req, res) => {
res.status(200).send("Moderator Content.");
res.status(200).send("Moderator Content. You can´t access to another contents.");
};
34 changes: 33 additions & 1 deletion app/middlewares/authJwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,41 @@ const isModerator = (req, res, next) => {
});
};

const isUser = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}

Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}

for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "user") {
next();
return;
}
}

res.status(403).send({ message: "Require User Role!" });
return;
}
);
});
};

const authJwt = {
verifyToken,
isAdmin,
isModerator
isModerator,
isUser
};
module.exports = authJwt;
1 change: 1 addition & 0 deletions app/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ db.mongoose = mongoose;

db.user = require("./user.model");
db.role = require("./role.model");

db.refreshToken = require("./refreshToken.model");

db.ROLES = ["user", "admin", "moderator"];
Expand Down
2 changes: 1 addition & 1 deletion app/models/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const User = mongoose.model(
password: String,
roles: [
{
type: mongoose.Schema.Types.ObjectId,
type: mongoose.Schema.Types.ObjectId,
ref: "Role"
}
]
Expand Down
Loading