From 460d6f788aaf6076da71698157c9e4a3ca66c836 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Sun, 26 Feb 2023 13:15:31 +0100 Subject: [PATCH] Add Auth Db backend --- example/data/sqlite.init-db.sql | 12 +++ src/Auth/Db.php | 144 ++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 src/Auth/Db.php diff --git a/example/data/sqlite.init-db.sql b/example/data/sqlite.init-db.sql index 06ccab9..7200e55 100644 --- a/example/data/sqlite.init-db.sql +++ b/example/data/sqlite.init-db.sql @@ -1,3 +1,15 @@ +CREATE TABLE users ( + username text NOT NULL PRIMARY KEY, + name text COLLATE NOCASE NOT NULL, + mail text COLLATE NOCASE, + password text NOT NULL +); + +INSERT INTO users (username, name, mail, password) VALUES ( + "admin", "Administrator", "admin@example.com", + "$argon2id$v=19$m=65536,t=4,p=1$WTQ0di44NW11MUJ1b3RMQw$+LRAQRaIXE2jhfavNFNuxnEtEUT6tEBz/98pTtD0EnM" +); + CREATE TABLE item ( id INTEGER PRIMARY KEY, name text COLLATE NOCASE NOT NULL, diff --git a/src/Auth/Db.php b/src/Auth/Db.php new file mode 100644 index 0000000..149fd68 --- /dev/null +++ b/src/Auth/Db.php @@ -0,0 +1,144 @@ + fpdo -> from(self :: $users_table) + -> select(null) + -> select(self :: $exposed_fields) + -> where(self :: $username_field, $username); + + $result = $query -> execute(); + $info = $result -> fetch(); + if ($info === false) + return null; + return new User($username, '\\EesyPHP\\Auth\\Db', $info); + } + catch (Exception $e) { + Log :: error("Error retreiving user %s info from database: %s", $username, $e->getMessage()); + } + return false; + } + + /** + * Check a user password + * @param \EesyPHP\Auth\User $user The user object + * @param string $password The password to check + * @return boolean + */ + public static function check_password($user, $password) { + self :: connect(); + try { + $query = self :: $db -> fpdo -> from(self :: $users_table) + -> select(null) + -> select(self :: $password_field) + -> where(self :: $username_field, $user->username); + + $result = $query -> execute(); + $info = $result -> fetch(); + if ($info === false) + return false; + return password_verify($password, $info['password']); + } + catch (Exception $e) { + Log :: error("Error retreiving user %s password from database: %s", $user, $e->getMessage()); + } + return false; + } +}