loopback icon indicating copy to clipboard operation
loopback copied to clipboard

Disable all remote methods and enable only selected ones (white-list)

Open voitau opened this issue 12 years ago • 75 comments

There is a bunch of existing open/closed issues with questions how to hide the method of the model. My question is about how can all the methods be disabled first and then enabled only those which are necessary? (basically, duplicates this comment: https://github.com/strongloop/loopback/issues/465#issuecomment-54851858)

Here is the simple function which hides all the methods of the model:

/**
 * Hides all the methods besides those in 'methods'.
 *
 * @param Model model to be updated.
 * @param methods array of methods to expose, e.g.: ['find', 'updateAttributes'].
 */
var setMethodsVisibility = function(Model, methods) {
  methods = methods || [];
  Model.sharedClass.methods().forEach(function(method) {
    method.shared = methods.indexOf(method.name) > -1;
  });
};

However, it doesn't hide two groups:

  • remote methods, which have to be hidden like this: Model.disableRemoteMethod(name, isStatic)
  • custom methods, like User.login or User.resetPassword (didn't find any way to hide them at all);

Could you please advise what would be the correct way to hide everything (without specific call for each method by its name explicitly) and allow only the methods which are necessary?

voitau avatar Oct 15 '14 19:10 voitau

@gunjpan Another issue ..

Can we hide PATCH end points?

image

I see for example PATCH and PUT has the same method names but with index?! like upsert_0 and upsert?

When I hide upsert it hides both PATCH and PUT .. can we keep one of them and hide the others?

ahmed-abdulmoniem avatar Oct 15 '16 09:10 ahmed-abdulmoniem

@ahmed-abdulmoniem : Added to #2860 .

gunjpan avatar Oct 17 '16 14:10 gunjpan

@gunjpan Thanks

ahmed-abdulmoniem avatar Oct 17 '16 15:10 ahmed-abdulmoniem

I'm not sure if this is the best place for this comment, but I found @ericprieto's disableAllMethodsWithExceptions incredibly helpful. Thank you for documenting it! I received a deprecation warning for disableRemoteMethod when using it, so I rewrote the function to use the recommended disableRemoteMethodByName.

const disableAllMethodsWithExceptions = function disableAllMethods(model, methodsToExpose) {
  if(model && model.sharedClass)
  {
    methodsToExpose = methodsToExpose || [];

    const modelName = model.sharedClass.name;
    const methods = model.sharedClass.methods();
    const relationMethods = [];
    const hiddenMethods = [];

    try
    {
      relationMethods.push({ name: 'prototype.patchAttributes' });
      Object.keys(model.definition.settings.relations).forEach(function(relation)
      {
        relationMethods.push({ name: 'prototype.__findById__' + relation });
        relationMethods.push({ name: 'prototype.__destroyById__' + relation });
        relationMethods.push({ name: 'prototype.__updateById__' + relation });
        relationMethods.push({ name: 'prototype.__exists__' + relation });
        relationMethods.push({ name: 'prototype.__link__' + relation });
        relationMethods.push({ name: 'prototype.__get__' + relation });
        relationMethods.push({ name: 'prototype.__create__' + relation });
        relationMethods.push({ name: 'prototype.__update__' + relation });
        relationMethods.push({ name: 'prototype.__destroy__' + relation });
        relationMethods.push({ name: 'prototype.__unlink__' + relation });
        relationMethods.push({ name: 'prototype.__count__' + relation });
        relationMethods.push({ name: 'prototype.__delete__' + relation });
      });
    } catch(err) {}

    methods.concat(relationMethods).forEach(function(method)
    {
      if(methodsToExpose.indexOf(method.name) < 0)
      {
        hiddenMethods.push(method.name);
        model.disableRemoteMethodByName(method.name);
      }
    });

    if(hiddenMethods.length > 0)
    {
      console.log('\nRemote methods hidden for', modelName, ':', hiddenMethods.join(', '), '\n');
    }
  }
};

cashweaver-zz avatar Nov 07 '16 00:11 cashweaver-zz

Should we add this (explanation and code for disableAllMethodsWithExceptions) to the documentation? If so, what would be the best place?

crandmck avatar Nov 08 '16 23:11 crandmck

Why is prototype.patchAttributes treated separately? I noticed that disabling patchAttributes alone doesn't have any effect (anymore, was fine until a few weeks ago), but wonder if this the intended behaviour?

ghost avatar Nov 09 '16 08:11 ghost

@crandmck :

Should we add this (explanation and code for disableAllMethodsWithExceptions) to the documentation? If so, what would be the best place?

Not at the moment, This feature is partially complete, once implemented, should eliminate a need to write above code. We can document the feature at the time.

gunjpan avatar Nov 09 '16 13:11 gunjpan

@gunjpan Cool--please keep me posted. I added the needs-doc label to remind us when we get to that point. Thanks.

crandmck avatar Nov 09 '16 21:11 crandmck

I have refactored the code to be a little more DRY and also include a method for passing in an array of endpoints to disable.

'use strict';
const
  relationMethodPrefixes = [
    'prototype.__findById__',
    'prototype.__destroyById__',
    'prototype.__updateById__',
    'prototype.__exists__',
    'prototype.__link__',
    'prototype.__get__',
    'prototype.__create__',
    'prototype.__update__',
    'prototype.__destroy__',
    'prototype.__unlink__',
    'prototype.__count__',
    'prototype.__delete__'
  ];

function reportDisabledMethod( model, methods ) {
  const joinedMethods = methods.join( ', ' );

  if ( methods.length ) {
    console.log( '\nRemote methods hidden for', model.sharedClass.name, ':', joinedMethods, '\n' );
  }
}

module.exports = {
  disableAllExcept( model, methodsToExpose ) {
    const
      excludedMethods = methodsToExpose || [];
    var hiddenMethods = [];

    if ( model && model.sharedClass ) {
      model.sharedClass.methods().forEach( disableMethod );
      Object.keys( model.definition.settings.relations ).forEach( disableRelatedMethods );
      reportDisabledMethod( model, hiddenMethods );
    }
    function disableRelatedMethods( relation ) {
      relationMethodPrefixes.forEach( function( prefix ) {
        var methodName = prefix + relation;

        disableMethod({ name: methodName });
      });
    }
    function disableMethod( method ) {
      var methodName = method.name;

      if ( excludedMethods.indexOf( methodName ) < 0 ) {
        model.disableRemoteMethodByName( methodName );
        hiddenMethods.push( methodName );
      }
    }
  },
  /**
   * Options for methodsToDisable:
   * create, upsert, replaceOrCreate, upsertWithWhere, exists, findById, replaceById,
   * find, findOne, updateAll, deleteById, count, updateAttributes, createChangeStream
   * -- can also specify related method using prefixes listed above
   * and the related model name ex for Account: (prototype.__updateById__followers, prototype.__create__tags)
   * @param model
   * @param methodsToDisable array
   */
  disableOnlyTheseMethods( model, methodsToDisable ) {
    methodsToDisable.forEach( function( method ) {
      model.disableRemoteMethodByName( method );
    });
    reportDisabledMethod( model, methodsToDisable );
  }
};

dancingshell avatar Nov 09 '16 22:11 dancingshell

@dancingshell could you turn this into a module, maybe even a mixin?

Also, this does not hide Model.prototype.updateAttributes temporary solution is model.disableRemoteMethod('updateAttributes', false) swag

Discountrobot avatar Nov 17 '16 11:11 Discountrobot

@Discountrobot and @dancingshell --- converted to mixin:

You can expose methods in your model.json file:

{
  "mixins":{
    "DisableAllMethods":{
      "expose":[
        "find",
        "findById"
      ]
    }
  }
}

or hide specific methods:

{
  "mixins":{
    "DisableAllMethods":{
      "hide":[
        "create"
      ]
    }
  }
}

https://gist.github.com/drmikecrowe/7ec75265fda2788e1c08249ece505a44

drmikecrowe avatar Nov 23 '16 17:11 drmikecrowe

hi, thanks for the gist :) As proposed in https://github.com/strongloop/loopback/issues/2953 What do you think of adding an option per method to decide whether the remote method should be made totally unavailable (in code and over rest), or just over rest?

ebarault avatar Nov 23 '16 17:11 ebarault

What I chose to do (I just updated the Gist) is to not hide any methods that had explicit ACL's. So, if you granted an allow permission, then expose that method or remote method (based on these comments https://github.com/strongloop/loopback/issues/651#issuecomment-219639397)

drmikecrowe avatar Nov 23 '16 17:11 drmikecrowe

@drmikecrowe , all, please see this gist

I refactored bits and pieces to make the code more straightforward and compatible with any version of loopback including v3 where a number of function names change.

Especially, i simplified the whole <is this a static or is this a related instance method?> logic. The reason why you only get static model methods from Model.sharedClass.methods() in your code is that you don't wait for all models to be attached, this is easily fixed by waiting for app.on('started') event. The prototype. prefix appending is then decided against the isStatic property of the remote method. This way there's no need to establish beforehand a list of possible methods prefix, making it time proof.

I also added an option for the mixin to work even if not specifying any method to explicitly hide or expose

Also included is an index.js file to allow for mixin declaration

Note: the code now uses the disableMethodByName method from loopback v3, please adapt if your loopback version does not support it yet.

ebarault avatar Dec 01 '16 09:12 ebarault

After all I bootstrapped a whole new mixin which is more compact (leveraging on lodash sugar):

the option to enable methods from ACLs is now configurable with enableFromACLs param (which defaults to true)

ebarault avatar Dec 01 '16 11:12 ebarault

@ebarault Where did you spot enableFromACLs ? Not seen anything mentioned of it and searching Google and the codebase returns nothing...

PaddyMann avatar Dec 01 '16 13:12 PaddyMann

@PaddyMann : it's from my own mixin code : here you configure it in the mixin setup section of the Model definition : here

(although it's intended to bet set when expected false, as it defaults to true)

ebarault avatar Dec 01 '16 14:12 ebarault

ah great stuff (sorry I misread your previous comment!)

I'll probably give your mixin a try in the next week or two :)

PaddyMann avatar Dec 01 '16 14:12 PaddyMann

@ebarault: what would be the differences between using your gist and this module https://github.com/Neil-UWA/loopback-remote-routing ? (Are there any differences?) If there are differences, I would recommend creating your code as a npm module.

c3s4r avatar Dec 01 '16 20:12 c3s4r

@c3s4r You meant your comment for someone else? (no gists from me?)

PaddyMann avatar Dec 01 '16 21:12 PaddyMann