/yii2-account

A module for the Yii framework that provides common account functionality.

Primary LanguagePHPBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause

yii2-account

Build Status Code Climate Latest Stable Version Total Downloads Latest Unstable Version License

A module for the Yii framework that provides common account functionality.

Why do I want this

This project was inspired by both the http://github.com/mishamx/yii-user and https://github.com/dektrium/yii2-user modules and was carefully developed with our expertise in Yii following the best practices of the framework. The module uses Yii's own password methods in yii\base\Security, alternatively you can implement our PasswordHasherInterface to hash passwords differently. Other features include interfaces for sending mail and creating authentication tokens; various password security features and much more. For more details refer to the features section below.

Features

  • Secure accounts (bcrypt encryption) DONE
  • Optional sign-up process (enabled by default) DONE
  • Captcha support on sign up DONE
  • Optional account activation (enabled by default) DONE
  • Log in / Log out DONE
  • Sign up and log in through third-party services DONE
  • Reset password DONE
  • Email sending (with token validation) DONE
  • Require new password every x days (disabled by default) DONE
  • Password history (encrypted) to prevent from using same password twice DONE
  • Lock accounts after x failed login attempts (disabled by default) DONE
  • Console command for creating accounts DONE
  • Proper README WIP

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist nordsoftware/yii2-account "*"

or add

"nordsoftware/yii2-account": "*"

to the require section of your composer.json file.

Before you can start using the module you need to apply its database migrations. To do so run the following command:

yii migrate --migrationPath="vendor/nordsoftware/yii2-account/migrations"

Usage

Once the extension is installed, simply modify your application configuration as follows:

return [
    'bootstrap' => [
        'nord\yii\account\Bootstrap'
        // ...
    ],
    'modules' => [
        'account' => 'nord\yii\account\Module',
        // ...
    ],
    // ...
];

Configuration

The following configurations are available for the nord\yii\account\Module class:

  • classMap array map over classes to use within the module.
  • enableActivation bool whether to enable account activation (defaults to true).
  • enableSignup bool whether to enable the sign-up process (defaults to true).
  • enableCaptcha bool whether to enable CAPTCHA when signing up (defaults to false).
  • enableClientAuth bool whether to enable client authentication (defaults to false).
  • userConfig array configuration passed to yii\web\User.
  • passwordConfig array configuration passed to PasswordStrengthValidator.
  • captchaConfig array configuration passed to CaptchaAction.
  • clientAuthConfig array configuration passed to yii\authclient\Collection.
  • urlConfig array configuration for the URLs used by the module.
  • loginAttribute string name of the attribute to use for logging in (defaults to username).
  • passwordAttribute string name of the password attribute (defaults to password).
  • messageSource string message source component to use for the module.
  • messagePath string message path to use for the module.

Parameters

The following parameters are available for the nord\yii\account\Module class:

  • fromEmailAddress string from e-mail address used when sending e-mail.
  • numAllowedFailedLoginAttempts int number of failed login attempts before the account is locked (defaults to 10)
  • minUsernameLength int minimum length for usernames (defaults to 4).
  • minPasswordLength int minimum length for passwords (defaults to 6).
  • loginExpireTime int number of seconds for login cookie to expire (defaults to 30 days).
  • activateExpireTime int number of seconds for account activation to expire (defaults to 30 days).
  • resetPasswordExpireTime int number of seconds for password reset to expire (defaults to 1 day).
  • passwordExpireTime int number of seconds for passwords to expire (defaults to disabled).
  • lockoutExpireTime int number of seconds for account lockout to expire (defaults to 10 minutes).
  • tokenExpireTime int number of seconds for the authorization tokens to expire (defaults to 1 hour).

Usage

Now you should be able to see the login page when you go to the following url:

index.php?r=account OR index.php/account

You can run the following command to generate an account from the command line:

yii account/create demo demo1234

Extending

This project was developed with a focus on re-usability, so before you start copy-pasting take a moment of your time and read through this section to learn how to extend this module properly.

Custom account model

You can use your own account model as long as you add the following fields to it:

  • username varchar(255) not null account username
  • password varchar(255) not null account password
  • authKey varchar(255) not null authentication key used for cookie authentication
  • email varchar(255) not null account email
  • lastLoginAt datetime null default null when the user last logged in
  • createdAt datetime null default null when the account was created
  • status int(11) default '0' account status (e.g. unactivated, activated)

Changing the model used by the extension is easy, simply configure it to use your class instead by adding it to the class map for the module:

'account' => [
    'class' => 'nord\yii\account\Module',
    'classMap' => [
        'account' => 'MyAccount',
    ],
],

Custom models

You can use the class map to configure any classes used by the module, here is a complete list of the available classes:

  • account models\Account account model
  • token models\AccountToken account token model
  • provider models\AccountProvider account provider model
  • loginHistory models\AccountLoginHistory login history model
  • passwordHistory models\AccountPasswordHistory password history model
  • loginForm models\LoginForm login form
  • passwordForm models\PasswordForm base form that handles passwords
  • signupForm models\SignupForm signup form
  • connectForm models\ConnectForm connect form
  • forgotPassword models\ForgotPasswordForm forgot password form
  • passwordBehavior behaviors/PasswordAttributeBehavior password attribute behavior
  • passwordValidator validators/PasswordStrengthValidator password strength validator
  • webUser yii\web\User web user component
  • captcha yii\captcha\Captcha captcha widget
  • captchaAction yii\captcha\CaptchaAction captcha action

Custom controllers

If you want to use your own controllers you can map them using the module's controller map:

'account' => [
    'class' => 'nord\yii\account\Module',
    'controllerMap' => [
        'authenticate' => 'MyAuthenticateController',
    ],
],

Custom components

If you want to change the components used by the module, here is a complete list of the available interfaces:

  • dataContract components\datacontract\DataContractInterface abstraction layer between the module and its data model (defaults to DataContract)
  • mailSender components\mailsender\MailSenderInterface component used for sending e-mail (defaults to YiiMailSender)
  • passwordHasher components\passwordhasher\PasswordHasherInterface component used for hashing password (defaults to YiiPasswordHasher)
  • tokenGenerator components\tokengenerator\TokenGeneratorInterface component used for generating random tokens (default to YiiTokenGenerator)

You might want to look at the bundled implementations before making your own because we already support e.g. sending mail through Mandrill.

Contribute

If you wish to contribute to this project feel free to create a pull-request to the develop branch.

Running tests

Coming soon ...

Translate

If you wish to translate this project you can find the translation templates under messages/templates. When you are done with your translation you should create a pull-request to the develop branch.