简体   繁体   中英

How do i make specific users for only them to have access to their own specific data in mongodb and nodejs

I am working on a blog project. I am done with the functionality to create,edit and delete posts. I have also setup and login and signup with passport authentication and can already restrict pages to only logged in users. I want to also restrict editing and deleting of posts to only the users who created the post. I just can't seem to figure out how the link the two collections(one being the users collection and the other being the posts collection).

Below are the schemas for the two collections

posts schema

const articleSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    markdown: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    sanitizedHTML: {
        type: String,
        required: true
    }
})

users schema

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
});

In the articleSchema you need a field createdBy which will be linked with the id in userSchema. So, when the user is logged in you will get the user's id. Through which you can check if the post is created by that particular user. This is the best approach for your case right now.

If you want to have more extensive roles. For eg editors who can edit any articles. There are two ways to do it:

If you need multiple roles and their permissions are configurable

You need to create roleSchema which will have roleName, permissions etc. And in userSchema will be a field called role which corresponds to role_id for each user. This will allow you to change permissions and create new roles easily in future through UI.

If you just have few roles and confident that it won't change often

You can just define for yourself what these roles are: for eg 1 -> Editor, 2 -> Subscriber, 3 -> Admin etc. And add a role field in userSchema to put the relevant role. This will allow you to have fixed permission for each role. Now when you are doing anything with article's you can get the role and filter accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM