servnest/auth.php

87 lines
2 KiB
PHP

<?php
define("USERNAME_REGEX", "^[a-z]{4,32}$");
define("PASSWORD_REGEX", "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8,1024}|.{10,1024}$");
define("ORIGIN", "https://niver.test:42443");
define("CHGRP_PATH", "/usr/bin/chgrp");
// Password storage security
define("ALGO_PASSWORD", PASSWORD_ARGON2ID);
define("OPTIONS_PASSWORD", array(
"memory_cost" => 65536,
"time_cost" => 24,
"threads" => 64,
));
function checkPasswordFormat($password) {
return preg_match("/" . PASSWORD_REGEX . "/", $password);
}
function checkUsernameFormat($username) {
return preg_match("/" . USERNAME_REGEX . "/", $username);
}
function hashPassword($password) {
return password_hash($password, ALGO_PASSWORD, OPTIONS_PASSWORD);
}
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']))
$dbUsername = $data['username'];
else
$dbUsername = NULL;
if (isset($dbUsername)) {
return true;
} else {
return false;
}
}
function checkPassword($username, $password) {
$username2[0] = $username;
$db = new PDO('sqlite:' . DB_PATH);
$op = $db->prepare('SELECT username, password FROM users WHERE username = ?');
$op->execute($username2);
$dbPassword = $op->fetch()['password'];
return password_verify($password, $dbPassword);
}
function outdatedPasswordHash($username) {
$username2[0] = $username;
$db = new PDO('sqlite:' . DB_PATH);
$op = $db->prepare('SELECT username, password FROM users WHERE username = ?');
$op->execute($username2);
$dbPassword = $op->fetch()['password'];
return password_needs_rehash($dbPassword, ALGO_PASSWORD, OPTIONS_PASSWORD);
}
function changePassword($username, $password) {
$password = hashPassword($password);
$db = new PDO('sqlite:' . DB_PATH);
$stmt = $db->prepare("UPDATE users SET password = :password WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
}