Skip to content

Commit

Permalink
Merge pull request #51 from bellaabdelouahab/dev
Browse files Browse the repository at this point in the history
fix - testing role managment
  • Loading branch information
Khalid1G committed Jun 25, 2023
2 parents dca09e4 + c7b8464 commit 0115fee
Show file tree
Hide file tree
Showing 28 changed files with 708 additions and 624 deletions.
1 change: 1 addition & 0 deletions backend-app/.env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
API_VERSION = "v1"
MONGO_URI = "mongodb+srv://username:password@cluster0.cmlpjag.mongodb.net/?retryWrites=true&w=majority"
ADMIN_EMAIL = "admin@swf.com"
ADMIN_PASSWORD = "password123418746"
Expand Down
11 changes: 4 additions & 7 deletions backend-app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@ const hpp = require("hpp");
const cors = require("cors");
const morgan = require("./middlewares/morgan");
const swaggerDocs = require("./utils/swagger");
const { CURRENT_ENV } = require("./config/appConfig");
const { CURRENT_ENV, API_VERSION } = require("./config/appConfig");

const userRoutes = require("./routes/userRoutes");
const adminRoutes = require("./routes/adminRoute");
const app = express();

// configure swagger docs
Expand Down Expand Up @@ -61,11 +59,10 @@ if (CURRENT_ENV.toLocaleLowerCase() === "production") {
app.use("/api", limiter);
}

// Routes
app.use("/api/v1/users", userRoutes);
app.use("/api/v1/admin", adminRoutes);
// routes
app.use(`/api/${API_VERSION}`, require("./routes/index"));


//welcome page with the welcome message and env
app.get("/", (req, res) => {
res.status(200).json({
status: "success",
Expand Down
3 changes: 2 additions & 1 deletion backend-app/config/appConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ const { join } = require("path");
const dotenv = require("dotenv");
dotenv.config({ path: join(__dirname, "../.env") });

console.log(process.env.NODE_ENV);
// console.log(process.env.NODE_ENV);

exports.logFilePath = join(__dirname, "../server-logs");
exports.CURRENT_ENV = process.env.NODE_ENV || "development";
exports.API_VERSION = process.env.API_VERSION || "v1";
exports.DATABASE = process.env.MONGO_URI || "mongodb://127.0.0.1:27017";
exports.PORT = process.env.PORT || "5000";
exports.ADMIN_EMAIL = process.env.ADMIN_EMAIL || "admin@gmail.com";
Expand Down
3 changes: 3 additions & 0 deletions backend-app/controllers/adminController.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ exports.authorizeOrRestrict = async (req, res, next) => {
);
const user = await userModel.findById(userId);
if (!user) throw new AppError(404, 'fail', 'No user found with this id');
// if the user is a super admin, he can't be restricted
if (user.roles?.includes("SUPER_ADMIN"))
throw new AppError(400, "fail", "User is a super admin");
const existingAuthorities = user.authorities;
const existingRestrictions = user.restrictions;
user.authorities = Array.from(
Expand Down
16 changes: 14 additions & 2 deletions backend-app/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,16 +157,28 @@ exports.protect = async (req, res, next) => {
req.user = user;
next();
} catch (err) {
// check if the token is expired
if (err.name === 'TokenExpiredError') {
return next(
new AppError(401, 'fail', 'Your token is expired'),
req,
res,
next
);
}
next(err);
}
};

// Authorization check if the user have rights to do this action
exports.restrictTo = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
const roleExist = roles.some((role) => {
return req.user.roles.includes(role);
});
if (!roleExist) {
return next(
new AppError(403, 'fail', 'You are not allowed to do this action'),
new AppError(403, "fail", "You are not allowed to do this action"),
req,
res,
next
Expand Down
45 changes: 45 additions & 0 deletions backend-app/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
const User = require('../models/userModel');
const base = require('./baseController');
const AppError = require("../utils/appError");



exports.getMe = (req, res, next) => {
// return data of the current user
res.status(200).json({
status: 'success',
data: req.user
});
};

exports.deleteMe = async (req, res, next) => {
try {
Expand All @@ -18,6 +29,40 @@ exports.deleteMe = async (req, res, next) => {
}
};


exports.updateMe = async (req, res, next) => {
try {
// 1) Create error if user POSTs password data
if (req.body.password || req.body.passwordConfirm) {
return next(new AppError(400, 'fail', 'This route is not for password updates. Please use /updateMyPassword'), req, res, next);
}
// create error if user tries to update role
if (req.body.roles) {
return next(new AppError(400, 'fail', 'This route is not for role updates. Please use /updateRole'), req, res, next);
}
// 2) Filtered out unwanted fields names that are not allowed to be updated
const filteredBody = Object.keys(req.body).filter(el => el !== 'name' && el !== 'email');

// 3) Update user document
const doc = await User.findByIdAndUpdate(req.user.id, filteredBody, {
new: true,
runValidators: true,
});
if (!doc) {
return next(new AppError(404, "fail", "No document found with that id"), req, res, next);
}

res.status(200).json({
status: "success",
data: {
doc
}
});
} catch (error) {
next(error);
}
};

exports.getAllUsers = base.getAll(User);
exports.getUser = base.getOne(User);

Expand Down
Loading

0 comments on commit 0115fee

Please sign in to comment.