. */ /** * An interface to the user table in the database */ class User extends Model { /** {@inheritDoc} */ public $table = 'user', $fillable_columns = ['username', 'password']; /** * Generate a random password * * @return string The password */ public static function generateRandomPassword() { return preg_replace('/[^\w]/', '', base64_encode(bin2hex(openssl_random_pseudo_bytes(4)))); } /** * Hash a password * * @param string $password The password to be hashed * @param int $cost The password cost * * @return string The hashed password */ public static function hash($password, $cost=null) { return password_hash( $password, Constants::password_algo, ['cost' => is_null($cost) ? Constants::password_cost : $cost] ); } /** * {@inheritDoc} * @param $key {@inheritDoc} * @param $value {@inheritDoc} */ public function mutator($key, $value) { switch ($key) { case 'password': return self::hash($password); break; default: return parent::mutator($key, $value); } } /** * Check if a user has administrator rights * * @return bool True iff the user has administrator rights */ public function isAdmin() { return in_array($this->id, Constants::user_admins); } /** * Verify a password * * @param string $password The password to verify * * @return bool True iff the password can be accepted */ public function verifyPassword($password) { if (!password_verify($password, $this->password)) { return false; } if (password_needs_rehash($this->password, Constants::password_algo, ['cost' => Constants::password_cost])) { $this->password = $password; } return true; } }