yii2-otp
YII2 extension for generating one time passwords according to RFC 4226 (HOTP Algorithm) and the RFC 6238 (TOTP Algorithm)
Installation
The preferred way to install this extension is through composer.
Either run
composer require infoburp/yii2-otp:~0.1.1
or add
"infoburp/yii2-otp" : "~0.1.1"
to the require section of your application's composer.json
file.
Usage
After extension is installed you need to setup auth client collection application component:
Configure
<?php
use infoburp\otp\Otp;
...
'components' => [
'otp' => [
'class' => 'Otp',
// 'totp' only now
'algorithm' => infoburp\otp\Collection::ALGORITHM_TOTP
// length of code
'digits' => 6,
// Algorithm for hashing
'digets' => 'sha1',
// Lable of application
'lable' => 'yii2-otp',
// Uri to image (application icon)
'imgLabelUrl' => Yii::to('/icon.png'),
// Betwen 8 and 1024
'secretLength' => 64
'interval'
],
...
]
Add behavior Add any model column for storing secure code. //My case: the use of two-factor authentication
<?php
use infoburp\otp\behaviors\OtpBehavior;
...
'behavior' => [
'otp' => [
'class' => OtpBehavior::className(),
// Component name
'component' => 'otp',
// column|property name for get and set secure phrase
//'secretAttribute' => 'secret'
//Window in time for check authorithation (current +/- window*interval)
//'window' => 0
],
...
]
Widget use Widget for generate init QR-code
use infoburp\otp\widgets\OtpInit;
<?php echo $form->field($model, 'otpSecret')->widget(
OtpInit::className() ,[
'component'=>'otp',
// link text
'link' => 'ADD OTP BY LINK',
'QrParams' => [
// pixels per cell
'size' => 3,
// margin around QR-code
'margin' => 5,
// by default image create and save at Yii::$app->runtimePath . '/temporaryQR/'
'outfile' => '/tmp/'.uniqid(),
// save or delete after generate
'save' => false,
]
]); ?>
Validation. Additional examples
// login view
<?php
...
<?php echo $form->field($model, 'username') ?>
<?php echo $form->field($model, 'otp')->passwordInput() ?>
...
// login form model
<?php
/**
* Validates the OTP.
*/
public function validateOtp()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validateOtpSecret($this->otp)) {
$this->addError('otp', Yii::t('common', 'Incorrect code.'));
}
}
}
Further Information
Credits
License
The LGPLv3 License. Please see License File for more information.