From f312ae83ce52b6d653b22cf047c455e222ef2b9d Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Mon, 11 Jun 2018 23:57:05 +0200 Subject: [PATCH] adding app/models/Data/PasswordLink.php --- app/models/Data/PasswordLink.php | 174 +++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 app/models/Data/PasswordLink.php diff --git a/app/models/Data/PasswordLink.php b/app/models/Data/PasswordLink.php new file mode 100644 index 0000000..9f834c4 --- /dev/null +++ b/app/models/Data/PasswordLink.php @@ -0,0 +1,174 @@ +setSource('password_link'); + $this->useDynamicUpdate(true); + + // Relationships + $this->belongsTo('user_id', User::class, 'id', array('alias' => 'User')); + + // Behaviour + $this->addBehavior(new RandomIdBehavior(array( + 'field' => 'public_id', + 'length' => 12, + 'expression' => '(password IS NULL OR HOUR(TIMEDIFF(date, NOW())) = 0)' + ))); + + $this->addBehavior(new SoftDelete([ + 'field' => 'password', + 'value' => null + ])); + } + + /** + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * @param int $id + * @return PasswordLink + */ + public function setId(int $id) : PasswordLink + { + $this->id = $id; + return $this; + } + + /** + * @return string + */ + public function getPublicId() + { + return $this->public_id; + } + + /** + * @param string $public_id + * @return PasswordLink + */ + public function setPublicId(string $public_id) : PasswordLink + { + $this->public_id = $public_id; + return $this; + } + + /** + * @return int + */ + public function getUserId() + { + return $this->user_id; + } + + /** + * @param int $user_id + * @return PasswordLink + */ + public function setUserId(int $user_id) : PasswordLink + { + $this->user_id = $user_id; + return $this; + } + + /** + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * @param string $password + * @return PasswordLink + */ + public function setPassword(string $password) : PasswordLink + { + $this->password = $password; + return $this; + } + + /** + * Has the link been used? + * + * @return bool + */ + public function isUsed() : bool + { + return strlen($this->password) < 1; + } + + /** + * Is the link still valid? + * + * @return bool + */ + public function isValid() : bool + { + // Used links are not valid. + if ($this->isUsed()) { + return false; + } + + $date = new \DateTime($this->date); + $now = new \DateTime(); + + // Get the differerence in hours. + $diff = $now->format('U') - $date->format('U'); + $diff = ($diff / 60) / 60; + + // Only valid for an hour. + return $diff >= 0 && $diff <= 1; + } + + public function beforeCreate() + { + // Creating a new link automatically removes old ones. + $links = self::find(["user_id = ?0", 'bind' => [ $this->user_id ]]); + + foreach($links as $link) { + $link->delete(); + } + } +}