- About
- Resources
- Installation
- Identity interfaces
- User model example
- Diceware aka password generator
- Customize
- Usage scenarios
- Configuration for Twitter Bootstrap
- License
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 ¶
Github repo: https://github.com/nineinchnick/yii-usr
Composer package: nineinchnick/yii-usr
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
OpenID Support
I realize this was just released, but you may want to consider adding OpenID support, through an adapter like HybridAuth.
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 :-)
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 ?
Update profile email
I've created a new version with a migration creating user table.
Also added email verification after change through profile form.
How with DB
How to use it with DB ... can you give full example .. please!
Data ?
there is no data folder or file!
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.
Then ..
If my app already have user management with db, why do i need usr ?
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.
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 ...
Create normal how-to-install
May be your extension great, but write normal instructions (may be step by step) how to install you extension.
It's not trivial to understand how your module to get alive (working). installation instruction is too poor.
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.
Time-based One-Time Passwords
It would be nice if this supported Time-based One-time Password authentication (i.e.: Google Authenticator).
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.
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?
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.
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.
Login History
Thanks for reporting, I will take care of this. Could you create an issue in the Github repo?
Login History
Will do - I forgot about that!
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)
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.
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?
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.
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()?
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.
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).
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.
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.
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.
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.
Hybridauth & sessions
In order to use Hybridauth I had to change the app configuration file in this way:
'session' => array ( 'sessionName' => 'PHPSESSID', ),
Otherwise, enabling Hybridauth produces that login process generates two different sessions, one named PHPSESSID used by hybridauth library to store its session data, and another one (named YIISESSION or other depending on custom app configuration file). The effect is that main app can't figure out if the current user is logged in, while the usr module considers the user already logged and doesn't permit the action 'login' (see defaultController/beforeAction).
Hybridauth & sessions
This issue concerns Hybridauth, not yii-usr directly. I do plan to backport yii2-authclient, since I've already replaced Hybridauth with it in yii2-usr.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.