usr

Yii framework module for user authentication, password reset, registration and profile updating.
22 followers

About

Usr module is inspired by the popular Yii-user module but written from scratch. It provides basic user actions like:

  • logging in and out,
  • password recovery and reset if expired
  • registration with optional email verification,
  • viewing and updating a minimal user profile along with changing password, profile pictures are supported
  • user managment

It's goal is to be easier to integrate into current projects by not requiring to modify existing user database table and model. Only the UserIdentity class is used to provide all business logic by implementing few provided interfaces.

Key differences from yii-user:

  • clean codebase, easier to read/review
  • use good password hashing
  • no need to modify current tables and models
  • bundled mailer class
  • built-in Hybridauth for logging using social site identities
  • built-in Google Authenticator for two step authentication using one time passwords

Resources

Installation

Using composer:

[bash]
curl -sS https://getcomposer.org/installer | php
./composer.phar require nineinchnick/yii-usr:dev-master

Download and unpack in protected/modules.

Enable the module in the config/main.php file:

return array(
    ......
    'modules'=>array(
        'usr'=>array(
               'userIdentityClass' => 'UserIdentity',
        ),
    ),
)

See UsrModule.php file for full options reference.

To be able to use user managment, create auth items using the createAuthItems command and assign them to a role or users.

Fast setup and/or new projects

This assumes there are no user tables in the database and all features can be enabled.

  • Copy migrations files from the module to your project and adjust their filenames and class names. Apply them.
  • Copy the ExampleUserIdentity to your components directory changing it's name to UserIdentity, remove the abstract keyword from the class definition.
  • Copy each file starting with Example from the models directory to your projects and remove that prefix. Remove the abstract keyword from the class definition.

Custom setup and/or existing projects

If the module will be used with existing database tables and/or not all features will be used the identity class should be copied and adjusted or reimplemented from scratch.

Requirements for the UserIdentity class are described in next chapter.

Identity interfaces

To be able to use all features of the Usr module, the UserIdentity class must implement some or all of the following interfaces.

For details, please read comments in each identity file or see the provided ExampleUserIdentity file.

Editable

This interface allows to create new identities (register) and update existing ones.

Active/disabled and email verification

This interface allows:

  • finding existing identities using one of its attributes.
  • generating and verifying an activation key used to verify email and send a recovery link

Remember to invalidate the email if it changes in the save() method from the Editable interface.

Password history

This interface allows password reset with optional tracking of used passwords. This allows to detect expired passwords and avoid reusing old passwords by users.

Hybridauth

This interface allows finding local identity associated with a remote one (from an external social site) and creating such associations.

One Time Password

This interface allow saving and retrieving a secret used to generate one time passwords. Also, last used password and counter used to generate last password are saved and retrieve to protect against reply attacks.

Profile Pictures

Allows users to upload a profile picture. The example identity uses Gravatar to provide a default picture.

Managable

Allows to manage users:

  • update their profiles (and pictures)
  • change passwords
  • assign authorization roles
  • activate/disable and mark email as verified
  • see details as timestamps of account creation, last profile update and last visit

User model example

A sample ExampleUserIdentity and corresponding ExampleUser and ExampleUserUsedPassword models along with database migrations are provided respectively in the 'components', 'models' and 'migrations' folders.

They could be used as-is by extending from or copying to be modified to better suit a project.

To use the provided migrations it's best to copy them to your migrations directory and adjust the filenames and classnames to current date and time. Also, they could be modified to remove not needed features.

Diceware aka password generator

A simple implementation of a Diceware Passphrase generator is provided to aid users when they need to create a good, long but also easy to remember passphrase.

Read more at the Diceware Passphrase homepage.

Customize

Custom profile fields

It is possible to add more profile fields:

  • Override view files in a theme.
  • Create a behavior class extending FormModelBehavior.
  • Add that behvaior in the UsrModule::profileFormBehaviors property.
  • Remember to update setAttributes and getAttributes methods of your UserIdentity class to include new profile fields.

The behavior will include properties, rules and labels. Rules can contain inline validators defined in that behavior, just call them using the behaviorValidator helper method:

// BEHAVIOR_NAME is the key used in UsrModule::profileFormBehaviors
   // INLINE_VALIDATOR is the name of the inline validator method defined in the behavior
   array('attribute', 'behaviorValidator', 'behavior'=>'BEHAVIOR_NAME', 'validator'=>'INLINE_VALIDATOR', /* other params */),

Email templates

Set the setPathViews and setPathLayouts keys under the mailerConfig module option.

Translations

Feel free to send new and updated translations to the author.

Usage scenarios

Varios scenarios can be created by enabling or disabling following features:

  • registration
  • email verification
  • account activation

Implementing those scenarios require some logic outside the scope of this module.

Public site

Users can register by themselves. Their accounts are activated instantly or after verifying email.

Moderated site

Users can register, but to allow them to log in an administrator must activate their accounts manually, optionally assigning an authorization profile. Email verification is optional and activation could trigger an email notification.

Configuration for Twitter Bootstrap

If using the bootstrap extension, the following configuration may be used:

'usr' => array(
        'layout' => '//layouts/centered',
        'formClass'=>'bootstrap.widgets.TbActiveForm',
        'detailViewClass'=>'bootstrap.widgets.TbDetailView',
        'formCssClass'=>'form well',
        'alertCssClassPrefix'=>'alert alert-',
        'submitButtonCssClass'=>'btn btn-primary',
        'htmlCss' => array(
            'errorSummaryCss' => 'alert alert-error',
            'errorMessageCss' => 'text-error',
            ),
        // mail
        ...mail config...
    ),

Besides that, all views could be overriden in a theme. A following skin can be used for user managment grid:

<?php
return array(
    'default' => array(
        'itemsCssClass' => 'table table-striped table-bordered table-condensed',
        'pagerCssClass' => 'paging_bootstrap pagination',
    ),
);

License

MIT or BSD

Total 19 comments

#15749 report it
AndrewM at 2013/12/12 03:11am
Login History

Will do - I forgot about that!

#15748 report it
nineinchnick at 2013/12/12 02:53am
Login History

Thanks for reporting, I will take care of this. Could you create an issue in the Github repo?

#15747 report it
AndrewM at 2013/12/12 01:35am
Login History

Reviewing this, I notice that the authenticate method in your ExampleUserIdentity class updates the last_visit_on attribute of the ExampleUser model. I know this is an example, but I don't believe that should be the way it works, because:

1) You're effectively creating a side-effect in the authenticate method. I believe that as implemented (and I don't pretend to understand it all!), the authenticate method is not just called at login - for example it's also called when the password is changed.

2) The authenticate method is not called during initial registration.

So the net result would be that last_visit_on would not be updated correctly.

I believe the correct approach if this functionality is needed (and I do need it!) would be to override the afterLogin method of the CWebUser class, or maybe create an additional interface (eg ILoginHistoryIdentity) that ExampleUserIdentity should implement and that would get called from your own afterLogin methods.

#15711 report it
nineinchnick at 2013/12/09 04:37am
v0.9.8

You're right Andrew, right after releasing 0.9.8 I found numerous bugs. I'm waiting to release 1.0 after finishing up unit and functional tests.

The Github version is the most recent. I'm in the middle of porting it to Yii 2 and doing further refactoring to separate extra features logic. That's causing small but fatal errors.

I'm going to clean it all up today and release 0.9.9 before further changes.

#15706 report it
AndrewM at 2013/12/08 04:45pm
Problems with v0.9.8 - what's the best alternate version

I just downloaded v0.9.8 to take a look at this. There are multiple problems as a result of the refactoring and new features that prevent this working "out of the box". For example some migration names & table references don't reflect the fact the table names have changed to use the plural form. There are also other exceptions, such as SQL inserts failing due to missing attributes. Note also the extension's demo website (linked above) does not respond to Submission of the registration form - debugging the Post response shows an incorrect table name, as I mentioned above.

The problems I encountered before giving up on v0.9.8 look like they are fixed in Github, but the latest version appears to be a work in progress as it has immediate PHP syntax issues if you try and run it as is.

So what is the most recent stablest version that would be suitable for reviewing? Or is there a new version imminent?

#15296 report it
nineinchnick at 2013/10/24 03:15pm
HybridAuth

@Ne0nx3r0 it took me some time but I added Hybridauth. It's in Github but I haven't prepared a new release yet.

New stuff can be tested on the demo page.

@Aaron I'm going to work on it next, along with SSO using Kerberos.

I invite anybody to report issues and/or ideas on the Github project page.

#15126 report it
Aaron at 2013/10/09 10:31pm
Time-based One-Time Passwords

It would be nice if this supported Time-based One-time Password authentication (i.e.: Google Authenticator).

#15081 report it
nineinchnick at 2013/10/05 01:17pm
instructions

This module is indented to be integrated with existing applications. Provided examples are just examples, not a final solution. You should adjust them to your needs. See the demo sources for a really basic setup.

Migrations that create tables assume that you have tablePrefix set to an empty string.

#15071 report it
LIAL at 2013/10/04 01:31pm
Create normal how-to-install

May be your extension great, but write normal instructions (may be step by step) how to install you extension. - Should I rename ExampleUser and ExampleUserIdentity to User and UserIdentity ? - Why DB has name with double curly brackets ? Is it normal?

It's not trivial to understand how your module to get alive (working). installation instruction is too poor.

#14752 report it
marvix at 2013/09/07 04:03am
more simple!

Am new to Yii, am searching for simple User module with user admin, and it seems no one had created like this extension.

Or, yes it exsist but am searching in worng area ...

#14724 report it
nineinchnick at 2013/09/06 02:48am
db

Maybe you'd want a cleaner, simpler version of user login and registration. I made it for my apps that started with a legacy DB that other software is using and where the user table can't be modified. Other extensions providing login/registration require either to adjust your user table or alter the extension. This one interacts with the underlying data only through the UserIdentity class. That includes hashing password, so it's not limited to built-in methods.

#14721 report it
marvix at 2013/09/05 06:28pm
Then ..

If my app already have user management with db, why do i need usr ?

#14719 report it
nineinchnick at 2013/09/05 04:54pm
db

This extension is intented to easily integrate with existing projects which already contain a User model with corresponding db table. There are examples provided to help implementing your own UserIdentity class. There is no example schema, only a migration that creates a user table.

#14718 report it
marvix at 2013/09/05 04:07pm
Data ?

there is no data folder or file!

#14717 report it
marvix at 2013/09/05 04:05pm
How with DB

How to use it with DB ... can you give full example .. please!

#14488 report it
nineinchnick at 2013/08/16 02:50pm
Update profile email

I've created a new version with a migration creating user table.

Also added email verification after change through profile form.

#14085 report it
Skylight at 2013/07/17 07:48pm
Update profile email

Hi, This is an awesome module, great job with it! Looking forward to seeing the database schema..

A small question here... On the update profile page, the user can change his email ... Isn't it better to send a confirmation email to the new one ? (It should have a slightly different logic I suppose). What do you think ?

#14034 report it
nineinchnick at 2013/07/12 02:19pm
OpenID

I haven't looked into OpenID yet. This module was developed for small, private and moderated sites. I'm all for new features, but I need to have some personal interest in this or (more) user demand :-)

#14030 report it
Ne0nx3r0 at 2013/07/12 11:54am
OpenID Support

I realize this was just released, but you may want to consider adding OpenID support, through an adapter like HybridAuth.

Leave a comment

Please to leave your comment.

Create extension