update models + added social network account services

This commit is contained in:
Antonio Ramirez
2016-12-06 00:24:24 +01:00
parent be80b12a03
commit c5279eb13c
22 changed files with 1324 additions and 62 deletions

128
lib/User/Form/LoginForm.php Normal file
View File

@ -0,0 +1,128 @@
<?php
namespace Da\User\Form;
use Da\User\Helper\SecurityHelper;
use Da\User\Model\User;
use Da\User\Query\UserQuery;
use Da\User\Traits\ModuleTrait;
use Yii;
use yii\base\Model;
class LoginForm extends Model
{
use ModuleTrait;
/**
* @var string login User's email or username
*/
public $login;
/**
* @var string User's password
*/
public $password;
/**
* @var bool whether to remember User's login
*/
public $rememberMe = false;
/**
* @var User
*/
protected $user;
/**
* @var UserQuery
*/
protected $query;
/**
* @var SecurityHelper
*/
protected $securityHelper;
/**
* @param UserQuery $query
* @param SecurityHelper $securityHelper
* @param array $config
*/
public function __construct(UserQuery $query, SecurityHelper $securityHelper, $config = [])
{
$this->query = $query;
$this->securityHelper = $securityHelper;
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'login' => Yii::t('user', 'Login'),
'password' => Yii::t('user', 'Password'),
'rememberMe' => Yii::t('user', 'Remember me next time'),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
'requiredFields' => [['login', 'password'], 'required'],
'loginTrim' => ['login', 'trim'],
'passwordValidate' => [
'password',
function ($attribute) {
if ($this->user === null ||
!$this->securityHelper->validatePassword($this->password, $this->user->password_hash)
) {
$this->addError($attribute, Yii::t('user', 'Invalid login or password'));
}
}
],
'confirmationValidate' => [
'login',
function ($attribute) {
if ($this->user !== null) {
$module = $this->getModule();
$confirmationRequired = $module->enableEmailConfirmation && !$module->allowUnconfirmedEmailLogin;
if ($confirmationRequired && !$this->user->getIsConfirmed()) {
$this->addError($attribute, Yii::t('user', 'You need to confirm your email address'));
}
if ($this->user->getIsBlocked()) {
$this->addError($attribute, Yii::t('user', 'Your account has been blocked'));
}
}
}
],
'rememberMe' => ['rememberMe', 'boolean'],
];
}
/**
* Validates form and logs the user in.
*
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
$duration = $this->rememberMe ? $this->module->rememberLoginLifespan : 0;
return Yii::$app->getUser()->login($this->user, $duration);
} else {
return false;
}
}
/**
* @inheritdoc
*/
public function beforeValidate()
{
if (parent::beforeValidate()) {
$this->user = $this->query->whereUsernameOrEmail(trim($this->login))->one();
return true;
}
return false;
}
}

View File

@ -1,15 +1,74 @@
<?php
namespace Da\User\Form;
/**
*
* RecoveryForm.php
*
* Date: 4/12/16
* Time: 15:18
* @author Antonio Ramirez <hola@2amigos.us>
*/
class RecoveryForm
{
use Da\User\Query\UserQuery;
use Da\User\Traits\ContainerTrait;
use Yii;
use yii\base\Model;
class RecoveryForm extends Model
{
use ContainerTrait;
const SCENARIO_REQUEST = 'request';
const SCENARIO_RESET = 'reset';
/**
* @var string User's email
*/
public $email;
/**
* @var string User's password
*/
public $password;
/**
* @var UserQuery
*/
protected $query;
/**
* @param UserQuery $query
* @param array $config
*/
public function __construct(UserQuery $query, array $config)
{
$this->query = $query;
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'email' => Yii::t('user', 'Email'),
'password' => Yii::t('user', 'Password'),
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
return [
self::SCENARIO_REQUEST => ['email'],
self::SCENARIO_RESET => ['password'],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
'emailRequired' => ['email', 'required'],
'emailPattern' => ['email', 'email'],
'passwordRequired' => ['password', 'required'],
'passwordLength' => ['password', 'string', 'max' => 72, 'min' => 6],
];
}
}

View File

@ -0,0 +1,140 @@
<?php
/*
* This file is part of the Dektrium project.
*
* (c) Dektrium project <http://github.com/dektrium/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace dektrium\user\models;
use dektrium\user\traits\ModuleTrait;
use Yii;
use yii\base\Model;
/**
* Registration form collects user input on registration process, validates it and creates new User model.
*
* @author Dmitry Erofeev <dmeroff@gmail.com>
*/
class RegistrationForm extends Model
{
use ModuleTrait;
/**
* @var string User email address
*/
public $email;
/**
* @var string Username
*/
public $username;
/**
* @var string Password
*/
public $password;
/**
* @inheritdoc
*/
public function rules()
{
$user = $this->module->modelMap['User'];
return [
// username rules
'usernameLength' => ['username', 'string', 'min' => 3, 'max' => 255],
'usernameTrim' => ['username', 'filter', 'filter' => 'trim'],
'usernamePattern' => ['username', 'match', 'pattern' => $user::$usernameRegexp],
'usernameRequired' => ['username', 'required'],
'usernameUnique' => [
'username',
'unique',
'targetClass' => $user,
'message' => Yii::t('user', 'This username has already been taken')
],
// email rules
'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
'emailRequired' => ['email', 'required'],
'emailPattern' => ['email', 'email'],
'emailUnique' => [
'email',
'unique',
'targetClass' => $user,
'message' => Yii::t('user', 'This email address has already been taken')
],
// password rules
'passwordRequired' => ['password', 'required', 'skipOnEmpty' => $this->module->enableGeneratingPassword],
'passwordLength' => ['password', 'string', 'min' => 6, 'max' => 72],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'email' => Yii::t('user', 'Email'),
'username' => Yii::t('user', 'Username'),
'password' => Yii::t('user', 'Password'),
];
}
/**
* @inheritdoc
*/
public function formName()
{
return 'register-form';
}
/**
* Registers a new user account. If registration was successful it will set flash message.
*
* @return bool
*/
public function register()
{
if (!$this->validate()) {
return false;
}
/** @var User $user */
$user = Yii::createObject(User::className());
$user->setScenario('register');
$this->loadAttributes($user);
if (!$user->register()) {
return false;
}
Yii::$app->session->setFlash(
'info',
Yii::t(
'user',
'Your account has been created and a message with further instructions has been sent to your email'
)
);
return true;
}
/**
* Loads attributes to the user model. You should override this method if you are going to add new fields to the
* registration form. You can read more in special guide.
*
* By default this method set all attributes of this model to the attributes of User model, so you should properly
* configure safe attributes of your User model.
*
* @param User $user
*/
protected function loadAttributes(User $user)
{
$user->setAttributes($this->attributes);
}
}

View File

@ -0,0 +1,116 @@
<?php
/*
* This file is part of the Dektrium project.
*
* (c) Dektrium project <http://github.com/dektrium/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace dektrium\user\models;
use dektrium\user\Finder;
use dektrium\user\Mailer;
use yii\base\Model;
/**
* ResendForm gets user email address and if user with given email is registered it sends new confirmation message
* to him in case he did not validate his email.
*
* @author Dmitry Erofeev <dmeroff@gmail.com>
*/
class ResendForm extends Model
{
/**
* @var string
*/
public $email;
/**
* @var Mailer
*/
protected $mailer;
/**
* @var Finder
*/
protected $finder;
/**
* @param Mailer $mailer
* @param Finder $finder
* @param array $config
*/
public function __construct(Mailer $mailer, Finder $finder, $config = [])
{
$this->mailer = $mailer;
$this->finder = $finder;
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
'emailRequired' => ['email', 'required'],
'emailPattern' => ['email', 'email'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'email' => \Yii::t('user', 'Email'),
];
}
/**
* @inheritdoc
*/
public function formName()
{
return 'resend-form';
}
/**
* Creates new confirmation token and sends it to the user.
*
* @return bool
*/
public function resend()
{
if (!$this->validate()) {
return false;
}
$user = $this->finder->findUserByEmail($this->email);
if ($user instanceof User && !$user->isConfirmed) {
/** @var Token $token */
$token = \Yii::createObject([
'class' => Token::className(),
'user_id' => $user->id,
'type' => Token::TYPE_CONFIRMATION,
]);
$token->save(false);
$this->mailer->sendConfirmationMessage($user, $token);
}
\Yii::$app->session->setFlash(
'info',
\Yii::t(
'user',
'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'
)
);
return true;
}
}

View File

@ -0,0 +1,206 @@
<?php
/*
* This file is part of the Dektrium project.
*
* (c) Dektrium project <http://github.com/dektrium/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace dektrium\user\models;
use dektrium\user\helpers\Password;
use dektrium\user\Mailer;
use dektrium\user\Module;
use dektrium\user\traits\ModuleTrait;
use Yii;
use yii\base\Model;
/**
* SettingsForm gets user's username, email and password and changes them.
*
* @property User $user
*
* @author Dmitry Erofeev <dmeroff@gmail.com>
*/
class SettingsForm extends Model
{
use ModuleTrait;
/** @var string */
public $email;
/** @var string */
public $username;
/** @var string */
public $new_password;
/** @var string */
public $current_password;
/** @var Mailer */
protected $mailer;
/** @var User */
private $_user;
/** @return User */
public function getUser()
{
if ($this->_user == null) {
$this->_user = Yii::$app->user->identity;
}
return $this->_user;
}
/** @inheritdoc */
public function __construct(Mailer $mailer, $config = [])
{
$this->mailer = $mailer;
$this->setAttributes([
'username' => $this->user->username,
'email' => $this->user->unconfirmed_email ?: $this->user->email,
], false);
parent::__construct($config);
}
/** @inheritdoc */
public function rules()
{
return [
'usernameRequired' => ['username', 'required'],
'usernameTrim' => ['username', 'filter', 'filter' => 'trim'],
'usernameLength' => ['username', 'string', 'min' => 3, 'max' => 255],
'usernamePattern' => ['username', 'match', 'pattern' => '/^[-a-zA-Z0-9_\.@]+$/'],
'emailRequired' => ['email', 'required'],
'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
'emailPattern' => ['email', 'email'],
'emailUsernameUnique' => [['email', 'username'], 'unique', 'when' => function ($model, $attribute) {
return $this->user->$attribute != $model->$attribute;
}, 'targetClass' => $this->module->modelMap['User']],
'newPasswordLength' => ['new_password', 'string', 'max' => 72, 'min' => 6],
'currentPasswordRequired' => ['current_password', 'required'],
'currentPasswordValidate' => ['current_password', function ($attr) {
if (!Password::validate($this->$attr, $this->user->password_hash)) {
$this->addError($attr, Yii::t('user', 'Current password is not valid'));
}
}],
];
}
/** @inheritdoc */
public function attributeLabels()
{
return [
'email' => Yii::t('user', 'Email'),
'username' => Yii::t('user', 'Username'),
'new_password' => Yii::t('user', 'New password'),
'current_password' => Yii::t('user', 'Current password'),
];
}
/** @inheritdoc */
public function formName()
{
return 'settings-form';
}
/**
* Saves new account settings.
*
* @return bool
*/
public function save()
{
if ($this->validate()) {
$this->user->scenario = 'settings';
$this->user->username = $this->username;
$this->user->password = $this->new_password;
if ($this->email == $this->user->email && $this->user->unconfirmed_email != null) {
$this->user->unconfirmed_email = null;
} elseif ($this->email != $this->user->email) {
switch ($this->module->emailChangeStrategy) {
case Module::STRATEGY_INSECURE:
$this->insecureEmailChange();
break;
case Module::STRATEGY_DEFAULT:
$this->defaultEmailChange();
break;
case Module::STRATEGY_SECURE:
$this->secureEmailChange();
break;
default:
throw new \OutOfBoundsException('Invalid email changing strategy');
}
}
return $this->user->save();
}
return false;
}
/**
* Changes user's email address to given without any confirmation.
*/
protected function insecureEmailChange()
{
$this->user->email = $this->email;
Yii::$app->session->setFlash('success', Yii::t('user', 'Your email address has been changed'));
}
/**
* Sends a confirmation message to user's email address with link to confirm changing of email.
*/
protected function defaultEmailChange()
{
$this->user->unconfirmed_email = $this->email;
/** @var Token $token */
$token = Yii::createObject([
'class' => Token::className(),
'user_id' => $this->user->id,
'type' => Token::TYPE_CONFIRM_NEW_EMAIL,
]);
$token->save(false);
$this->mailer->sendReconfirmationMessage($this->user, $token);
Yii::$app->session->setFlash(
'info',
Yii::t('user', 'A confirmation message has been sent to your new email address')
);
}
/**
* Sends a confirmation message to both old and new email addresses with link to confirm changing of email.
*
* @throws \yii\base\InvalidConfigException
*/
protected function secureEmailChange()
{
$this->defaultEmailChange();
/** @var Token $token */
$token = Yii::createObject([
'class' => Token::className(),
'user_id' => $this->user->id,
'type' => Token::TYPE_CONFIRM_OLD_EMAIL,
]);
$token->save(false);
$this->mailer->sendReconfirmationMessage($this->user, $token);
// unset flags if they exist
$this->user->flags &= ~User::NEW_EMAIL_CONFIRMED;
$this->user->flags &= ~User::OLD_EMAIL_CONFIRMED;
$this->user->save(false);
Yii::$app->session->setFlash(
'info',
Yii::t(
'user',
'We have sent confirmation links to both old and new email addresses. You must click both links to complete your request'
)
);
}
}