servnest/auth.php

81 lines
1.9 KiB
PHP
Raw Normal View History

<?php
2022-04-22 23:57:43 +00:00
define("USERNAME_REGEX", "^[a-z]{4,32}$");
define("PASSWORD_REGEX", "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8,1024}|.{10,1024}$");
// Password storage security
define("ALGO_PASSWORD", PASSWORD_ARGON2ID);
define("OPTIONS_PASSWORD", array(
"memory_cost" => 65536,
"time_cost" => 24,
"threads" => 64,
));
function checkPasswordFormat($password) {
if (preg_match("/" . PASSWORD_REGEX . "/", $password) !== 1)
userError("Password malformed.");
2022-04-22 23:57:43 +00:00
}
function checkUsernameFormat($username) {
if (preg_match("/" . USERNAME_REGEX . "/", $username) !== 1)
userError("Username malformed.");
2022-04-22 23:57:43 +00:00
}
function hashPassword($password) {
2022-04-18 14:05:00 +00:00
return password_hash($password, ALGO_PASSWORD, OPTIONS_PASSWORD);
}
2022-04-22 23:57:43 +00:00
function userExist($username) {
$usernameArray[0] = $username;
$db = new PDO('sqlite:' . DB_PATH);
$op = $db->prepare('SELECT username FROM users WHERE username = ?');
$op->execute($usernameArray);
$data = $op->fetch();
if (isset($data['username']))
return true;
else
2022-04-22 23:57:43 +00:00
return false;
}
function checkPassword($username, $password) {
2022-04-18 14:05:00 +00:00
$username2[0] = $username;
2022-04-18 14:05:00 +00:00
$db = new PDO('sqlite:' . DB_PATH);
2022-04-18 14:05:00 +00:00
$op = $db->prepare('SELECT username, password FROM users WHERE username = ?');
$op->execute($username2);
2022-04-18 14:05:00 +00:00
$dbPassword = $op->fetch()['password'];
2022-04-18 14:05:00 +00:00
return password_verify($password, $dbPassword);
}
function outdatedPasswordHash($username) {
2022-04-18 14:05:00 +00:00
$username2[0] = $username;
2022-04-18 14:05:00 +00:00
$db = new PDO('sqlite:' . DB_PATH);
2022-04-18 14:05:00 +00:00
$op = $db->prepare('SELECT username, password FROM users WHERE username = ?');
$op->execute($username2);
2022-04-18 14:05:00 +00:00
$dbPassword = $op->fetch()['password'];
2022-04-18 14:05:00 +00:00
return password_needs_rehash($dbPassword, ALGO_PASSWORD, OPTIONS_PASSWORD);
}
function changePassword($username, $password) {
2022-04-18 14:05:00 +00:00
$password = hashPassword($password);
2022-04-18 14:05:00 +00:00
$db = new PDO('sqlite:' . DB_PATH);
2022-04-18 14:05:00 +00:00
$stmt = $db->prepare("UPDATE users SET password = :password WHERE username = :username");
2022-04-18 14:05:00 +00:00
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
2022-04-18 14:05:00 +00:00
$stmt->execute();
}