Coder Social home page Coder Social logo

sharedb-access's Introduction

sharedb-access

NPM

Note

If you use nodejsthat doesn't support async/await you need [email protected]

Installation

  • Install: npm install sharedb-access

Usage

const shareDbAccess = require('sharedb-access')
shareDbAccess(backend)

Using sharedb-access you can control create, read, update, and delete database operation for every collection. You can use two types of rules: allow and deny. By default all the operations are denied. So, you should add some rules to allow them. If at least one allow-rule allows the write, and no deny-rules deny the write, then the write is allowed to proceed.

You can call allow and deny-rules as many times as you like. The functions should return true if they think the operation should be allowed for allow rules and denied for deny-rules. Otherwise they should return false, or nothing at all (undefined).

Create

// Allow create-operation for collection 'items'

// docId - id of your doc for access-control
// doc   - document object
// session - your connect session

backend.allowCreate('items', async (docId, doc, session) => {
  return true
})

// Deny creation if user is not admin
backend.denyCreate('items', async (docId, doc, session) => {
  return !session.isAdmin
})

// So, finally, only admins can create docs in 'items' collection
// the same results is if you just write:

backend.allowCreate('items', async (docId, doc, session) => {
  return session.isAdmin
})

Read

Interface is like create-operation

backend.allowRead('items', async (docId, doc, session) => {
  // Allow all operations
  return true
})

backend.denyRead('items', async (docId, doc, session) => {
  // But only if the reader is owner of the doc
  return doc.ownerId !== session.userId
})

Delete

Interface is like create-operation

backend.allowDelete('items', async (docId, doc, session) => {
  // Only owners can delete docs
  return doc.ownerId === session.userId
})

backend.denyDelete('items', async (docId, doc, session) => {
  // But deny deletion if it's a special type of docs
  return doc.type === 'liveForever'
})

Update

// docId - id of your doc for access-control
// oldDoc  - document object (before update)
// newDoc  - document object (after update)
// ops    - array of OT operations
// session - your connect session

const allowUpdateAll = async (docId, oldDoc, newDoc, ops, session) => {
  return true
}

backend.allowUpdate('items', allowUpdateAll);

MIT License 2017 by Artur Zayats

sharedb-access's People

Contributors

balek avatar cjblomqvist avatar cray0000 avatar fctsvirus avatar ovvn avatar qinyang912 avatar zag2art avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharedb-access's Issues

TypeError: plugin is not a function

Hello,
I'm attempting to start using sharedb-access. I tried to follow the setup steps from the README, and I'm getting the following error:

/Users/curran/repos/myApp/node_modules/racer/lib/util.js:178
    plugin(this, options);
    ^

TypeError: plugin is not a function
    at Racer.use (/Users/curran/repos/myApp/node_modules/racer/lib/util.js:178:5)
    at new ShareDBAccess (/Users/curran/repos/myApp/node_modules/sharedb-access/lib/index.js:29:11)
    at ShareDBAccess (/Users/curran/repos/myApp/node_modules/sharedb-access/lib/index.js:22:48)
    at Racer.use (/Users/curran/repos/myApp/node_modules/racer/lib/util.js:178:5)
    at store (/Users/curran/repos/myApp/server/store.js:10:9)
    at /Users/curran/repos/myApp/server.js:17:40
    at Racer.Derby.run (/Users/curran/repos/myApp/node_modules/derby/lib/Derby.server.js:17:5)
    at Object.<anonymous> (/Users/curran/repos/myApp/server.js:8:7)
    at Module._compile (module.js:397:26)
    at Object.Module._extensions..js (module.js:404:10)

Here we can see the source of the error within sharedb-access:

https://github.com/dmapper/sharedb-access/blob/master/lib/index.js#L29

backend.use('doc', this.docHandler.bind(this));

The definition of use can be found here in racer:

https://github.com/derbyjs/racer/blob/master/lib/util.js#L173

function use(plugin, options) {
  // Don't include a plugin more than once
  var plugins = this._plugins || (this._plugins = []);
  if (plugins.indexOf(plugin) === -1) {
    plugins.push(plugin);
    plugin(this, options);
  }
  return this;
}

It seems the use function does not take a string as the first argument. This can be traced to a change by @nateps in 2014

derbyjs/racer@4317c8b#diff-3deb3f32958bb937ae05c6f3e4abbdf5L170

I'm not sure if this is actually the cause of the error though, because sharedb-access was updated more recently than that by @cjblomqvist

9aa2d9e

Here are the versions from my package.json:

  "dependencies": {
    "async": "^2.0.0-rc.5",
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.1",
    "compression": "^1.6.2",
    "connect-mongo": "^1.2.0",
    "cookie-parser": "^1.4.3",
    "derby": "^0.8.5",
    "derby-debug": "^0.1.0",
    "derby-login": "^1.1.1",
    "express": "^4.13.4",
    "express-session": "^1.13.0",
    "racer-bundle": "^0.2.4",
    "racer-highway": "^7.0.2",
    "redis-url": "^1.2.1",
    "serve-favicon": "^2.3.0",
    "serve-static": "^1.10.3",
    "sharedb-access": "^3.0.0",
    "sharedb-mongo": "^0.8.7",
    "sharedb-redis-pubsub": "^0.3.1"

Here's where I'm adding sharedb-access (inside store.js from generator-derby):

var shareDbMongo = require("sharedb-mongo");
var shareDbAccess = require("sharedb-access");

module.exports = store;

function store(derby, publicDir) {
  var db = shareDbMongo(process.env.MONGO_URL + "?auto_reconnect=true", {safe: true});

  derby.use(require("racer-bundle"));
  derby.use(shareDbAccess);

  var redis = require("redis-url");
  var redisPubSub = require("sharedb-redis-pubsub");

Any ideas why this error is occurring or how it can be fixed? Thank you.

How do I "setup" a session.

Hi,

First of all, thanks for your work, you are making access control look easy. I have a major issue though.

The 3rd argument of each function is session. The documentation only says session - your connect session but this is empty for me on read, and for a write operation for example, it is the content of op, sent by the client using doc.submitOp(op).

I need to protect resources behind roles using JWT so I guess my question is "how do I setup a session". I've looked on the ShareDB documentation, but nothing is mentioned.

If you could point me out to the right direction, I'd be grateful.

Thanks

More detailed usage examples would be helpful

Hi, I'm trying to use sharedb-access with sharedb itself (without racer or derby) just as the sharedb README suggests.

The usage examples in the README don't go into much details how to implement this module this way.
I have the following questions:

  1. can I use sharedb-access as a middleware with a sharedb example like this?
let share = new ShareDB();
share.use(require('sharedb-access'))
  1. what is the store in this case that are used in the create, read, delete, update examples?

  2. how does the session parameter work in this situation?

Method `allowCreate` never executed?

I am running,

"sharedb": "^1.0.0-beta",
"sharedb-access": "^5.0.0",

With,

$ node --version
v10.13.0

And when running,

shareDbAccess(backend);
backend.allowCreate('default', async (docId, doc, session) => {
  console.log('docId, doc, session:', docId, doc, session);
  return false;
})

The console.log never executes and I'm allowed to create the 'default' document even when the function returns false.

All other mehods, allowRead and allowUpdate are working perfectly.

Any ideas why this happens? What I'm doing wrong?

Thanks!

Неверная инициализация

Указанное подключение в readme неверное, метод .use у объекта Racer передает в качестве первого аргумента не экземпляр Backend (или store), а указатель на себя. Сам Racer не имеет ссылок на создаваемые им экземпляры Backend, только его прототип.
В итоге получилось подключить данный модуль только так:


sharedbAccess = require "sharedb-access"

new sharedbAccess(store, options)

Version 4 is broken

Thanks for making this useful library. I see that version 4 was just released a day ago. I wanted to let you know that it is broken. A simple:

const shareDbAccess = require('sharedb-access');

...will break it. I switched to 3.0.0 and it's working fine. The error:

error: uncaughtException: Unexpected token function

Не используется асинхронность

Хотелось бы видеть асинхронность в принятии решений об отказе или доступе к операции, чаще всего решение принимается на основе данных которых нет в наличии синхронно. Это сильно ограничивает применение данного модуля.
Ведь сам sharedb во всем использует обратные вызовы, в отличие от того же sharejs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.