{"id":20012842,"url":"https://github.com/erdiko/authorize","last_synced_at":"2025-05-04T21:31:43.530Z","repository":{"id":56978585,"uuid":"73362947","full_name":"Erdiko/authorize","owner":"Erdiko","description":"User authorization","archived":false,"fork":false,"pushed_at":"2017-08-22T21:07:44.000Z","size":43,"stargazers_count":5,"open_issues_count":0,"forks_count":4,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-08T12:21:09.177Z","etag":null,"topics":["authorization","authorizer","erdiko","pimple","symfony-security","users"],"latest_commit_sha":null,"homepage":"http://erdiko.org/authorize/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Erdiko.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-11-10T08:43:59.000Z","updated_at":"2024-07-09T22:33:26.000Z","dependencies_parsed_at":"2022-08-21T11:50:47.393Z","dependency_job_id":null,"html_url":"https://github.com/Erdiko/authorize","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Erdiko%2Fauthorize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Erdiko%2Fauthorize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Erdiko%2Fauthorize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Erdiko%2Fauthorize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Erdiko","download_url":"https://codeload.github.com/Erdiko/authorize/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252404162,"owners_count":21742506,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authorization","authorizer","erdiko","pimple","symfony-security","users"],"created_at":"2024-11-13T07:33:34.051Z","updated_at":"2025-05-04T21:31:43.117Z","avatar_url":"https://github.com/Erdiko.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Erdiko Authorize\n\n[![Package version](https://img.shields.io/packagist/v/erdiko/authorize.svg?style=flat-square)](https://packagist.org/packages/erdiko/authorize)\n[![CircleCI](https://img.shields.io/circleci/project/github/Erdiko/authorize/develop.svg?style=flat-square)](https://circleci.com/gh/Erdiko/authorize)\n[![license](https://img.shields.io/github/license/erdiko/authorize.svg?style=flat-square)](https://github.com/Erdiko/authorize/blob/master/LICENSE)\n\n**Authorize**\n\nAn Erdiko package to provide user authorization.\n\nCompatibility\n-------------\nThis package is compatible with PHP 5.4 or above and the latest version of Erdiko.\n\nInstallation\n------------\nAdd the eridko/authorize package using composer with this command:\n\n`composer require erdiko/authorize`\n\n##### Requirements\n\nBetween its requirements we count on Pimple and Symfony Security.\nIn case of Pimple, we choose this package to manage Dependency Injection, allowing us to add more flexibility and \nextensibility. \nIt also adds compatibility with Symfony Security module.\n\n\nHow to Use\n----------\n\nOnce you have installed the package you are ready to start. Basic Role based Admin validation works out of the box!\n\nTo start using it in your code just create an instance of `Authorizer` class. This class will expect an instance of\n`AuthenticationManagerInterface` from symfony/security package as a constructor parameter.\n\nHere's an example:\n ```php\n class AuthenticationManager implements AuthenticationManagerInterface\n {\n     private $authenticationManager;\n\n     public function __construct()\n     {\n         // implements UserProviderInterface\n         $userProvider = new InMemoryUserProvider(\n             array(\n                 'bar@mail.com' =\u003e array(\n                     'password' =\u003e 'asdf1234',\n                     'roles'    =\u003e array('ROLE_ADMIN'),\n                 ),\n                 'foo@mail.com' =\u003e array(\n                     'password' =\u003e 'asdf1234',\n                     'roles'    =\u003e array('ROLE_USER'),\n                 ),\n             )\n         );\n\n         // Create an encoder factory that will \"encode\" passwords\n         $encoderFactory = new \\Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactory(array(\n             // We simply use plaintext passwords for users from this specific class\n             'Symfony\\Component\\Security\\Core\\User\\User' =\u003e new PlaintextPasswordEncoder(),\n         ));\n\n         // The user checker is a simple class that allows to check against different elements (user disabled, account expired etc)\n         $userChecker = new UserChecker();\n         // The (authentication) providers are a way to make sure to match credentials against users based on their \"providerkey\".\n         $userProvider = array(\n             new DaoAuthenticationProvider($userProvider, $userChecker, 'main', $encoderFactory, true),\n         );\n\n\n         $this-\u003eauthenticationManager = new AuthenticationProviderManager($userProvider, true);\n     }\n\n     public function authenticate(TokenInterface $unauthenticatedToken)\n     {\n\n         try {\n             $authenticatedToken = $this-\u003eauthenticationManager-\u003eauthenticate($unauthenticatedToken);\n             Authorizer::startSession();\n             $tokenStorage = new TokenStorage();\n             $tokenStorage-\u003esetToken($authenticatedToken);\n             $_SESSION['tokenstorage'] = $tokenStorage;\n         } catch (\\Exception $failed) {\n             // authentication failed\n             throw new \\Exception($failed-\u003egetMessage());\n         }\n         return $authenticatedToken;\n     }\n }\n ```\n\nIt’s a best practice to add instance creation in the `_before` hook. An example of this best practice looks like this:\n\n ```php\n ...\n     public function _before()\n     {\n         $authManager = new AuthenticationManager();\n         $this-\u003eauth = new Authorizer($authManager);\n         // Run the parent beore filter to prep the theme\n         parent::_before();\n     }\n ...\n ```\n\nYou will then have a `$this-\u003eauth` attribute available to use in any _get_ or _post_ action. This will be used in `can`\nmethods that determine access, allowing you to grant or reject access to a resource.\n\nFor example, if current user has ADMIN role, then it will be redirected to admin dashboard (GRANTED), otherwise the user\nwill be redirected to login page (REJECTED).\n\n ```\n    php public function getDashboard()\n    {\n        if($this-\u003eauth-\u003ecan(\"VIEW_ADMIN_DASHBOARD\")) {\n            // Add page data\n            $this-\u003esetTitle('Erdiko Admin Dashboard');\n            $this-\u003eaddView('examples/admin/dashboard');\n        } else {\n            \\erdiko\\core\\helpers\\FlashMessages::set(\"You SHALL NO Pass!!\", \"danger\");\n            $this-\u003eredirect('/users/login');\n        }\n    }\n ```\nNote that in this example, current user is an instance of `Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface`,\nstored in `$_SESSION['tokenstorage']`.\n\nAlso available is the “VIEW_ADMIN_DASHBOARD” attribute we will use to grant or reject access for the current user.\n\nYou can use the same logic to validate Models by adding a `__construct` method where you will place the authorize creation\n\n```php\n   public function __construct()\n   {\n       $authManager = new AuthenticationManager();\n       $this-\u003eauth = new Authorizer($authManager);\n   }\n```\n\nSame for GRANT/REJECT:\n```php\n   public function doSomething1()\n   {\n       if($this-\u003eauth-\u003ecan(\"CAN_DO_1\")) {\n           return \"success something one\";\n       } else {\n           throw new \\Exception(\"You are not granted\");\n       }\n   }\n```\n\nCustomization\n-------------\n\nThis package provides you with a framework to create custom validation. There are two different methods to create custom\nvalidation:\n- Custom Voters\n\nImplement `Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface`\ninterface, and pass them in an array as second argument of `Authorizer` constructor.\n\n- Custom Validator\n\nOr you can create a `Validator` class that implements `erdiko\\authorize ValidatorInterface` interface.\nThen you will have to register all validators in `/app/config/default/authorize.json`, and voila, all the custom validation\nlogic you've created is already available to the authorizer.  \n\nauthorize.json\n```json\n{\n     \"validators\":{\n       \"custom_types\": [{\n         \"name\": \"example\",\n         \"namespace\": \"app_validators_example\",\n         \"classname\": \"ExampleValidator\",\n         \"enabled\": true\n       }]\n     }\n   }\n```\n\nIn these validator classes you will be able to define custom attributes, \"VIEW_ADMIN_DASHBOARD\" as we mention above,\nwe might want to add \"IS_PREMIUM_ACCOUNT\", or any other attributes you want.\n\nNote that `namespace` field of the above JSON indicate the class `namespace` and is related to the app root folder,\ne.g. `/app/validators/example/ExampleValidator.php`\n\nLet's implement the example class registered in the example JSON.  \n\n```php\nclass ExampleValidator implements ValidatorInterface\n{\n    public static function supportedAttributes()\n    {\n        return array('IS_PREMIUM_ACCOUNT');\n    }\n\n    public function supportsAttribute($attribute)\n    {\n        return in_array($attribute, self::supportedAttributes());\n    }\n\n    public function validate($token)\n    {\n        $result = false;\n        $user = $token-\u003egetUser();\n        if (!$user instanceof UserInterface) {\n            $result = false;\n        } else {\n            $result = ($user-\u003egetRole()=='ROLE_PREMIUM');\n        }\n        return $result;\n    }\n}\n```\n\n\nSpecial Thanks\n--------------\n\nArroyo Labs - For sponsoring development, [http://arroyolabs.com](http://arroyolabs.com)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ferdiko%2Fauthorize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ferdiko%2Fauthorize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ferdiko%2Fauthorize/lists"}