如何在处理单个用户帐户和多个用户(具有角色的组织帐户)的同时创建MongoDB模式设计

时间:2018-12-21 07:20:27

标签: node.js mongodb express mongoose mongoose-schema

我正在使用mongoDB和mongoose一起开发Nodejs Express API项目,我想从最佳实践中获取一些建议,并打算从社区创建有效的模式设计

该应用程序处理两种类型的用户帐户

帐户类型:

  • 单(默认)
  • 组织(可以从设置切换到)

注意在组织帐户中,将有一个管理员(所有者)和其他受邀请的用户,并且为每个用户分配了权限级别/访问级别。一个用户将始终仅与一个帐户相关联,即,不能再次邀请他到另一个帐户或如果他已经是现有帐户的一部分,请启动一个新帐户。另外,在组织帐户的情况下,帐单和送货地址是特定于帐户而不是用户的(用户切换到组织帐户的地址将是组织帐户的地址)

我已经通过 passport.js JWT 本地策略

完成了身份验证部分

我试图开发一种类似于RDBMS的方法(我曾经是RDBMS家伙),但失败了

enter image description here

模型和架构

const userSchema = new Schema({
    first_name: String,
    last_name: String,
    email: String,
    phone: String,
    avatar: String,
    password: String,
    active: Boolean
});

const User = mongoose.model('user', userSchema);

const accountSchema =  mongoose.Schema({
    account_type: { type: String, enum: ['single', 'organization'], default: 'single' },
    organization: { type: Schema.Types.ObjectId, ref: 'organization', required: false },
    billing_address: String,
    shipping_address: String,

});

const Account = mongoose.model('account', accountSchema);

const accountUserRoleSchema =  mongoose.Schema({
    user :  { type: Schema.Types.ObjectId, ref: 'user', },
    role: { type: String, enum: ['admin', 'user'], default: 'user' },
    account: { type: Schema.Types.ObjectId, ref: 'account', required: true  }
});

const AccountUserRole = mongoose.model('accountUserRole', accountUserRoleSchema);


const permissionSchema =  mongoose.Schema({
    user :  { type: Schema.Types.ObjectId, ref: 'user', required: true },
    type: {  type: Schema.Types.ObjectId, ref: 'permissionType', required: true  },
    read: { type: Boolean, default: false, required: true  },
    write: { type: Boolean, default: false, required: true },
    delete: { type: Boolean, default: false, required: true },
    accountUser : {  type: Schema.Types.ObjectId, ref: 'account',required: true }

});

const Permission = mongoose.model('permission', permissionSchema);


const permissionTypeSchema =  mongoose.Schema({
    name :  { type: String, required: true   }

});

const PermissionType = mongoose.model('permissionType', permissionTypeSchema); 


const organizationSchema =  mongoose.Schema({
    account :  { type: Schema.Types.ObjectId, ref: 'account', },
    name: {  type: String, required: true },
    logo: { type: String, required: true  }
});


const Organization = mongoose.model('organization', organizationSchema);

现在,我正在开发“授权”部分,在该部分中,需要通过检查用户分配给他的权限来限制用户对资源的访问。

我发现的解决方案是开发一个授权中间件,该中间件在验证中间件之后运行,该中间件检查分配的访问权限

但是当我尝试根据当前登录的用户访问帐户数据时出现了问题,因为我将不得不基于objectId引用搜索文档。而且我可以理解,如果我继续当前的设计,可能会发生这种情况。这很好,但是使用objectId引用搜索文档似乎不是一个好主意

授权中间件

module.exports = {

    checkAccess :  (permission_type,action) => {

        return  async (req, res, next) => {

            // check if the user object is in the request after verifying jwt
            if(req.user){

                // find the accountUserRole with the user data from the req after passort jwt auth
                const accountUser = await AccountUserRole.findOne({ user :new ObjectId( req.user._id) }).populate('account');
                if(accountUser)
                {
                    // find  the account  and check the type 

                    if(accountUser.account)
                    {   
                        if(accountUser.account.type === 'single')
                        {   
                            // if account  is single grant access
                            return next();
                        }
                        else if(accountUser.account.type === 'organization'){


                             // find the user permission 

                             // check permission with permission type and see if action is true 

                             // if true move to next middileware else throw  access denied error  


                        }
                    }

                }

            }
        }


    }


}

我决定取消当前的架构,因为我了解到在NoSQL上强制执行RDBMS方法是一个坏主意。

与关系数据库不同,MongoDB的最佳方案设计在很大程度上取决于您如何访问数据。您将使用什么帐户数据,以及如何访问它

我新设计的新模式和模型

const userSchema = new Schema({
    first_name: String,
    last_name: String,
    email: String,
    phone: String,
    avatar: String,
    password: String,
    active: Boolean
    account :  { type: Schema.Types.ObjectId, ref: 'account', },
    role: { type: String, enum: ['admin', 'user'], default: 'user' },
    permssion: [
        {
            type: {  type: Schema.Types.ObjectId, ref: 'permissionType', required: true  },
            read: { type: Boolean, default: false, required: true  },
            write: { type: Boolean, default: false, required: true },
            delete: { type: Boolean, default: false, required: true },
        }
    ]

});

const User = mongoose.model('user', userSchema);

const accountSchema =  mongoose.Schema({
    account_type: { type: String, enum: ['single', 'organization'], default: 'single' },
    organization: {  
            name: {  type: String, required: true },
            logo: { type: String, required: true  }
         },
    billing_address: String,
    shipping_address: String,

});


const Account = mongoose.model('account', accountSchema);


const permissionTypeSchema =  mongoose.Schema({
    name :  { type: String, required: true   }

});

const PermissionType = mongoose.model('permissionType', permissionTypeSchema);

我仍然不确定这是否是正确的方法,请帮我提出建议。

2 个答案:

答案 0 :(得分:1)

您可以合并用户和用户帐户架构:

添加了一些对您有用的文件。

const userSchema = new Schema({
    first_name: { type: String,default:'',required:true},
    last_name: { type: String,default:'',required:true},
    email:  { type: String,unique:true,required:true,index: true},
    email_verified :{type: Boolean,default:false},
    email_verify_token:{type: String,default:null},
    phone:  { type: String,default:''},
    phone_verified :{type: Boolean,default:false},
    phone_otp_number:{type:Number,default:null},
    phone_otp_expired_at:{ type: Date,default:null},
    avatar:  { type: String,default:''},
    password: { type: String,required:true},
    password_reset_token:{type: String,default:null},
    reset_token_expired_at: { type: Date,default:null},
    active: { type: Boolean,default:true}
    account_type: { type: String, enum: ['single', 'organization'], default: 'single' },
    organization: {type:Schema.Types.Mixed,default:{}},
    billing_address: { type: String,default:''}
    shipping_address: { type: String,default:''}
    role: { type: String, enum: ['admin', 'user'], default: 'user' },
    permission: [
        {
            type: {  type: Schema.Types.ObjectId, ref: 'permissionType', required: true  },
            read: { type: Boolean, default: false, required: true  },
            write: { type: Boolean, default: false, required: true },
            delete: { type: Boolean, default: false, required: true },
        }
    ],
   created_at: { type: Date, default: Date.now },
   updated_at: { type: Date, default: Date.now }
});

在您的中间件中:

module.exports = {

  checkAccess :  (permission_type,action) => {

    return  async (req, res, next) => {

        // check if the user object is in the request after verifying jwt
         if(req.user){
              if(req.user.account_type === 'single')
                    {   
                        // if account  is single grant access
                        return next();
                    }
                    else{


                         // find the user permission 

                         // check permission with permission type and see if action is true 

                         // if true move to next middileware else throw  access denied error  


                    }
         }
       }
   }
};

答案 1 :(得分:0)

我建议:

1-定义您的权限级别,例如:如果将用户分配到特定的角色/权限级别,则他可以访问哪些功能/选项。

2-权限级别应通过数字(1 =管理员,2 =用户)等识别,并且该密钥应在MongoDB中建立索引(您也可以使用并依赖ObjectID)。

3-猫鼬中的用户对象/模式仅应具有类型为 Number 的权限密钥-无需为此创建单独的架构。

/* if the shell field has a space: treat it like a shell script */
if (strchr(pwd->pw_shell, ' ')) {
    buff = xmalloc(strlen(pwd->pw_shell) + 6);

    strcpy(buff, "exec ");
    strcat(buff, pwd->pw_shell);
    childArgv[childArgc++] = "/bin/sh";
    childArgv[childArgc++] = "-sh";
    childArgv[childArgc++] = "-c";
    childArgv[childArgc++] = buff;
} else {
    char tbuf[PATH_MAX + 2], *p;

    tbuf[0] = '-';
    xstrncpy(tbuf + 1, ((p = strrchr(pwd->pw_shell, '/')) ?
                p + 1 : pwd->pw_shell), sizeof(tbuf) - 1);

    childArgv[childArgc++] = pwd->pw_shell;
    childArgv[childArgc++] = xstrdup(tbuf);
}

childArgv[childArgc++] = NULL;

execvp(childArgv[0], childArgv + 1);

if (!strcmp(childArgv[0], "/bin/sh"))
    warn(_("couldn't exec shell script"));
else
    warn(_("no shell"));

exit(EXIT_SUCCESS);

使用这种方法,您可以修改auth check中间件,以仅检查数据库是否标识了客户端发送的权限级别,如果是,则授予用户访问权限,否则会抛出拒绝访问错误。

如果您愿意,可以添加另一个具有权限类型的字段,并返回该权限的名称,但是我认为您应该在客户端而不是服务器上进行处理。

我部分地理解了要求(读太多单词很不好),所以我什么都没碰,让我知道。