* @license BSD */ namespace Domframework; /** * User authentication against .htpasswd file * A .htpasswd can be created by the 'htpasswd' command for Apache, and contain * toto@toto.com:$2y$05$uHCUNqicE7Pku3MK1qZaDuJxP/pocqCcEAnacZBjsfWgW9EcuG5y2 */ class Authhtpasswd extends Auth { /** * The .htpasswd file to use for authentication */ public $htpasswdFile; /** * The details to return if the user is authenticated */ private $details = null; /** * There is no real connection to htpasswd */ public function connect() { if (! file_exists($this->htpasswdFile)) { throw new \Exception(sprintf( dgettext( "domframework", "The HTPasswd file '%s' is not found" ), $this->htpasswdFile ), 500); } if (! is_readable($this->htpasswdFile)) { throw new \Exception(sprintf( dgettext( "domframework", "The HTPasswd file '%s' is not readable" ), $this->htpasswdFile ), 500); } } /** * Try to authenticate the email/password of the user * @param string $email Email to authenticate * @param string $password Password to authenticate */ public function authentication($email, $password) { // Redo the checks of connect to not have a property to add $this->connect(); $file = file_get_contents($this->htpasswdFile); $lines = explode("\n", $file); foreach ($lines as $line) { // Comment line : skip it if (isset($line[0]) && $line[0] === "#") { continue; } $line = trim($line); $user = strstr($line, ":", true); $cryptedPassword = substr(strstr($line, ':'), 1); if ($user === $email) { if (substr($cryptedPassword, 0, 6) === '$apr1$') { throw new \Exception(dgettext( "domframework", "Invalid format of password" ), 500); } if (crypt($password, $cryptedPassword) !== $cryptedPassword) { throw new \Exception("Bad password for '$email'", 401); } $this->details = ["email" => $email]; return true; } } throw new \Exception("Unable to find the user : '$email'", 401); } /** * Return all the parameters recorded for the authenticate user */ public function getdetails() { return $this->details; } /** * Method to change the password * @param string $oldpassword The old password (to check if the user have the * rights to change the password) * @param string $newpassword The new password to be recorded */ public function changepassword($oldpassword, $newpassword) { throw new \Exception( dgettext( "domframework", "The password can't be change for HTPasswd users" ), 405 ); } /** * Method to overwrite the password (without oldpassword check) * Must be reserved to the administrators. For the users, use changepassword * method * @param string $email the user identifier to select * @param string $newpassword The new password to be recorded */ public function overwritepassword($email, $newpassword) { throw new \Exception( dgettext( "domframework", "The password can't be change for HTPasswd users" ), 405 ); } }