Guest User

Untitled

a guest
May 29th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.23 KB | None | 0 0
  1. namespace amnahyii2usermodels;
  2.  
  3. use Yii;
  4. use yiidbActiveRecord;
  5. use yiiwebIdentityInterface;
  6. use yiiswiftmailerMailer;
  7. use yiiswiftmailerMessage;
  8. use yiihelpersInflector;
  9. use ReflectionClass;
  10.  
  11. /**
  12. * This is the model class for table "tbl_user".
  13. *
  14. * @property string $id
  15. * @property string $role_id
  16. * @property integer $status
  17. * @property string $email
  18. * @property string $username
  19. * @property string $password
  20. * @property string $auth_key
  21. * @property string $access_token
  22. * @property string $logged_in_ip
  23. * @property string $logged_in_at
  24. * @property string $created_ip
  25. * @property string $created_at
  26. * @property string $updated_at
  27. * @property string $banned_at
  28. * @property string $banned_reason
  29. *
  30. * @property Profile $profile
  31. * @property Role $role
  32. * @property UserToken[] $userTokens
  33. * @property UserAuth[] $userAuths
  34. */
  35. class User extends ActiveRecord implements IdentityInterface
  36. {
  37. /**
  38. * @var int Inactive status
  39. */
  40. const STATUS_INACTIVE = 0;
  41.  
  42. /**
  43. * @var int Active status
  44. */
  45. const STATUS_ACTIVE = 1;
  46.  
  47. /**
  48. * @var int Unconfirmed email status
  49. */
  50. const STATUS_UNCONFIRMED_EMAIL = 2;
  51.  
  52. /**
  53. * @var string Current password - for account page updates
  54. */
  55. public $currentPassword;
  56.  
  57. /**
  58. * @var string New password - for registration and changing password
  59. */
  60. public $newPassword;
  61.  
  62. /**
  63. * @var string New password confirmation - for reset
  64. */
  65. public $newPasswordConfirm;
  66.  
  67. /**
  68. * @var array Permission cache array
  69. */
  70. protected $permissionCache = [];
  71.  
  72. /**
  73. * @var amnahyii2userModule
  74. */
  75. public $module;
  76.  
  77. /**
  78. * @inheritdoc
  79. */
  80. public function init()
  81. {
  82. if (!$this->module) {
  83. $this->module = Yii::$app->getModule("user");
  84. }
  85. }
  86.  
  87. /**
  88. * @inheritdoc
  89. */
  90. public function rules()
  91. {
  92. // set initial rules
  93. $rules = [
  94. // general email and username rules
  95. [['email', 'username'], 'string', 'max' => 255],
  96. [['email', 'username'], 'unique'],
  97. [['email', 'username'], 'filter', 'filter' => 'trim'],
  98. [['email'], 'email'],
  99. [['username'], 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u', 'message' => Yii::t('user', '{attribute} can contain only letters, numbers, and "_"')],
  100.  
  101. // password rules
  102. [['newPassword'], 'string', 'min' => 3],
  103. [['newPassword'], 'filter', 'filter' => 'trim'],
  104. [['newPassword'], 'required', 'on' => ['register', 'reset']],
  105. [['newPasswordConfirm'], 'required', 'on' => ['reset']],
  106. [['newPasswordConfirm'], 'compare', 'compareAttribute' => 'newPassword', 'message' => Yii::t('user', 'Passwords do not match')],
  107.  
  108. // account page
  109. [['currentPassword'], 'validateCurrentPassword', 'on' => ['account']],
  110.  
  111. // admin crud rules
  112. [['role_id', 'status'], 'required', 'on' => ['admin']],
  113. [['role_id', 'status'], 'integer', 'on' => ['admin']],
  114. [['banned_at'], 'integer', 'on' => ['admin']],
  115. [['banned_reason'], 'string', 'max' => 255, 'on' => 'admin'],
  116. ];
  117.  
  118. // add required for currentPassword on account page
  119. // only if $this->password is set (might be null from a social login)
  120. if ($this->password) {
  121. $rules[] = [['currentPassword'], 'required', 'on' => ['account']];
  122. }
  123.  
  124. // add required rules for email/username depending on module properties
  125. $requireFields = ["requireEmail", "requireUsername"];
  126. foreach ($requireFields as $requireField) {
  127. if ($this->module->$requireField) {
  128. $attribute = strtolower(substr($requireField, 7)); // "email" or "username"
  129. $rules[] = [$attribute, "required"];
  130. }
  131. }
  132.  
  133. return $rules;
  134. }
  135.  
  136. /**
  137. * Validate current password (account page)
  138. */
  139. public function validateCurrentPassword()
  140. {
  141. if (!$this->validatePassword($this->currentPassword)) {
  142. $this->addError("currentPassword", "Current password incorrect");
  143. }
  144. }
  145.  
  146. /**
  147. * @inheritdoc
  148. */
  149. public function attributeLabels()
  150. {
  151. return [
  152. 'id' => Yii::t('user', 'ID'),
  153. 'role_id' => Yii::t('user', 'Role ID'),
  154. 'status' => Yii::t('user', 'Status'),
  155. 'email' => Yii::t('user', 'Email'),
  156. 'username' => Yii::t('user', 'Username'),
  157. 'password' => Yii::t('user', 'Password'),
  158. 'auth_key' => Yii::t('user', 'Auth Key'),
  159. 'access_token' => Yii::t('user', 'Access Token'),
  160. 'logged_in_ip' => Yii::t('user', 'Logged In Ip'),
  161. 'logged_in_at' => Yii::t('user', 'Logged In At'),
  162. 'created_ip' => Yii::t('user', 'Created Ip'),
  163. 'created_at' => Yii::t('user', 'Created At'),
  164. 'updated_at' => Yii::t('user', 'Updated At'),
  165. 'banned_at' => Yii::t('user', 'Banned At'),
  166. 'banned_reason' => Yii::t('user', 'Banned Reason'),
  167.  
  168. // virtual attributes set above
  169. 'currentPassword' => Yii::t('user', 'Current Password'),
  170. 'newPassword' => $this->isNewRecord ? Yii::t('user', 'Password') : Yii::t('user', 'New Password'),
  171. 'newPasswordConfirm' => Yii::t('user', 'New Password Confirm'),
  172. ];
  173. }
  174.  
  175. /**
  176. * @inheritdoc
  177. */
  178. public function behaviors()
  179. {
  180. return [
  181. 'timestamp' => [
  182. 'class' => 'yiibehaviorsTimestampBehavior',
  183. 'value' => function ($event) {
  184. return gmdate("Y-m-d H:i:s");
  185. },
  186. ],
  187. ];
  188. }
  189.  
  190. /**
  191. * Stick with 1 user:1 profile
  192. * @return yiidbActiveQuery
  193. */
  194. /*
  195. public function getProfiles()
  196. {
  197. return $this->hasMany(Profile::className(), ['user_id' => 'id']);
  198. }
  199. */
  200.  
  201. /**
  202. * @return yiidbActiveQuery
  203. */
  204. public function getProfile()
  205. {
  206. $profile = $this->module->model("Profile");
  207. return $this->hasOne($profile::className(), ['user_id' => 'id']);
  208. }
  209.  
  210. /**
  211. * @return yiidbActiveQuery
  212. */
  213. public function getRole()
  214. {
  215. $role = $this->module->model("Role");
  216. return $this->hasOne($role::className(), ['id' => 'role_id']);
  217. }
  218.  
  219. /**
  220. * @return yiidbActiveQuery
  221. */
  222. public function getUserTokens()
  223. {
  224. $userToken = $this->module->model("UserToken");
  225. return $this->hasMany($userToken::className(), ['user_id' => 'id']);
  226. }
  227.  
  228. /**
  229. * @return yiidbActiveQuery
  230. */
  231. public function getUserAuths()
  232. {
  233. return $this->hasMany(UserAuth::className(), ['user_id' => 'id']);
  234. }
  235.  
  236. /**
  237. * @inheritdoc
  238. */
  239. public static function findIdentity($id)
  240. {
  241. return static::findOne($id);
  242. }
  243.  
  244. /**
  245. * @inheritdoc
  246. */
  247. public static function findIdentityByAccessToken($token, $type = null)
  248. {
  249. return static::findOne(["access_token" => $token]);
  250. }
  251.  
  252. /**
  253. * @inheritdoc
  254. */
  255. public function getId()
  256. {
  257. return $this->id;
  258. }
  259.  
  260. /**
  261. * @inheritdoc
  262. */
  263. public function getAuthKey()
  264. {
  265. return $this->auth_key;
  266. }
  267.  
  268. /**
  269. * @inheritdoc
  270. */
  271. public function validateAuthKey($authKey)
  272. {
  273. return $this->auth_key === $authKey;
  274. }
  275.  
  276. /**
  277. * Validate password
  278. * @param string $password
  279. * @return bool
  280. */
  281. public function validatePassword($password)
  282. {
  283. return Yii::$app->security->validatePassword($password, $this->password);
  284. }
  285.  
  286. /**
  287. * @inheritdoc
  288. */
  289. public function beforeSave($insert)
  290. {
  291. // check if we're setting $this->password directly
  292. // handle it by setting $this->newPassword instead
  293. $dirtyAttributes = $this->getDirtyAttributes();
  294. if (isset($dirtyAttributes["password"])) {
  295. $this->newPassword = $dirtyAttributes["password"];
  296. }
  297.  
  298. // hash new password if set
  299. if ($this->newPassword) {
  300. $this->password = Yii::$app->security->generatePasswordHash($this->newPassword);
  301. }
  302.  
  303. // convert banned_at checkbox to date
  304. if ($this->banned_at) {
  305. $this->banned_at = gmdate("Y-m-d H:i:s");
  306. }
  307.  
  308. // ensure fields are null so they won't get set as empty string
  309. $nullAttributes = ["email", "username", "banned_at", "banned_reason"];
  310. foreach ($nullAttributes as $nullAttribute) {
  311. $this->$nullAttribute = $this->$nullAttribute ? $this->$nullAttribute : null;
  312. }
  313.  
  314. return parent::beforeSave($insert);
  315. }
  316.  
  317. /**
  318. * Set attributes for registration
  319. * @param int $roleId
  320. * @param string $status
  321. * @return static
  322. */
  323. public function setRegisterAttributes($roleId, $status = null)
  324. {
  325. // set default attributes
  326. $attributes = [
  327. "role_id" => $roleId,
  328. "created_ip" => Yii::$app->request->userIP,
  329. "auth_key" => Yii::$app->security->generateRandomString(),
  330. "access_token" => Yii::$app->security->generateRandomString(),
  331. "status" => static::STATUS_ACTIVE,
  332. ];
  333.  
  334. // determine if we need to change status based on module properties
  335. $emailConfirmation = $this->module->emailConfirmation;
  336. $requireEmail = $this->module->requireEmail;
  337. $useEmail = $this->module->useEmail;
  338. if ($status) {
  339. $attributes["status"] = $status;
  340. } elseif ($emailConfirmation && $requireEmail) {
  341. $attributes["status"] = static::STATUS_INACTIVE;
  342. } elseif ($emailConfirmation && $useEmail && $this->email) {
  343. $attributes["status"] = static::STATUS_UNCONFIRMED_EMAIL;
  344. }
  345.  
  346. // set attributes and return
  347. $this->setAttributes($attributes, false);
  348. return $this;
  349. }
  350.  
  351. /**
  352. * Check for email change
  353. * @return string|bool
  354. */
  355. public function checkEmailChange()
  356. {
  357. // check if user didn't change email
  358. if ($this->email == $this->getOldAttribute("email")) {
  359. return false;
  360. }
  361.  
  362. // check if we need to confirm email change
  363. if (!$this->module->emailChangeConfirmation) {
  364. return false;
  365. }
  366.  
  367. // check if user is removing email address (only valid if Module::$requireEmail = false)
  368. if (!$this->email) {
  369. return false;
  370. }
  371.  
  372. // update status and email before returning new email
  373. $newEmail = $this->email;
  374. $this->status = static::STATUS_UNCONFIRMED_EMAIL;
  375. $this->email = $this->getOldAttribute("email");
  376. return $newEmail;
  377. }
  378.  
  379. /**
  380. * Update login info (ip and time)
  381. * @return bool
  382. */
  383. public function updateLoginMeta()
  384. {
  385. $this->logged_in_ip = Yii::$app->request->userIP;
  386. $this->logged_in_at = gmdate("Y-m-d H:i:s");
  387. return $this->save(false, ["logged_in_ip", "logged_in_at"]);
  388. }
  389.  
  390. /**
  391. * Confirm user email
  392. * @param string $newEmail
  393. * @return bool
  394. */
  395. public function confirm($newEmail)
  396. {
  397. // update status
  398. $this->status = static::STATUS_ACTIVE;
  399.  
  400. // process $newEmail from a userToken
  401. // check if another user already has that email
  402. $success = true;
  403. if ($newEmail) {
  404. $checkUser = static::findOne(["email" => $newEmail]);
  405. if ($checkUser) {
  406. $success = false;
  407. } else {
  408. $this->email = $newEmail;
  409. }
  410. }
  411.  
  412. $this->save(false, ["email", "status"]);
  413. return $success;
  414. }
  415.  
  416. /**
  417. * Check if user can do specified $permission
  418. * @param string $permissionName
  419. * @param array $params
  420. * @param bool $allowCaching
  421. * @return bool
  422. */
  423. public function can($permissionName, $params = [], $allowCaching = true)
  424. {
  425. // check for auth manager rbac
  426. // copied from yiiwebUser
  427. $auth = Yii::$app->getAuthManager();
  428. if ($auth) {
  429. if ($allowCaching && empty($params) && isset($this->permissionCache[$permissionName])) {
  430. return $this->permissionCache[$permissionName];
  431. }
  432. $access = $auth->checkAccess($this->getId(), $permissionName, $params);
  433. if ($allowCaching && empty($params)) {
  434. $this->permissionCache[$permissionName] = $access;
  435. }
  436. return $access;
  437. }
  438.  
  439. // otherwise use our own custom permission (via the role table)
  440. return $this->role->checkPermission($permissionName);
  441. }
  442.  
  443. /**
  444. * Get display name for the user
  445. * @var string $default
  446. * @return string|int
  447. */
  448. public function getDisplayName($default = "")
  449. {
  450. // define possible fields
  451. $possibleNames = [
  452. "username",
  453. "email",
  454. "id",
  455. ];
  456.  
  457. // go through each and return if valid
  458. foreach ($possibleNames as $possibleName) {
  459. if (!empty($this->$possibleName)) {
  460. return $this->$possibleName;
  461. }
  462. }
  463.  
  464. return $default;
  465. }
  466.  
  467. /**
  468. * Send email confirmation to user
  469. * @param UserToken $userToken
  470. * @return int
  471. */
  472. public function sendEmailConfirmation($userToken)
  473. {
  474. /** @var Mailer $mailer */
  475. /** @var Message $message */
  476.  
  477. // modify view path to module views
  478. $mailer = Yii::$app->mailer;
  479. $oldViewPath = $mailer->viewPath;
  480. $mailer->viewPath = $this->module->emailViewPath;
  481.  
  482. // send email
  483. $user = $this;
  484. $profile = $user->profile;
  485. $email = $userToken->data ?: $user->email;
  486. $subject = Yii::$app->id . " - " . Yii::t("user", "Email Confirmation");
  487. $result = $mailer->compose('confirmEmail', compact("subject", "user", "profile", "userToken"))
  488. ->setTo($email)
  489. ->setSubject($subject)
  490. ->send();
  491.  
  492. // restore view path and return result
  493. $mailer->viewPath = $oldViewPath;
  494. return $result;
  495. }
  496.  
  497. /**
  498. * Get list of statuses for creating dropdowns
  499. * @return array
  500. */
  501. public static function statusDropdown()
  502. {
  503. // get data if needed
  504. static $dropdown;
  505. $constPrefix = "STATUS_";
  506. if ($dropdown === null) {
  507.  
  508. // create a reflection class to get constants
  509. $reflClass = new ReflectionClass(get_called_class());
  510. $constants = $reflClass->getConstants();
  511.  
  512. // check for status constants (e.g., STATUS_ACTIVE)
  513. foreach ($constants as $constantName => $constantValue) {
  514.  
  515. // add prettified name to dropdown
  516. if (strpos($constantName, $constPrefix) === 0) {
  517. $prettyName = str_replace($constPrefix, "", $constantName);
  518. $prettyName = Inflector::humanize(strtolower($prettyName));
  519. $dropdown[$constantValue] = $prettyName;
  520. }
  521. }
  522. }
  523.  
  524. return $dropdown;
  525. }
Add Comment
Please, Sign In to add comment