Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use Yii;
- use appmodelsauthLogin;
- class UserController extends yiiwebController
- {
- //Экшен по умолчанию
- public $defaultAction = 'login';
- public function beforeAction($action) {
- ///////////////////////////////////////////////////////////////
- //FOR DEBUG
- $this->enableCsrfValidation = false;
- return parent::beforeAction($action);
- //////////////////////////////////////////////////////////////
- }
- public function actionLogin()
- {
- if (!Yii::$app->user->isGuest) {
- //TODO
- }
- $model = new Login();
- //Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
- if ($model->load(Yii::$app->request->post()) && $model->save()) {
- print('ok');
- }
- return $this->render('login');
- }
- public function actionRegister()
- {
- return $this->render('register');
- }
- public function actionPassword()
- {
- }
- }
- namespace appmodelsauth;
- use Yii;
- use yiibaseModel;
- class Login extends Model
- {
- public $email;
- public $phone;
- public $password;
- public $rememberMe = true;
- public $typeLogin;
- private $_user = false;
- public function rules()
- {
- return [
- [['password'], 'required'],
- ['email', 'validateLogin'],
- ['phone', 'validateLogin'],
- ['password', 'validatePassword'],
- ['rememberMe', 'boolean'],
- ];
- }
- /*
- * Валидация введеного адреса эл. почты или телефона
- * @return bool
- */
- public function validateLogin($model, $attribute)
- {
- //TODO
- if ($this->email) {
- $this->typeLogin = 'email';
- return;
- }
- if ($this->phone) {
- $this->typeLogin = 'phone';
- return;
- }
- $this->addError($attribute, 'Неправильное имя пользователя или пароль!');
- }
- /*
- * Валидация пароля
- * @return bool
- */
- public function validatePassword($model, $attribute)
- {
- if ( !$this->hasErrors() ) {
- $user = $this->getUser();
- if (!$user || !$user->validatePassword($this->password)) {
- $this->addError($attribute, 'Неправильное имя пользователя или пароль!');
- }
- }
- }
- /*
- * Авторизация пользователя
- * @return bool
- */
- public function login()
- {
- if ($this->validate()) {
- return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
- }
- return false;
- }
- /*
- * Поиск пользователя по логину или номкру телефона
- * @return bool
- */
- public function getUser()
- {
- if ($this->_user === false) {
- if ($this->typeLogin === 'email')
- $this->_user = User::findByEmail($this->email);
- else
- $this->_user = User::findByPhone($this->phone);
- }
- return $this->_user;
- }
- //public function load($data)
- //{
- // $this->email = isset($data['email']) ? $data['email'] : null;
- // $this->phone = isset($data['phone']) ? $data['phone'] : null;
- // $this->password = isset($data['password']) ? $data['password'] : null;
- // $this->rememberMe = isset($data['rememberMe']) ? $data['rememberMe'] : null;
- // parent::load($data);
- //}
- }
- <?php
- namespace appmodelsauth;
- use Yii;
- use yiidbActiveRecord;
- use yiiwebIdentityInterface;
- use yiibehaviorsTimestampBehavior;
- /**
- * @property integer $id
- * @property string $email
- * @property string $phone
- * @property string $password
- * @property string $name
- * @property string $sename
- * @property string $fathername
- * @property integer $group_id
- * @property integer $enabled
- * @property string $last_ip
- * @property string $created
- * @property integer $subscribed_on_news
- * @property integer $downloaded_to_unisender
- */
- class User extends ActiveRecord implements IdentityInterface
- {
- private $salt = '79d6e182b3c811c559e6b';
- public static function tableName()
- {
- return 's_users';
- }
- public function rules()
- {
- return [
- [['email', 'phone', 'name', 'sename'], 'required'],
- [['group_id', 'enabled', 'subscribed_on_news', 'downloaded_to_unisender'], 'integer'],
- [['created'], 'safe'],
- [['email', 'password', 'name', 'fathername'], 'string', 'max' => 255],
- [['phone', 'sename'], 'string', 'max' => 30],
- [['last_ip'], 'string', 'max' => 15],
- [['phone'], 'unique'],
- ];
- }
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'email' => 'Email',
- 'phone' => 'Phone',
- 'password' => 'Password',
- 'name' => 'Name',
- 'sename' => 'Sename',
- 'fathername' => 'Fathername',
- 'group_id' => 'Group ID',
- 'enabled' => 'Enabled',
- 'last_ip' => 'Last Ip',
- 'created' => 'Created',
- 'subscribed_on_news' => 'Subscribed On News',
- 'downloaded_to_unisender' => 'Downloaded To Unisender',
- ];
- }
- /*
- * Поведения
- */
- public function behaviors()
- {
- return [
- TimestampBehavior::className()
- ];
- }
- /*
- * Поиск пользователя по email
- * @param string $email
- * @return
- */
- public function findByEmail($email)
- {
- return static::findOne(['email' => $email ]);
- }
- /*
- * Поиск пользователя по номеру телефона
- * @param string $email
- * @return
- */
- public function findByPhone($phone)
- {
- return static::findOne(['phone' => $phone ]);
- }
- /*
- * Проверка пароля
- * @parem string $password
- * @return bool
- */
- public function validatePassword($password)
- {
- return $this->password === md5($this->salt.$password.md5($password));
- }
- /*
- * Добавление/Изменение пароля
- */
- public function setPassword($password)
- {
- $this->password = md5($this->salt.$password.md5($password));
- }
- /*
- * Генерация случайной строки для индетификации пользователя,
- * например может понадобится в опции "запомнить меня"
- */
- public function generateAuthKey()
- {
- $this->authKey === $app->security->generateRandomString();
- }
- /* Реализация методов интерфейса IdentityInterface */
- public static function findIdentity($id)
- {
- return static::findOne($id);
- }
- public static function findIdentityByAccessToken($token, $type = null)
- {
- //return static::findOne(['access_token' => $token]);
- }
- public function getId()
- {
- return $this->id;
- }
- public function getAuthKey()
- {
- return $this->authKey;
- }
- public function validateAuthKey($authKey)
- {
- return $this->authKey === $authKey;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement