User.php 2.4 KB
Newer Older
1
<?php
2
namespace common\models;
3

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
use yii\db\ActiveRecord;
use yii\helpers\SecurityHelper;
use yii\web\Identity;

/**
 * Class User
 * @package common\models
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $email
 * @property string $auth_key
 * @property integer $role
 * @property integer $status
 * @property integer $create_time
 * @property integer $update_time
 */
class User extends ActiveRecord implements Identity
23
{
24 25 26
	/**
	 * @var string the raw password. Used to collect password input and isn't saved in database
	 */
27
	public $password;
28 29 30 31 32 33 34 35 36 37 38 39

	const STATUS_DELETED = 0;
	const STATUS_ACTIVE = 10;

	const ROLE_USER = 10;

	public function behaviors()
	{
		return array(
			'timestamp' => array(
				'class' => 'yii\behaviors\AutoTimestamp',
				'attributes' => array(
40
					ActiveRecord::EVENT_BEFORE_INSERT => array('create_time', 'update_time'),
41 42 43 44 45
					ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
				),
			),
		);
	}
46 47 48

	public static function findIdentity($id)
	{
49
		return static::find($id);
50 51 52 53
	}

	public static function findByUsername($username)
	{
54
		return static::find(array('username' => $username, 'status' => static::STATUS_ACTIVE));
55 56 57 58 59 60 61 62 63
	}

	public function getId()
	{
		return $this->id;
	}

	public function getAuthKey()
	{
64
		return $this->auth_key;
65 66 67 68
	}

	public function validateAuthKey($authKey)
	{
69
		return $this->auth_key === $authKey;
70 71 72 73
	}

	public function validatePassword($password)
	{
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
		return SecurityHelper::validatePassword($password, $this->password_hash);
	}

	public function rules()
	{
		return array(
			array('username', 'filter', 'filter' => 'trim'),
			array('username', 'required'),
			array('username', 'length', 'min' => 2, 'max' => 255),

			array('email', 'filter', 'filter' => 'trim'),
			array('email', 'required'),
			array('email', 'email'),
			array('email', 'unique', 'message' => 'This email address has already been taken.'),

			array('password', 'required'),
			array('password', 'length', 'min' => 6),
		);
	}

	public function scenarios()
	{
		return array(
			'signup' => array('username', 'email', 'password'),
			'login' => array('username', 'password'),
		);
	}

	public function beforeSave($insert)
	{
		if(parent::beforeSave($insert)) {
			if($this->isNewRecord) {
				if(!empty($this->password)) {
					$this->password_hash = SecurityHelper::generatePasswordHash($this->password);
				}
			}
			return true;
		}
		return false;
113 114
	}
}