Skip to content

ADD: final task #3

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 2 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
4 changes: 2 additions & 2 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",
secret: process.env.SECRET_KEY,
jwtExpiration: 3600, // 1 hour
jwtRefreshExpiration: 86400, // 24 hours

/* for test */
// jwtExpiration: 30, // 1 minute
// jwtExpiration: 30, // 1/2 minute
// jwtRefreshExpiration: 120, // 2 minutes
};
4 changes: 2 additions & 2 deletions app/config/db.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASSWORD;
const dbName = 'PilarTecno'
const dbUri = `mongodb+srv://${dbUser}:${dbPass}@cluster0.qtcrz.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const dbName = 'PilarTecno';
const dbUri = `mongodb+srv://${dbUser}:${dbPass}@practice.b9mlq.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const mongooseOptions = {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true};


Expand Down
7 changes: 7 additions & 0 deletions app/config/default.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const LOTR_TOKEN = process.env.LOTR_TOKEN;

const Tokens = {
LOTR_TOKEN
};

module.exports = Tokens;
62 changes: 62 additions & 0 deletions app/controllers/games.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// https://www.freetogame.com/api-doc
// Free-To-Play Games Database API

const axios = require('axios');
const db = require("../models");
const { game: Game } = db;

// Get all the games free to play.
async function getGames(req, res){
const platform = req.query.platform ? req.query.platform : 'all';
const sortby = req.query.sortby ? req.query.sortby : 'relevance';
const category = req.query.category;
const params = category
? `?platform=${platform}&sort-by=${sortby}&category=${category}`
: `?platform=${platform}&sort-by=${sortby}`;
await axios.get(`https://www.freetogame.com/api/games${params}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

// Get game by id.
async function getGameById(req, res){
const id = req.params.id;
await axios.get(`https://www.freetogame.com/api/game?id=${id}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
res.status(500).json(err);
});
}

// add game by id
async function postGameById(req, res){
const id = req.body.id;
await axios.get(`https://www.freetogame.com/api/game?id=${id}`)
.then((response) => {
const game = new Game({
title: response.data.title,
platform: response.data.platform,
game_url: response.data.game_url,
genre: response.data.genre,
description: response.data.description
});
game.save(err => {
if (err) {
res.status(500).send({ message: err });
return;
}
});
res.send({ message: "Game was added successfully!" });
})
.catch(err => {
res.status(500).json(err);
});
}

module.exports = {getGames, getGameById, postGameById};
67 changes: 67 additions & 0 deletions app/controllers/lotr.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// https://the-one-api.dev/
// The Lord of the Rings API.
// Need a token for generate a request.
// Get your access token by registering a free API account. https://the-one-api.dev/sign-up

const axios = require('axios');
const { LOTR_TOKEN } = require('../config/default.config');

// Get all character.
async function getCharacter(req, res){
await axios({
method: 'get',
url: `https://the-one-api.dev/v2/character`,
headers: {Authorization: `Bearer ${LOTR_TOKEN}`}
})
.then((response) => {
let {docs} = response.data;
const qRace = req.query.race;
let qGen = req.query.gender[0].toUpperCase() + req.query.gender.slice(1).toLowerCase();
if (qRace){
docs = docs.filter(({race}) => race.toUpperCase() === qRace.toUpperCase());
}
if (qGen){
docs = docs.filter(({gender}) => gender === qGen);
}
res.json(docs);
})
.catch(err => {
res.status(500).json(err);
});
}
// Get all books.
async function getBooks(req, res){
await axios({
method: 'get',
url: `https://the-one-api.dev/v2//book/`,
headers: {Authorization: `Bearer ${LOTR_TOKEN}`}
})
.then((response) => {
const {docs} = response.data;
res.json(docs);
})
.catch(err => {
res.status(500).json(err);
});
}

// Get all book's chapters by id.
async function getChapterxBook(req, res){
// Book 1 - id: 5cf5805fb53e011a64671582
// Book 2 - id: 5cf58077b53e011a64671583
// Book 3 - id: 5cf58080b53e011a64671584
const id = req.params.id;
await axios({
method: 'get',
url: `https://the-one-api.dev/v2/book/${id}/chapter`,
headers: {Authorization: `Bearer ${LOTR_TOKEN}`}
})
.then((response) => {
res.json(response.data.docs);
})
.catch(err => {
res.status(500).json(err);
});
}

module.exports = {getCharacter, getChapterxBook, getBooks};
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;
14 changes: 14 additions & 0 deletions app/models/game.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose = require("mongoose");

const Game = mongoose.model(
"Game",
new mongoose.Schema({
title: String,
platform: String,
game_url: String,
genre: String,
description: String
})
);

module.exports = Game;
2 changes: 2 additions & 0 deletions app/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ db.refreshToken = require("./refreshToken.model");

db.ROLES = ["user", "admin", "moderator"];

db.game = require('./game.model');

module.exports = db;
22 changes: 22 additions & 0 deletions app/routes/games.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const controller = require("../controllers/games.controller");
const { authJwt } = require("../middlewares");

module.exports = function(app) {
app.get(
"/ftp_games",
[authJwt.verifyToken, authJwt.isUser],
controller.getGames
);

app.get(
"/ftp_game/:id",
[authJwt.verifyToken, authJwt.isUser],
controller.getGameById
)

app.post(
"/add_game/",
[authJwt.verifyToken, authJwt.isUser],
controller.postGameById
)
};
22 changes: 22 additions & 0 deletions app/routes/lotr.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const controller = require("../controllers/lotr.controller");
const { authJwt } = require("../middlewares");

module.exports = function(app) {
app.get(
"/lotr/character",
[authJwt.verifyToken, authJwt.isUser],
controller.getCharacter
);

app.get(
"/lotr/book/",
[authJwt.verifyToken, authJwt.isUser],
controller.getBooks
)

app.get(
"/lotr/book/:id",
[authJwt.verifyToken, authJwt.isUser],
controller.getChapterxBook
)
};
2 changes: 1 addition & 1 deletion app/routes/user.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module.exports = function(app) {

app.get("/api/test/all", controller.allAccess);

app.get("/api/test/user", [authJwt.verifyToken], controller.userBoard);
app.get("/api/test/user", [authJwt.verifyToken, authJwt.isUser], controller.userBoard);

app.get(
"/api/test/mod",
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.12.10",
Expand Down
5 changes: 5 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const express = require("express");
const cors = require("cors");
const dotenv = require('dotenv').config();
const dbConfig = require("./app/config/db.config");

const app = express();
Expand Down Expand Up @@ -38,6 +39,10 @@ app.get("/", (req, res) => {
// routes
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// lord of the ring route.
require("./app/routes/lotr.routes")(app);
// games free to play route.
require("./app/routes/games.routes")(app);

// set port, listen for requests
const PORT = process.env.PORT || 3000;
Expand Down