Skip to main content
Tweeted twitter.com/StackCodeReview/status/1220859189616107522

Clean code: PermistionPermission with middleware

In my example, I have 4 modelfour models: User, Company, Project, and Plant (inthough my project, it's have technically has more: Plant, Job, Team.., etc.).

First, I makewrote a simple codescript to check the role, of a given user (write in middlewaremiddleware.js):

To check multi permistionmultiple permissions, I makewrote a function andthat always use itgets used in the middleware.

After thatAfterwards, I writewrote this function to get a list userof users by project idID (write in controllercontroller.js):

To more easily find a given project easily in routerby its ID, i write aI wrote this helper function:

Finally, I write awrote the router (write in routerrouter.js):

It's my ideal and it working well and as intended, but thisthe code notisn't particularly fun to work with! How to make thiscan I improve the code cleanlyand make it more clean? I want help from you!

Clean code: Permistion with middleware

In example, I have 4 model: User, Company, Project, Plant (in my project, it's have more: Plant, Job, Team...).

First, I make simple code to check role, (write in middleware.js

To check multi permistion, I make a function and always use it in middleware.

After that, I write this function to get list user by project id (write in controller.js)

To find project easily in router, i write a function:

Finally, I write a router (write in router.js):

It's my ideal and it working well but this code not fun! How to make this code cleanly? I want help from you!

Clean code: Permission with middleware

In my example, I have four models: User, Company, Project, and Plant (though my project technically has more: Plant, Job, Team, etc.).

First, I wrote a simple script to check the role of a given user (middleware.js):

To check multiple permissions, I wrote a function that always gets used in the middleware.

Afterwards, I wrote this function to get a list of users by project ID (controller.js):

To more easily find a given project by its ID, I wrote this helper function:

Finally, I wrote the router (router.js):

It's working well and as intended, but the code isn't particularly fun to work with! How can I improve the code and make it more clean?

Source Link

Clean code: Permistion with middleware

In example, I have 4 model: User, Company, Project, Plant (in my project, it's have more: Plant, Job, Team...).

Model User: name, role, company: { id, role }, projects: [ { id, role } ], plants: [ { id, role } ]
Model Company: name, members [ ], projects [ ]
Model Project: title, members [ ], company, plants [ ]
Model Plant: title, members [ ], project, jobs [ ]

First, I make simple code to check role, (write in middleware.js

const isAdmin = (user) => {
    return user.role === "admin"
}

const isCompanyMember = (user, companyId) => {
    return user.company.id && user.company.id.equals(companyId)
}

To check multi permistion, I make a function and always use it in middleware.

const checkPermit = (...checks) => {
    let permit = 0
    for (let i = 0; i < checks.length; i++) {
        if (checks[i]) permit = 1
    }
    return permit
}

After that, I write this function to get list user by project id (write in controller.js)

const getListUsersByProjectId = async (req, res, next) => {
    const { projectId } = req.params
    try {
        const project = await Project.findById(projectId)
            .select("members")
            .populate("members", "name")
        if (!project) return next("Project not found")
        res.json({
            result: 'ok',
            message: "Find list of users successfully",
            data: project
        })
    } catch (error) {
        next(error)
    }
}

To find project easily in router, i write a function:

const findProject = (projectId) => {
    return Project.findById(projectId)
}

Finally, I write a router (write in router.js):

router.get('/get-list-users/:projectId',
    authentication.required,
    // I set signed user to req.user in function authentication.required
    async (req, res, next) => {
        try {
            let { user } = req
            let project = await findProject(req.params.projectId)
            if (!project) return next("Can not find project")
            let permit = checkPermit(
                isAdmin(user)
                isCompanyMember(user, project.company)
            )
            if (permit) return next()
            else return next("You don't have authorization to do this action!")
        } catch (error) {
            next(error)
        }
    },
    getListUsersByProjectId
)

It's my ideal and it working well but this code not fun! How to make this code cleanly? I want help from you!