Giter Site home page Giter Site logo

enforce's Introduction

Enforce

Enforce is an add on for Laravel4 and provides an elegant way to define custom data access enforcers on your Eloquent ORM models.

Quick start

In the require key of composer.json file add the following

"darrylkuhn/enforce": "dev-master"

Run the Composer update comand

$ composer update

In config/app.php in the $aliases array replace the existing 'Eloquent' key with 'Enforce\Model':

'aliases' => array(

    'App'        => 'Illuminate\Support\Facades\App',
    'Artisan'    => 'Illuminate\Support\Facades\Artisan',
    ...
    'Eloquent'   => 'Enforce\Model',

),

Configuration

Enforce uses the standard Laravel config. Create app/config/enforce.php with the following:

<?php
return [
    'byDefault' => false,
];

Of course you can set this to true if you'd like but read throught he entire quickstart before doing so (there are good reasons to initialize your application with enforce off.

Usage

Your models should continue to extend Eloquent. Behind the scenes they're really extending Enforce\Model which in turn extends \Illuminate\Database\Eloquent\Model.

Your models now inherit a few new static methods including enforceOnRead() and enforceFilter().

  • enforceOnRead() takes a single parameter, either a Model or Collection. By default enforceOnRead() does nothing, its simply a passthru returning the model or collection it was given, this is where you can add your custom enforcement rules.
  • enforceFilter() takes a Model or Collection and filters out any model if the $key (member variable) does not match the $reference value. For example imagine you wanted to make sure the currently authenticated user could only access their own user model. You could implement such a restriction with the following code:
<?php

class User extends Eloquent
{
	public static function enforceOnRead( $models )
    {
        // If the user is not logged in then they can't read user data period
        if ( !Auth::check() ) 
        {
            return null;
        }
        // Filter out any results that don't belong to the user
        else 
        {
            $key = 'id';
            $refrenceValue = Auth::user()->id;
            return self::enforceFilter($models, $key, $refrenceValue);
        }
    }
}

This filters out any models who's id doesn't match the id of the currently authenticated user. Now calls to User::find($id); will return filtered results. To be a little more useful let's say you wanted to allow "admins" to access all models - you could implement the following:

<?php

class User extends Eloquent
{
	public static function enforceOnRead( $models )
    {
        // If the user is not logged in then they can't read user data period
        if ( !Auth::check() ) 
        {
            return null;
        }
        // If our user isn't an admin then we need to be sure to 
        // filter out any results that aren't theirs
        elseif ( ! Auth::user()->isAdmin() )
        {
            $key = 'id';
            $refrenceValue = Auth::user()->id;
            return self::enforceFilter($models, $key, $refrenceValue);
        }
        // Otherwise they can see anything.
        else 
        {
            return $models;
        }
    }
}

enforceFilter() can accpet complex keys (e.g. $key = 'primaryCompany()->locations[0]->id'; evaluates just fine.)

If necessary You may bypass enforcement by explicitly setting enforcement to false in the call User::find($id, ['*'], false);

Startup

In some cases it's adventageous to leave enforcement off until your app has reached some state. In the example above if enforcement is on and we do not explicity set enforcement to false when calling User::find()the authentication process will fail. This is because the rule requires a valid authenticated user to access user models and the authentication system uses the user model to authenticate - chicken meet egg. There are several ways to solve for this; you can of course flag calls in the authentication subsystem but this may require hacking the Laravel core (which is not recommended). Assuming you're using a filter to authenticate a user prior to routing my recommendation is to initialize the app with the enforcement off (byDefault => false) and then add a filter which flips it to true once the authentication is complete. For example in add the following filter to filters.php

Route::filter('app.applyEnforce', function()
{
    // Make sure our models enforce their access rules by default from here on out
    Config::set('enforce.byDefault', true);
});

Then include it in the appropriate routes call:

Route::group(array('before' => array('auth.basic', 'app.applyEnforce') ), function()
{
    // User Management
    Route::resource('users/{id}/roles', 'UserRoleController', ['only' => ['index', 'store', 'delete', 'describe']]);
});

This will first authenticate the user and then turn enforcement on.

enforce's People

Contributors

darrylkuhn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

wildfirelife

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.