PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/common/models/User.php

https://gitlab.com/junio-p/nutrirbox
PHP | 296 lines | 181 code | 24 blank | 91 comment | 3 complexity | 2c802358736d42f1ebaa3980d86134b8 MD5 | raw file
  1. <?php
  2. namespace common\models;
  3. use cheatsheet\Time;
  4. use common\commands\AddToTimelineCommand;
  5. use common\models\query\UserQuery;
  6. use Yii;
  7. use yii\behaviors\AttributeBehavior;
  8. use yii\behaviors\TimestampBehavior;
  9. use yii\db\ActiveRecord;
  10. use yii\helpers\ArrayHelper;
  11. use yii\web\IdentityInterface;
  12. /**
  13. * This is the model class for table "user".
  14. *
  15. * @property integer $id
  16. * @property string $username
  17. * @property string $auth_key
  18. * @property string $access_token
  19. * @property string $password_hash
  20. * @property string $oauth_client
  21. * @property string $oauth_client_user_id
  22. * @property string $email
  23. * @property integer $status
  24. * @property integer $created_at
  25. * @property integer $updated_at
  26. * @property integer $logged_at
  27. *
  28. * @property Article[] $articles
  29. * @property Article[] $articles0
  30. * @property UserProfile $userProfile
  31. */
  32. class User extends ActiveRecord implements IdentityInterface
  33. {
  34. const STATUS_NOT_ACTIVE = 1;
  35. const STATUS_ACTIVE = 2;
  36. const STATUS_DELETED = 3;
  37. const ROLE_USER = 'user';
  38. const ROLE_MANAGER = 'manager';
  39. const ROLE_ADMINISTRATOR = 'administrator';
  40. const EVENT_AFTER_SIGNUP = 'afterSignup';
  41. const EVENT_AFTER_LOGIN = 'afterLogin';
  42. /**
  43. * @inheritdoc
  44. */
  45. public static function tableName()
  46. {
  47. return '{{%user}}';
  48. }
  49. /**
  50. * @return UserQuery
  51. */
  52. public static function find()
  53. {
  54. return new UserQuery(get_called_class());
  55. }
  56. /**
  57. * @inheritdoc
  58. */
  59. public function behaviors()
  60. {
  61. return [
  62. TimestampBehavior::className(),
  63. 'auth_key' => [
  64. 'class' => AttributeBehavior::className(),
  65. 'attributes' => [
  66. ActiveRecord::EVENT_BEFORE_INSERT => 'auth_key'
  67. ],
  68. 'value' => Yii::$app->getSecurity()->generateRandomString()
  69. ],
  70. 'access_token' => [
  71. 'class' => AttributeBehavior::className(),
  72. 'attributes' => [
  73. ActiveRecord::EVENT_BEFORE_INSERT => 'access_token'
  74. ],
  75. 'value' => function() {
  76. return Yii::$app->getSecurity()->generateRandomString(40);
  77. }
  78. ]
  79. ];
  80. }
  81. /**
  82. * @return array
  83. */
  84. public function scenarios()
  85. {
  86. return ArrayHelper::merge(
  87. parent::scenarios(),
  88. [
  89. 'oauth_create'=>[
  90. 'oauth_client', 'oauth_client_user_id', 'email', 'username', '!status'
  91. ]
  92. ]
  93. );
  94. }
  95. /**
  96. * @inheritdoc
  97. */
  98. public function rules()
  99. {
  100. return [
  101. [['username', 'email'], 'unique'],
  102. ['status', 'default', 'value' => self::STATUS_NOT_ACTIVE],
  103. ['status', 'in', 'range' => array_keys(self::statuses())],
  104. [['username'],'filter','filter' => '\yii\helpers\Html::encode'],
  105. [['username', 'auth_key'], 'string', 'max' => 32],
  106. [['access_token'], 'string', 'max' => 40],
  107. [['password_hash', 'oauth_client', 'oauth_client_user_id', 'email'], 'string', 'max' => 255],
  108. ];
  109. }
  110. /**
  111. * @inheritdoc
  112. */
  113. public function attributeLabels()
  114. {
  115. return [
  116. 'username' => Yii::t('common', 'Username'),
  117. 'email' => Yii::t('common', 'E-mail'),
  118. 'status' => Yii::t('common', 'Status'),
  119. 'access_token' => Yii::t('common', 'API access token'),
  120. 'created_at' => Yii::t('common', 'Created at'),
  121. 'updated_at' => Yii::t('common', 'Updated at'),
  122. 'logged_at' => Yii::t('common', 'Last login'),
  123. ];
  124. }
  125. /**
  126. * @return \yii\db\ActiveQuery
  127. */
  128. public function getUserProfile()
  129. {
  130. return $this->hasOne(UserProfile::className(), ['user_id'=>'id']);
  131. }
  132. /**
  133. * @inheritdoc
  134. */
  135. public static function findIdentity($id)
  136. {
  137. return static::find()
  138. ->active()
  139. ->andWhere(['id' => $id])
  140. ->one();
  141. }
  142. /**
  143. * @inheritdoc
  144. */
  145. public static function findIdentityByAccessToken($token, $type = null)
  146. {
  147. return static::find()
  148. ->active()
  149. ->andWhere(['access_token' => $token, 'status' => self::STATUS_ACTIVE])
  150. ->one();
  151. }
  152. /**
  153. * Finds user by username
  154. *
  155. * @param string $username
  156. * @return static|null
  157. */
  158. public static function findByUsername($username)
  159. {
  160. return static::find()
  161. ->active()
  162. ->andWhere(['username' => $username, 'status' => self::STATUS_ACTIVE])
  163. ->one();
  164. }
  165. /**
  166. * Finds user by username or email
  167. *
  168. * @param string $login
  169. * @return static|null
  170. */
  171. public static function findByLogin($login)
  172. {
  173. return static::find()
  174. ->active()
  175. ->andWhere([
  176. 'and',
  177. ['or', ['username' => $login], ['email' => $login]],
  178. 'status' => self::STATUS_ACTIVE
  179. ])
  180. ->one();
  181. }
  182. /**
  183. * @inheritdoc
  184. */
  185. public function getId()
  186. {
  187. return $this->getPrimaryKey();
  188. }
  189. /**
  190. * @inheritdoc
  191. */
  192. public function getAuthKey()
  193. {
  194. return $this->auth_key;
  195. }
  196. /**
  197. * @inheritdoc
  198. */
  199. public function validateAuthKey($authKey)
  200. {
  201. return $this->getAuthKey() === $authKey;
  202. }
  203. /**
  204. * Validates password
  205. *
  206. * @param string $password password to validate
  207. * @return boolean if password provided is valid for current user
  208. */
  209. public function validatePassword($password)
  210. {
  211. return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
  212. }
  213. /**
  214. * Generates password hash from password and sets it to the model
  215. *
  216. * @param string $password
  217. */
  218. public function setPassword($password)
  219. {
  220. $this->password_hash = Yii::$app->getSecurity()->generatePasswordHash($password);
  221. }
  222. /**
  223. * Returns user statuses list
  224. * @return array|mixed
  225. */
  226. public static function statuses()
  227. {
  228. return [
  229. self::STATUS_NOT_ACTIVE => Yii::t('common', 'Not Active'),
  230. self::STATUS_ACTIVE => Yii::t('common', 'Active'),
  231. self::STATUS_DELETED => Yii::t('common', 'Deleted')
  232. ];
  233. }
  234. /**
  235. * Creates user profile and application event
  236. * @param array $profileData
  237. */
  238. public function afterSignup(array $profileData = [])
  239. {
  240. $this->refresh();
  241. Yii::$app->commandBus->handle(new AddToTimelineCommand([
  242. 'category' => 'user',
  243. 'event' => 'signup',
  244. 'data' => [
  245. 'public_identity' => $this->getPublicIdentity(),
  246. 'user_id' => $this->getId(),
  247. 'created_at' => $this->created_at
  248. ]
  249. ]));
  250. $profile = new UserProfile();
  251. $profile->locale = Yii::$app->language;
  252. $profile->load($profileData, '');
  253. $this->link('userProfile', $profile);
  254. $this->trigger(self::EVENT_AFTER_SIGNUP);
  255. // Default role
  256. $auth = Yii::$app->authManager;
  257. $auth->assign($auth->getRole(User::ROLE_USER), $this->getId());
  258. }
  259. /**
  260. * @return string
  261. */
  262. public function getPublicIdentity()
  263. {
  264. if ($this->userProfile && $this->userProfile->getFullname()) {
  265. return $this->userProfile->getFullname();
  266. }
  267. if ($this->username) {
  268. return $this->username;
  269. }
  270. return $this->email;
  271. }
  272. }