Skip to content

final task node #2

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 1 commit 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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
DB_USER=
DB_PASSWORD=
SECRET=
WEATHER_API_KEY=
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
2 changes: 1 addition & 1 deletion app/config/auth.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
secret: "bezkoder-secret-key",
secret: process.env.SECRET,
jwtExpiration: 3600, // 1 hour
jwtRefreshExpiration: 86400, // 24 hours

Expand Down
2 changes: 1 addition & 1 deletion 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 dbUri = `mongodb+srv://${dbUser}:${dbPass}@cluster0.rr5jw.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const mongooseOptions = {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true};


Expand Down
104 changes: 104 additions & 0 deletions app/controllers/city.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const axios = require("axios");
const City = require("../models/city.model");
const apiKey = process.env.WEATHER_API_KEY;

exports.getAllcities = async (req, res) => {
try {
const cities = await City.find({})
res.status(200).json({
ok: true,
message: "Results",
body: cities
})

} catch (error) {
res.status(400).json({
ok: false,
message: "Something goes wrong"
})
}
}

exports.getOneCityByID = async (req, res) => {
try {
const city = await City.findById({ _id: req.params.id });
res.status(200).json({
ok: true,
message: "Search results",
body: city
})
} catch (error) {
res.status(400).json({
ok: false,
message: "City not found"
})
}
}

exports.searchCity = async (req, res) => {
const { city, country } = req.body;

try {
const response = await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&units=metric&appid=${apiKey}`);
const newCity = new City({
temp: response.data.main.temp,
feels_like: response.data.main.feels_like,
temp_min: response.data.main.temp_min,
temp_max: response.data.main.temp_max,
pressure: response.data.main.pressure,
humidity: response.data.main.humidity,
sea_level: response.data.main.sea_level,
grnd_level: response.data.main.grnd_level,
name: response.data.name
});
await newCity.save();
res.status(200).json({
ok: true,
message: "City was saved",
body: newCity
})

} catch (error) {
res.status(400).json({
ok: false,
message: "Error"
})
}

}

exports.deleteCity = async (req, res) => {
try {
await City.findByIdAndDelete({ _id: req.params.id });
res.status(200).json({
ok: true,
message: "The city was deleted"
})
} catch (error) {
res.status(400).json({
ok: false,
message: "Error: The city cannot been deleted"
})
}
}

exports.editCity = async (req, res) => {
try {
const cityEdited = await City.findByIdAndUpdate({ _id: req.params.id }, req.body,
{
new: true,
}
);
res.status(200).json({
ok: true,
message: "City was edited",
body: cityEdited
})

} catch (error) {
res.status(400).json({
ok: false,
message: "Error: The city cannot been edited"
})
}
}
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;
16 changes: 16 additions & 0 deletions app/models/city.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require("mongoose");

const CitySchema = new mongoose.Schema({
temp: Number,
feels_like: Number,
temp_min: Number,
temp_max: Number,
pressure: Number,
humidity: Number,
sea_level: Number,
grnd_level: Number,
name: String
});


module.exports = mongoose.model("City", CitySchema);
24 changes: 24 additions & 0 deletions app/routes/city.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { searchCity, deleteCity, getAllcities, getOneCityByID, editCity } = require("../controllers/city.controller");
const { authJwt } = require("../middlewares");


module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});

app.get("/api/city", [authJwt.verifyToken, authJwt.isUser], getAllcities);

app.get("/api/city/:id", [authJwt.verifyToken, authJwt.isUser], getOneCityByID);

app.put("/api/city/:id", [authJwt.verifyToken, authJwt.isUser], editCity);

app.delete("/api/city/:id", [authJwt.verifyToken, authJwt.isUser], deleteCity);

app.post("/api/city", [authJwt.verifyToken, authJwt.isUser], searchCity)

};
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"description": "Node.js JWT Refresh Token with MongoDB",
"main": "server.js",
"scripts": {
"start": "nodemon server.js",
"dev": "nodemon server.js",
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
Expand All @@ -19,9 +20,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
2 changes: 2 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");
require("dotenv").config();
const dbConfig = require("./app/config/db.config");

const app = express();
Expand Down Expand Up @@ -38,6 +39,7 @@ app.get("/", (req, res) => {
// routes
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
require("./app/routes/city.routes")(app);

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