Giter Site home page Giter Site logo

jasongrimes / silex-simpleuser Goto Github PK

View Code? Open in Web Editor NEW
168.0 22.0 82.0 1.47 MB

A simple, extensible, database-backed user provider for the Silex security service.

Home Page: http://www.jasongrimes.org/2014/09/simple-user-management-in-silex

License: BSD 2-Clause "Simplified" License

PHP 100.00%

silex-simpleuser's Introduction

Simple User Provider for Silex

Build Status Total Downloads Latest Stable Version Latest Unstable Version

A simple, extensible, database-backed user provider for the Silex security service.

SimpleUser is an easy way to set up user accounts (authentication, authorization, and user administration) in the Silex PHP micro-framework. It provides drop-in services for Silex that implement the missing user management pieces for the Security component. It includes a basic User model, a database-backed user manager, controllers and views for user administration, and various supporting features.

Demo

Upgrading

If you're upgrading from 1.x, you'll need to update the database for version 2.0. Tools are provided to make this database migration relatively painless. See sql/MIGRATION.md for details.

Quick start example config

This configuration should work out of the box to get you up and running quickly. See below for additional details.

Install with composer. This command will automatically install the latest stable version:

composer require jasongrimes/silex-simpleuser

Set up your Silex application something like this:

<?php

use Silex\Application;
use Silex\Provider;

//
// Application setup
//

$app = new Application();
$app->register(new Provider\DoctrineServiceProvider());
$app->register(new Provider\SecurityServiceProvider());
$app->register(new Provider\RememberMeServiceProvider());
$app->register(new Provider\SessionServiceProvider());
$app->register(new Provider\ServiceControllerServiceProvider());
$app->register(new Provider\UrlGeneratorServiceProvider());
$app->register(new Provider\TwigServiceProvider());
$app->register(new Provider\SwiftmailerServiceProvider());

// Register the SimpleUser service provider.
$simpleUserProvider = new SimpleUser\UserServiceProvider();
$app->register($simpleUserProvider);

// ...

//
// Controllers
//

// Mount the user controller routes:
$app->mount('/user', $simpleUserProvider);

/*
// Other routes and controllers...
$app->get('/', function () use ($app) {
    return $app['twig']->render('index.twig', array());
});
*/

// ...

//
// Configuration
//

// SimpleUser options. See config reference below for details.
$app['user.options'] = array();

// Security config. See http://silex.sensiolabs.org/doc/providers/security.html for details.
$app['security.firewalls'] = array(
    /* // Ensure that the login page is accessible to all, if you set anonymous => false below.
    'login' => array(
        'pattern' => '^/user/login$',
    ), */
    'secured_area' => array(
        'pattern' => '^.*$',
        'anonymous' => true,
        'remember_me' => array(),
        'form' => array(
            'login_path' => '/user/login',
            'check_path' => '/user/login_check',
        ),
        'logout' => array(
            'logout_path' => '/user/logout',
        ),
        'users' => $app->share(function($app) { return $app['user.manager']; }),
    ),
);

// Mailer config. See http://silex.sensiolabs.org/doc/providers/swiftmailer.html
$app['swiftmailer.options'] = array();

// Database config. See http://silex.sensiolabs.org/doc/providers/doctrine.html
$app['db.options'] = array(
    'driver'   => 'pdo_mysql',
    'host' => 'localhost',
    'dbname' => 'mydbname',
    'user' => 'mydbuser',
    'password' => 'mydbpassword',
);

return $app;

Create the user database:

mysql -uUSER -pPASSWORD MYDBNAME < vendor/jasongrimes/silex-simpleuser/sql/mysql.sql

Note: if you're upgrading from SimpleUser 1.x, follow the instructions in sql/MIGRATION.md instead, to migrate the database without losing existing data.

You should now be able to create an account at the /user/register URL. Make the new account an administrator by editing the record directly in the database and setting the users.roles column to ROLE_USER,ROLE_ADMIN. (After you have one admin account, it can grant the admin role to others via the web interface.)

Config options

All of these options are optional. SimpleUser can work without any configuration at all, or you can customize one or more of the following options. The default values are shown below.

$app['user.options'] = array(

    // Specify custom view templates here.
    'templates' => array(
        'layout' => '@user/layout.twig',
        'register' => '@user/register.twig',
        'register-confirmation-sent' => '@user/register-confirmation-sent.twig',
        'login' => '@user/login.twig',
        'login-confirmation-needed' => '@user/login-confirmation-needed.twig',
        'forgot-password' => '@user/forgot-password.twig',
        'reset-password' => '@user/reset-password.twig',
        'view' => '@user/view.twig',
        'edit' => '@user/edit.twig',
        'list' => '@user/list.twig',
    ),

    // Configure the user mailer for sending password reset and email confirmation messages.
    'mailer' => array(
        'enabled' => true, // When false, email notifications are not sent (they're silently discarded).
        'fromEmail' => array(
            'address' => 'do-not-reply@' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : gethostname()),
            'name' => null,
        ),
    ),

    'emailConfirmation' => array(
        'required' => false, // Whether to require email confirmation before enabling new accounts.
        'template' => '@user/email/confirm-email.twig',
    ),

    'passwordReset' => array(
        'template' => '@user/email/reset-password.twig',
        'tokenTTL' => 86400, // How many seconds the reset token is valid for. Default: 1 day.
    ),

    // Set this to use a custom User class.
    'userClass' => 'SimpleUser\User',

    // Whether to require that users have a username (default: false).
    // By default, users sign in with their email address instead.
    'isUsernameRequired' => false,

    // A list of custom fields to support in the edit controller.
    'editCustomFields' => array(),

    // Override table names, if necessary.
    'userTableName' => 'users',
    'userCustomFieldsTableName' => 'user_custom_fields',

    //Override Column names, if necessary
    'userColumns' = array(
        'id' => 'id',
        'email' => 'email',
        'password' => 'password',
        'salt' => 'salt',
        'roles' => 'roles',
        'name' => 'name',
        'time_created' => 'time_created',
        'username' => 'username',
        'isEnabled' => 'isEnabled',
        'confirmationToken' => 'confirmationToken',
        'timePasswordResetRequested' => 'timePasswordResetRequested',
        //Custom Fields
        'user_id' => 'user_id',
        'attribute' => 'attribute',
        'value' => 'value',
    ),
);

More information

See the Silex SimpleUser tutorial.

silex-simpleuser's People

Contributors

cinu avatar corpulent avatar fbatiga avatar jasongrimes avatar parsingphase avatar ryanhalliday 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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

silex-simpleuser's Issues

[error] PHP Warning: Parent session handler is not open

During user logout process I've got the message:
[Tue Oct 01 07:24:48 2013] [error] [client 127.0.0.1] PHP Warning: SessionHandler::close(): Parent session handler is not open in ...
Is it PHP bug ? Or do we have some workaround?

SimpleUser in combination with silex 2.0 (dev)

Is there a way to work with silex 2.0 (dev version) and this library? Because I've written a whole lot of code in silex 2.0 but now I see that I need to have silex 1.0 installed to work with the simpleuser library.

Is there a work-around?

Wierd sql error when trying to register

An exception occurred while executing 'SELECT * FROM `users` WHERE `email` = :`email` ':

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':`email`' at line 1

Add rate limiting to certain actions

It would make sense to add rate limiting to the following actions to prevent automated attempts to compromise user accounts:

  • Login
  • Forgot password
  • Resend confirmation email

Composer install: Your requirements could not be resolved to an installable set of packages.

Here is my Cmd-Log:

    composer require jasongrimes/silex-simpleuser
    Using version ^2.0 for jasongrimes/silex-simpleuser
    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.

      Problem 1
        - The requested package jasongrimes/silex-simpleuser 1.0.0 could not be found.

    Potential causes:
     - A typo in the package name
     - The package is not available in a stable-enough version according to your minimum-stability setting
       see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

    Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

    Installation failed, reverting ./composer.json to its original content.

Any Idea what causes that problem?

Project Abandoned

I don't enjoy writing this message, but I am confident this project has been abandoned.
The last commit from Jason was Nov 2, 2014.

Here are three solutions other than this project:

  • Use some external OAuth system that is relevant.
  • Some other more generic authentication library (Symfony Security, Sentry etc.)
  • Roll your own, be sure to use password_hash and good security practices.

psr-4

I've got problems with simpleuser and psr-4.
It doesn't find my User class in

src/Model/User.php
namespace Project\Model

in composer.json
psr-4 "Project": "src"

Fatal error: Call to undefined method

I'm not sure if I've missed something, but I followed the instruction and got this?

Fatal error: Call to undefined method Symfony\Component\HttpKernel\Event\GetResponseEvent::isMasterRequest() in /var/www/php/ProjectName/vendor/symfony/security/Symfony/Component/Security/Http/Firewall.php on line 53

Cheers,

Ewan

Provide support for internationalisation

It'd be nice to use this plugin on sites that aren't in English. I'd be happy to work on a PR for this and integrate with the Translation component. Let me know :)

Base class of SimpleUser\User no longer supported in 1.2

https://github.com/jasongrimes/silex-simpleuser/tree/2e65ad7690265fe283fb197f3987ea32d78ebe84 removes the ability to use the base class 'SimpleUser\User' as the User object. Is this intentional?

UserManager.php:

 public function supportsClass($class)
 {
-        return $class === 'SimpleUser\User';
+        return is_subclass_of($class, 'SimpleUser\User');
 }

Problem is that classes are not considered subclasses of themselves, at least in PHP 5.5.9-1ubuntu4.3:

<?php
$cs = new stdClass;
echo is_subclass_of($cs,'stdClass')?'yes':'no';   
echo "\n";


no

Quite happy to put in a PR for this (probably just an OR of the above lines, but if you want me to do a PR, I'll test fully) if it's not intended, or either lock to v1.1 or adapt to the changes in 1.2 if it is - but this is a BC break in a minor version upgrade, and so should ideally either be a major version number update or have a warning somewhere in docs!

Thanks,
Richard

Deprecated SecurityContext class

After start app see this message:

Deprecated: The Symfony\Component\Security\Core\SecurityContext class is deprecated since version 2.6 and will be removed in 3.0. Use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage or Symfony\Component\Security\Core\Authorization\AuthorizationChecker instead. in /home/www/public_html/sf.bandis.ru/vendor/symfony/security/Core/SecurityContext.php on line 14 Deprecated: The Symfony\Component\Security\Core\SecurityContextInterface interface is deprecated since version 2.6 and will be removed in 3.0. in /home/www/public_html/sf.bandis.ru/vendor/symfony/security/Core/SecurityContextInterface.php on line 14

I guess error in this code (in UserServiceProvoder class):

$app['user.last_auth_exception'] = $app->protect(function (Request $request) {
            if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
                return $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
            }

            $session = $request->getSession();
            if ($session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
                $exception = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR);
                $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);

                return $exception;
            }
        });

Symphony docs says ( http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements )

// Symfony 2.5
use Symfony\Component\Security\Core\SecurityContextInterface;
if ($security->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { ... }

// Symfony 2.6
use Symfony\Component\Security\Core\Security;
if ($security->has(Security::AUTHENTICATION_ERROR)) { ... }

But I can't find place where shoud redeclare $app['user.last_auth_exception']

SImpleUser and SIlex 2.0

I had a project written in Silex 2.0 that I wanted to use SimpleUser with. Given that this project no longer appears to be being maintained, I have forked a project from Jason's SimpleUser modified the code and unit tests so that they run under Silex 2.0. The fork is located at https://github.com/DaveC49/SimpleUser-Silex2 and can be loaded using "composer require davec49/silex2-simpleuser".
The unit tests all complete successfully but as of 27/11/2016 I have not yet tested the fork functionally.

DaveC49

Typo in README.md

'userColumns' = array(
    'id' => 'id',
    'email' => 'email',
    'password' => 'password',
    'salt' => 'salt',
    'roles' => 'roles',
    'name' => 'name',
    'time_created' => 'time_created',
    'username' => 'username',
    'isEnabled' => 'isEnabled',
    'confirmationToken' => 'confirmationToken',
    'timePasswordResetRequested' => 'timePasswordResetRequested',
    //Custom Fields
    'user_id' => 'user_id',
    'attribute' => 'attribute',
    'value' => 'value',
),

Should be:

'userColumns' => array(
    'id' => 'id',
    'email' => 'email',
    'password' => 'password',
    'salt' => 'salt',
    'roles' => 'roles',
    'name' => 'name',
    'time_created' => 'time_created',
    'username' => 'username',
    'isEnabled' => 'isEnabled',
    'confirmationToken' => 'confirmationToken',
    'timePasswordResetRequested' => 'timePasswordResetRequested',
    //Custom Fields
    'user_id' => 'user_id',
    'attribute' => 'attribute',
    'value' => 'value',
),

Incorrect array key assignment operator :)

Exception raised when the user log out

Hello !

When I try to log out an exception is raised.

LogicException in HttpKernel.php line 157:
The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?

Updating user's isEnabled field receive sql error

when changing the user isEnabled value to false, will receive sql error "General error: 1366 Incorrect integer value: '' for column 'isEnabled' at row 1"

namely because a string "false" is passed into the sql query instead of int 0.

Changing user_manager class at line 538 to 'isEnabled' => intval($user->isEnabled()), will solve the problem.

Failure after creating user

After registering, when email confirmation is disabled, i get redirected to /user/login, with the following exception.

There is no user provider for user "SimpleUser\User"

Add a username field in the User class

Hello,

I think you should add a username field to the bundle, maybe along with a login function that supports both email and username.

It would make the class much more useful, and we wouldnt have to always extends de user class.

cheers

How to store custom fields value (From a form eg: in register.twig) in the database ?

I have added two custom fields like this:

schermata del 2015-05-24 17 03 24

I have also added getters and setters as mentioned above
in my VibeSMS\Model\User extends SimpleUser\User

schermata del 2015-05-24 16 58 56

and also edited register.twig adding two text fields (firstName and lastName)

schermata del 2015-05-24 17 01 49

but when i register an user through /user/register the app doesn't store my custom fields value in the database but it works in the /user/{id}/edit. Any idea o suggestion for helping ??

Custom table names causing sql issues

This is related to issue #37.
By introducing custom columns and escaping them in the scripts, a little bug came in.
It manifests when you use mysql and here's the error I get when trying to create account:
An exception occurred while executing 'SELECT * FROM `user` WHERE `email` = :`email` ':

I guess the reason for this is that SQLite, which is used for testing, would quote everything like:
'SELECT * FROM "user" WHERE "email" = :"email" ', which for some reason resolves to proper SQL.

Since I needed it functioning on my little home project, I've already implemented the bugfix.
I hope you don't mind this unauthorized conservation.

P.S.
This my first github issue report, and your project is the first I'm contributing to.
So I want to use this chance to say hello. Your project is a cool and very helpful Silex extension.
Thanks!

oAuth

Are there any samples that silex-simpleuser can be integrated with an oAuth?

ORM Design ?

Hey there,
First, I love this bit of code. Just went to start a project, used your SimpleUser, pretty easy. Wonderful. Then I still have some questions :

  • Is there any reason you decided not to go with ORM/Doctrine for the User class ? It would make the setup relatively easy to some extent. And mix well with most of the projects out there.
  • I have seen that the fork from @PKuebler has added a nice userManager options to replace the original userManager from your code, thus making it easy to add some Doctrine Entity Manager :)
  • More "Technical" stuff (remind that I am relatively new to Silex/Symfony) : I am trying to use your code in connection with AuthBucket/OAuth2-php but for some reason, there is no authentication provider available in $app["security.user_provider.default"]. Is there a thing I didn't understand in other package, I am missing something or is something not registered from your side ?

Update : There seem to be an issue with the token being a RememberMeToken instead of a UsernamePasswordToken for the Authbucket integration

MongoDB?

Hi,

Does anyone know if this works with MongoDB? If so, how to set it up?

Kind regards,
Sid

Moving the username to the user table

Hey Jason,
i'm thinking about moving the username to the main table, instead of the custom field. In most of my apps, the username is way more used than the email.
Also, i'm using doctrine Orm, and because of the username, i find myself loading the custom fields data, hence loosing the lazy loading features of doctrine.

How do you think i should go about it ? extending the usermanager ? or creating a pull request ?

Also i'm thinking about adding an option to define the "users" table name. I usually have my tables being singular (ie "USER" instead of "USERS"), and one can want to use Admin instead of users, or even other languages ...

let me know what you think.

Changeable SQL Column Names

Currently it appears to me that the only way to change the column names is to extend and partially rewrite the UserManager because the column names are written in there.

Would you like me to rewrite parts of the UserManager to include this modularity so that Column names can be defined like:

$app['user.options'] = array(
    'userColumns' => array(
        'id' => 'my_column_name',
        'email' => 'my_column_name',
        'password' => 'my_column_name',
        'salt' => 'my_column_name',
        'roles' => 'my_column_name',
        'name' => 'my_column_name',
        'time_created' => 'my_column_name',
        'username' => 'my_column_name',
        'isEnabled' => 'my_column_name',
        'confirmationToken' => 'my_column_name',
        'timePasswordResetRequested' => 'my_column_name'
    )
);

Installation failed, your reqs couldn't be resolved

When I ran the command, "composer require jasongrimes/silex-simpleuser", I received the error below.

php composer.phar require jasongrimes/silex-simpleuser
Using version ^2.0 for jasongrimes/silex-simpleuser
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1

  • jasongrimes/silex-simpleuser 2.0.1 requires doctrine/dbal ~2.4 -> no matching package found.
  • jasongrimes/silex-simpleuser 2.0 requires doctrine/dbal ~2.4 -> no matching package found.
  • Installation request for jasongrimes/silex-simpleuser ^2.0 -> satisfiable by jasongrimes/silex-simpleuser[2.0, 2.0.1].

Potential causes:

Read https://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

registrationAction not storing custom fields

Hi,
i have created an extended User and addeda number of custom fields as described in the tutorial. I found that the custom fields were not being stored in the database on registration. I had also setup validation in the extended User class for these custom fields and i found this was failing because the custom fields were not defined. I noted another users comment that the editAction did allow editing and saving of the custom fields on examining the code for the editAction and the registerAction, I found the code in the UserController::createUserFromRequest() method did not load the custom fields data from the request into the $user instance of the User class whereas the corresponding code in the editAction did. I extended the UserController and overrode the createUserFromRequest() method in the extended controller and added the following code copied from the editAction.

    $customFields = $this->editCustomFields ?: array();

    foreach (array_keys($customFields) as $customField) {
        if ($request->request->has($customField)) {
            $user->setCustomField($customField, $request->request->get($customField));
        }
    }

and then overrode the $app['user.controller'] in my bootstrap file with the extended UserController. This has resulted in the registerAction successfully storing the new user from the registerAction in the database and allowing the validation code I added in my extended User class to run and validate the custom fields in addition to the user table fields.

This seems to have resolved the issue of storing the customFields from the registerAction. It would be perhaps better to include the above code in the SimpleUser\UserController.

Cheers

David Cousens

Provide options to disable certain actions

Hi,

I suggest providing global options to disable the following actions within SimpleUser:

  • Registration - some people might use SimpleUser to manage administration, but prefer to add users manually (or via database)
  • Login/logout - under certain circumstances it might be preferable to disable the ability to login/logout for anyone but administrators.
  • User list - many people might not want to show the full list of users. This is a security risk in fact, to show the full list of users (including admins)

I'm happy to work on a PR for this, let me know :)

Security Issue: All forms are vulnerable to CSRF

Right now this is a security issue, as CSRF can occur.

You should consider moving decoupling all forms into an AbstractType and using the SF2 Form component.

One benefit of this is you can re-use forms elsewhere (and so can people who use the library). Also if you bump up the dependency to SF2.6 you can also use bootstrap form theme out the box, so the templates will also be a lot simpler.

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.