CakePHP plugin to allow passing currently logged in user to model layer.

Overview

Footprint

Build Status Coverage Total Downloads License

This plugin allows you to pass the currently logged in user info to the model layer of a CakePHP application.

It comes bundled with the FootprintBehavior to allow you control over columns such as user_id, created_by, company_id similar to the core's TimestampBehavior.

Install

Using Composer:

composer require muffin/footprint

You then need to load the plugin by running console command:

bin/cake plugin load Muffin/Footprint

Usage

Trait

First, you will need to include the Muffin\Footprint\Auth\FootprintAwareTrait to your AppController:

use Muffin\Footprint\Auth\FootprintAwareTrait;

class AppController extends Controller
{
    use FootprintAwareTrait;

    // Specify the user model if required. Defaults to "Users".
    $this->_userModel = 'YourPlugin.Members';
}

This will attach the Muffin\Footprint\Event\FootprintListener to models which will inject the currently logged in user's instance on Model.beforeSave and Model.beforeFind in the _footprint key of $options.

Your controller needs to have either cakephp/authentication plugin's AuthenticationComponent or CakePHP core's deprecated AuthComponent loaded so that the user identity can be fetched.

Behavior

To use the included behavior to automatically update the created_by and modified_by fields of a record for example, add the following to your table's initialize() method:

$this->addBehavior('Muffin/Footprint.Footprint');

You can customize that like so:

$this->addBehavior('Muffin/Footprint.Footprint', [
    'events' => [
        'Model.beforeSave' => [
        	'user_id' => 'new',
            'company_id' => 'new',
            'modified_by' => 'always'
        ]
    ],
    'propertiesMap' => [
        'company_id' => '_footprint.company.id',
    ],
]);

This will insert the currently logged in user's primary key in user_id and modified_by fields when creating a record, on the modified_by field again when updating the record and it will use the associated user record's company id in the company_id field when creating a record.

Warning

If you have the FootprintBehavior attached to a model do not load the model inside Controller::initialize() method directly or indirectly. If you do so the footprint (user entity) won't be set for the model and the behavior won't work as expected. You can load your model in Controller::beforeFilter() if needed.

This is because the FootprintListener which sets the user entity to the models is attached after Controller::initialize() is run.

Patches & Features

  • Fork
  • Mod, fix
  • Test - this is important, so it's not unintentionally broken
  • Commit - do not mess with license, todo, version, etc. (if you do change any, bump them into commits of their own that I can ignore when I pull)
  • Pull request - bonus point for topic branches

Bugs & Feedback

http://github.com/usemuffin/footprint/issues

License

Copyright (c) 2015-Present, Use Muffin and licensed under The MIT License.

Comments
  • FootprintBehavior's beforeSave doesn't seem to have the information it needs in it

    FootprintBehavior's beforeSave doesn't seem to have the information it needs in it

    Hi. This isn't really an 'issue' so much as a query. I have, I think, followed the instructions for getting this set up, and if I put breakpoints in the FootprintListener and FootprintAwareTrait I can see the User data being set where it seems to need to be, however when it then reaches the beforeSave in the FootprintBehavior, $options doesn't seem to contain any data pertaining to the user.

    My Table's initialise:

    $this->addBehavior('Muffin/Footprint.Footprint', [
        'events' => [
            'Model.beforeSave' => [
                'created_by' => 'new',
                'modified_by' => 'always',
            ]
        ]
    ]);
    

    The $options variable in the FootprintBehavior's beforeSave():

    ArrayObject::__set_state(array(
       'atomic' => true,
       'associated' => 
      array (
        'characters' => 
        array (
        ),
        'createduser' => 
        array (
        ),
        'modifyuser' => 
        array (
        ),
      ),
       'checkRules' => true,
       'checkExisting' => true,
       '_primary' => true,
    ))
    

    My full AppController My full XpTable

    question 
    opened by Cylindric 28
  • $options['_footprint'] is multi entities when using JwtAuth plugin

    $options['_footprint'] is multi entities when using JwtAuth plugin

    In the case we are more than one authentication method (in my case : Form and ADmad/JwtAuth.Jwt ).

    then noticed that the $options['_footprint']['id'] is not accessible from and I have to use $options['_footprint'][0]['id']

    object(Cake\ORM\Entity)[228]
      protected '_properties' => 
        array (size=2)
          0 => 
            array (size=14)
              'id' => string 'e666e197-74d3-4d6c-9ae1-2be9eab76349' (length=36)
              'full_name' => string 'aaa' (length=5)
              'username' => string 'aaa' (length=10)
              'email' => string '[email protected]' (length=20)
              'email_token' => null
              'email_verified' => boolean true
              'email_token_expires' => null
              'active' => boolean true
              'password_token' => null
              'password_token_expires' => null
              'role' => string 'ADMIN' (length=5)
              'last_login' => null
              'created' => 
                object(Cake\I18n\Time)[216]
                  ...
              'modified' => 
                object(Cake\I18n\Time)[219]
                  ...
          1 => 
            object(ADmad\JwtAuth\Auth\JwtAuthenticate)[140]
              protected '_token' => string 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJlNjY2ZTE5Ny03NGQzLTRkNmMtOWFlMS0yYmU5ZWFiNzYzNDkiLCJleHAiOjE0NjM0ODY4NTl9.3OOTe8UHrLIjR-VzG8w8EI3CKoU1fMHXxC-nuwh5mi0' (length=165)
              protected '_payload' => 
                object(stdClass)[139]
                  ...
              protected '_error' => null
              protected '_defaultConfig' => 
                array (size=6)
                  ...
              protected '_registry' => 
                object(Cake\Controller\ComponentRegistry)[103]
                  ...
              protected '_passwordHasher' => null
              protected '_needsPasswordRehash' => boolean false
              protected '_config' => 
                array (size=13)
                  ...
              protected '_configInitialized' => boolean true
      protected '_original' => 
        array (size=0)
          empty
      protected '_hidden' => 
        array (size=0)
          empty
      protected '_virtual' => 
        array (size=0)
          empty
      protected '_className' => null
      protected '_dirty' => 
        array (size=2)
          0 => boolean true
          1 => boolean true
      protected '_new' => boolean true
      protected '_errors' => 
        array (size=0)
          empty
      protected '_invalid' => 
        array (size=0)
          empty
      protected '_accessible' => 
        array (size=2)
          '*' => boolean true
          'id' => boolean true
      protected '_registryAlias' => string 'Users' (length=5)
    
    opened by eymen-elkum 21
  • Breaks table association.

    Breaks table association.

    Following is in my composer.json for context:

     "require": {
       "php": ">=5.5.9",
       "cakephp/cakephp": "3.3.*",
       "mobiledetect/mobiledetectlib": "2.*",
       "cakephp/migrations": "~1.0",
       "cakephp/plugin-installer": "*",
       "friendsofcake/crud": "^4.3",
       "friendsofcake/search": "^2.3",
       "friendsofcake/crud-view": "^0.3.3",
       "friendsofcake/crud-users": "^0.2.0",
       "cakedc/users": "^3.2",
       "maiconpinto/cakephp-adminlte-theme": "^1.0",
       "muffin/footprint": "dev-master"
     },
       "require-dev": {
       "psy/psysh": "@stable",
       "cakephp/debug_kit": "~3.2",
       "cakephp/bake": "~1.1"
     }
    

    When I enable the footprint plugin in my posts model:

    $this->addBehavior('Muffin/Footprint.Footprint', [
      'events' => [
        'Model.beforeSave' => [
          'user_id' => 'new',
          'edit_user_id' => 'new',
          'username' => 'new',
        ]
      ],
    ]);
    

    I have associations between PostsTable (belongsTo('Users')), UsersTable (hasMany('Posts')). When I enable this plugin it throws an error that posts is not associated with users. If I disable the plugin I am able to create a post with the logged in user. I have tried to identify the exact error but so far nothing specific has come up.

    Thoughts? Thanks again, great plugin so far, been using it for a while now on a few projects this is definitely new.

    invalid 
    opened by termlimit 17
  • Sets Model.initialize in trait __construct method

    Sets Model.initialize in trait __construct method

    A problem was occurring when models that have Footprint behaviour were initialised in component, before Footprint Model.initialize listener was getting set.

    opened by andrej-griniuk 13
  • Integration tests fail with cake 3.3.4

    Integration tests fail with cake 3.3.4

    With Cake 3.3.3 the following is included in our setUp() - and that puts content in the '_footprint' key in the table's $options array - but 3.3.4 and 3.3.5 this array is null :-/

    use Muffin\Footprint\Event\FootprintListener;
    
    //
    
        public function setUp()
        {
            parent::setUp();
    
            // put the login logic here instead in each function
            // Set session data
            $this->session([
                'Auth' => [
                    'User' => [ /**/ ],
                        'language' => [
                            'short_code' => 'en_US',
                            'currency_id' => '83e0e78d-115e-423f-82dc-cf3f9da37b3d',
                        ],
                    ],
                ],
            ]);
            $this->listener = new FootprintListener();
        }
    
    question 
    opened by Spriz 10
  • Use footprint across plugins

    Use footprint across plugins

    I have split my application into plugins .

    Im trying to use Footprint and I have the following setup:

    • I have FootprintAwareTrait called inside src/Controller/AppController
    • I have my Tables and Models in src and Controllers and Templates in plugins/Foo.

    The above setup didn't work.

    So I left FootprintAwareTrait; inside src/Controller/AppController and tried to move some stuff around:

    • Moved everything in src - WORKED
    • Moved everything in plugins/MyPluginName - WORKED

    But I still want to have Tables and Models in src and Controllers and Templates in plugins/Foo, so any ideas if it's possible to use the Footprintplugin in that case ?

    I have managed to reproduce that in a new project and made a repo.

    opened by kristiyandobrev 9
  • Configuration problem

    Configuration problem

    Using CakePHP4 Please, review the "Usage" readme secction. I'm unable to get it working correctly. Every fail (including Missing controller or action) end with: "You must have AuthenticationComponent or AuthComponent loaded to use Footprint"

    `use Muffin\Footprint\Auth\FootprintAwareTrait;

    class AppController extends Controller { use FootprintAwareTrait;

    // Specify the user model if required. Defaults to "Users".
    $this->_userModel = 'YourPlugin.Members';//<-- Cannot use $this out of function
    

    }`

    opened by jfalbel 6
  • Problem with foreign key constraint

    Problem with foreign key constraint

    Its working fine with cakephp 3.5 till user is login. but how to set NULL (not 0) for not login users.

    In simple words how to save fields (created_by, modified_by) with NULL not the 0.

    This is the case where user can fill form with or without login and system need to track user if it is login else it should enter NULL (not zero).

    bug 
    opened by nakoda 6
  • Support Model.beforeRules

    Support Model.beforeRules

    Right now rules cannot make use of the information provided by the FootprintBehavior, as it is injected after the rules checking step.

    However rules might need to check on it. Usage example:

    Records can be locked for editing by a user. The rule ensures that the modifying user is the one holding the lock, if there is any (by comparing modifiedby in the entity with lockedby in the database).

    I don't know the design decision to use beforeSave, but I would assume beforeRules is the better place in general. As the rules check the consistency of the entity and the user data might play part in it.

    I volunteer to do a PR that enables Model.beforeRules next to Model.beforeSave.

    opened by ypnos 6
  • CakePHP 3.9.7 breaks muffin/footprint plugin #15377

    CakePHP 3.9.7 breaks muffin/footprint plugin #15377

    This is a (multiple allowed):

    • [x] bug

    • [ ] enhancement

    • [ ] feature-discussion (RFC)

    • CakePHP Version: 3.9.7

    • Platform and Target: nginx,mysql,debian buster

    What you did

    composer update cakephp updating to 3.9.7

    What happened

    after updating cakephp, the muffin/footprint (v1.2.2) throws a 500.

    What you expected to happen

    geting the user from the muffin/footprint plugin

    grafik

    https://github.com/cakephp/cakephp/issues/15377

    opened by reloxx13 5
  • Add Plugin Manifest

    Add Plugin Manifest

    This should enable the correct loading of the plugin, long term and to preempt the warning coming in 4.2. See discussion on CakePHP/CakePHP 4.1.2 bug fix in the long term. CakePHP #14891

    opened by JacobAGTyler 5
Releases(3.0.0)
Owner
Muffin
Muffin
Flexible and rock solid audit log tracking for CakePHP 3

AuditStash Plugin For CakePHP This plugin implements an "audit trail" for any of your Table classes in your application, that is, the ability of recor

José Lorenzo Rodríguez 68 Dec 15, 2022
Open source medical record system on CakePHP (OMCAKE)

omcake v0.1 小さな診療所用の電子カルテ(もどき)です。 奥村晴彦先生のtwitter オープンソースの電子カルテシステムで、WebベースでクライアントOSを選ばず、 サーバは普通のLinuxで動くPHPとか、ないんだろうか。 で唐突に召喚され、それ、ウチにありますけど〜、とノコノコ出てき

古林 敬一 7 Aug 16, 2022
CakePHP3: plugin that facilitates versioned database entities

Version A CakePHP 4.x plugin that facilitates versioned database entities Installation Add the following lines to your application's composer.json: "r

Jose Diaz-Gonzalez 52 Sep 3, 2022
[READ-ONLY] Collection library in CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Collection Library The collection classes provide a set of tools to manipulate arrays or Traversable objects. If you have ever used underscore

CakePHP 85 Nov 28, 2022
[READ-ONLY] The event dispatcher library for CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Event Library This library emulates several aspects of how events are triggered and managed in popular JavaScript libraries such as jQuery: An

CakePHP 21 Oct 6, 2022
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
[READ-ONLY] CakePHP Utility classes such as Inflector, Text, Hash, Security and Xml. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Utility Classes This library provides a range of utility classes that are used throughout the CakePHP framework What's in the toolbox? Hash A

CakePHP 112 Feb 15, 2022
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
User authentication REST API with Laravel (Register, Email verification, Login, Logout, Logged user data, Change password, Reset password)

User Authentication API with Laravel This project is a user authentication REST API application that I developed by using Laravel and MySql. Setup Fir

Yusuf Ziya YILDIRIM 3 Aug 23, 2022
[READ-ONLY] Easy to use Caching library with support for multiple caching backends. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Caching Library The Cache library provides a Cache service locator for interfacing with multiple caching backends using a simple to use interf

CakePHP 49 Sep 28, 2022
[READ-ONLY] A flexible, lightweight and powerful Object-Relational Mapper for PHP, implemented using the DataMapper pattern. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP ORM The CakePHP ORM provides a powerful and flexible way to work with relational databases. Using a datamapper pattern the ORM allows you to m

CakePHP 146 Sep 28, 2022
Cakephp-book allows you to search in the official CakePHP documentation directly from the console.

CakeDC/Book plugin for CakePHP cakephp-book allows you to search in the official CakePHP documentation directly from the console. Requirements CakePHP

Cake Development Corporation 3 Apr 13, 2022
A sample CakePHP api application using CakeDC/cakephp-api and swoole as server

CakePHP Application Skeleton composer create-project --prefer-dist cakephp/app Added sample data using https://github.com/annexare/Countries Created m

Marcelo Rocha 3 Jul 28, 2022
Cbe frontauth - A Textpattern plugin to manage backend connections from frontend and protect content from non-logged users

cbe_frontauth This client-side plugin lets your users (or you) manage backend connection from frontend, i.e. connect and disconnect as they (you) woul

null 4 Jan 31, 2020
Allow your model to record the creation, update and deletion of user fingerprints in laravel packages

This laravel package will allow your models to record the the created, updated and deleted by User FingerPrints

Managemize 4 Mar 11, 2022
Allow any Discord user to sign in to your website and save their discord user information for later use.

Simple Discord SSO ( Single Sign-On ) Requires at least: 5.0 Tested up to: 5.8.3 Stable tag: 1.0.2 Requires PHP: 7.4 License: GPLv2 or later License U

null 2 Oct 7, 2022
🐺 Asynchronous Task Queue Based on Distributed Message Passing for PHP.

?? Asynchronous Task Queue Based on Distributed Message Passing for PHP.

Ahmed 36 Aug 11, 2022
(Live Link) Extensive ecommerce site with vendors, mods & ability to add to cart without being logged in. Upgraded to Laravel 8.x

(Live Link) Extensive ecommerce site with vendors, mods & ability to add to cart without being logged in. Upgraded to Laravel 8.x

null 14 Dec 21, 2022
Prevent players from passing a certain point in your server worlds

WorldBorder Info ~ Prevent players from passing a certain point in your server worlds! Stops glitchers trying to get past the border locking them in a

Hydro 1 Mar 27, 2022