usr

Yii framework module for user authentication, password reset, registration and profile updating.
25 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 20 comments

#18457 report it
ranjan at 2014/11/02 03:59am
How to implement the registration (Model + View) for two different user?

I am trying to extend this extension registration feature for two users. I have two users(user1 and user2), please tell me how to do this.

Scenario : when any user click on sigup link from login page it will redirect to the registration form with different field and title.

#18091 report it
nineinchnick at 2014/09/06 04:12am
rbac relations

I'm not sure what are you asking for. Maybe you should use the forum for that kind of help.

As for the email you can't use another component but why would you want to? Just add the mail settings to the usr module configuration. If you want to alter the email contents override the views using a theme.

#18088 report it
mem at 2014/09/05 04:57pm
rbac relations

After all day reading about it, and just to be clear:

I will create the auth items and the related relations I need for my application. I will use $auth=Yii::app()->authManager; and their methods, then, I run that php code to create the items on the database.

1) Should I then do anything, to relate Yii-usr to what I just did? (or there's nothing to setup, just use it as I normally use it if I hand't Yii-usr installed)?

2) I already have a class to sent emails on my main application, is it a straigh process to use that instead, or should I use the one provided on the module?

note: First name and last name are not created by database migration, I guess. They seem to be missing.

#18081 report it
nineinchnick at 2014/09/05 04:25am
registration

Only the manager controller use any auth items. All other functionality is controlled by the module options and UserIdentity implementation that can permit or deny specific operations.

Self-registration can be disabled through the registrationEnabled module option.

As for the manager controller it is usually used by administrators but by assigning the auth items you can give access to other users, like managers.

In my projects I often use a custom AuthManager class that skips all checkAccess calls if the current user is an admin - it's determined in some other way. In this case I don't even need to assign those specific auth items.

Anyway, feel free to play with it, you'll get used to all those new terms and architecture.

#18080 report it
mem at 2014/09/05 04:12am
Does it support a mix case scenario

I will read and then I will perhaps better understand your last comment.

Sometimes, registration is done by users themselves.(email verification...) Sometimes, registration is done by a admin user on the back. (no email verification...) Sometimes, registration is done, both, by the users, and by the admin.

Does the module support (out of the box), this last mix case scenario? I can read (up) that it supports both variations, but what about a mix?

Thank you for your patience, again. (sorry for all those comments/questions).

#18079 report it
nineinchnick at 2014/09/05 02:25am
auth items

You really should consult the Yii docs regarding commands and auth items.

You create roles and assign them to users yourself. Roles just group other auth items. Then you can either run the command or manually create auth items with required names. Then you assign those auth items to a role assign to a user.

#18078 report it
mem at 2014/09/04 03:46pm
One doubts - updated (again)

I've setup Auth Manager, I was able to run the command. I bunch of auth items were created.

1) If we wish to run your module console command again, to setup other auth items, (other then users, for example, posts rules), we must edit the: getTemplateAuthItems()?

#18077 report it
nineinchnick at 2014/09/04 02:56pm
managment

There's a console command to help create the auth items used in Manager controller. You have to add that console command to your command map in the console config file. Its the 'commands/UsrCommand.php' file. Go check it out, there are comments describing the auth items.

After you create the auth items used by the Manager controller just assign them to a role or directly to a user.

#18076 report it
mem at 2014/09/04 01:09pm
Users roles - where are they stored?

Hello,

Thanks for this brilliant job.

You state, at the very beginning that: "To be able to use user managment, create auth items using the createAuthItems command and assign them to a role or users."

I don't understand one thing: Where will those roles be associated with the users? On a db table, where? On migration files I see nothing related with that.

Can you please elaborate further?

#17742 report it
nineinchnick at 2014/07/18 08:11am
Usage

You have to provide (implement) a UserIdentity class. You can use the provided examples by either copying them or extending from them (that's why they're abstract).

You can check out the source code for the demo projekt, it's on Github. If you noticed something not working you can post an issue in the demo's repo.

#17741 report it
Alantin at 2014/07/18 07:39am
Using the extension

I'm having some problems using this module. I completed the steps in 'Installation' and 'Fast setup and/or new projects' (I'm using this in a new project). But I'm not clear on how to go beyond these steps. Am I supposed to copy all the files into my application? (that kind of beats the purpose of an extention so I doubt that's how I should do it)

Is there some demo application where a simple basic form of this is implemented so I can find my way into it? (I'm kind of new to this so I could use some form of example, the demo page doesn't seem to work and doesn't show me the basic implementation, only the result)

#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.

Leave a comment

Please to leave your comment.

Create extension