Created
July 26, 2017 13:09
-
-
Save stalniy/03423a09b3f98baaf76a55c994642cc3 to your computer and use it in GitHub Desktop.
CASL and mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { mongoosePlugin, AbilityBuilder } = require('casl') | |
const mongoose = require('mongoose') | |
mongoose.plugin(mongoosePlugin) | |
const Post = mongoose.model('Post', mongoose.Schema({ | |
title: String, | |
author: String, | |
content: String, | |
createdAt: Date | |
})) | |
// by default it asks for `read` rules and returns mongoose Query, so you can chain it | |
Post.accessibleBy(ability).where({ createdAt: { $gt: Date.now() - 24 * 3600 } }) | |
// also you can call it on existing query to enforce visibility. | |
// In this case it returns empty array because rules does not allow to read Posts of `someoneelse` author | |
Post.find({ author: 'someoneelse' }).accessibleBy(ability, 'update').exec() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment