Skip to content

Instantly share code, notes, and snippets.

@stalniy
Created July 26, 2017 13:09
Show Gist options
  • Save stalniy/03423a09b3f98baaf76a55c994642cc3 to your computer and use it in GitHub Desktop.
Save stalniy/03423a09b3f98baaf76a55c994642cc3 to your computer and use it in GitHub Desktop.
CASL and mongoose
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