added login and utils functions, to start the project

This commit is contained in:
Louis Vallat 2019-11-09 22:33:47 +01:00
commit 0ce0c5dccb
2 changed files with 276 additions and 0 deletions

184
assets/php/utils.php Normal file
View File

@ -0,0 +1,184 @@
<?php
$SESSION_COOKIE_NAME = "connection_id";
$MAX_COOKIE_LIFE = time() + 86400 * 30; // 30 days max
$dsn = "mysql:dbname=food-inventory;host=localhost";
$user = 'food-inventory';
$password = 'xt3apB8uVbFIYJvp';
$PDO = new PDO($dsn, $user, $password);
$PDO->query('SET CHARSET UTF8');
function is_https()
{
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
function generate_random_string()
{
return substr(str_shuffle(MD5(microtime())), 0, 32);
}
function connect_user($user_id, $long_expiration = true)
{
global $PDO, $SESSION_COOKIE_NAME, $MAX_COOKIE_LIFE;
// Set an expiration delay for the cookie
$delay = 0;
if ($long_expiration === true) {
$delay = $MAX_COOKIE_LIFE;
}
// The session id is a 32-chars random string
$session_id = generate_random_string();
$sql = "INSERT INTO sessions(user_id, connection_eol, session_id)
VALUES (:user_id, :connection_eol, :session_id);";
$query = $PDO->prepare($sql);
$query->bindValue(":user_id", $user_id);
if ($long_expiration === true) {
$query->bindValue(
":connection_eol",
date('Y-m-d H:i:s', strtotime(
"$MAX_COOKIE_LIFE seconds",
strtotime(date("Y-m-d H:i:s"))
))
);
} else {
$query->bindValue(":connection_eol", null, PDO::PARAM_INT);
}
$query->bindValue(":session_id", $session_id);
if ($query->execute()) {
return setcookie(
$SESSION_COOKIE_NAME,
$session_id,
$delay,
$secure = true
);
}
return false;
}
function clean_old_sessions()
{
global $PDO;
$sql = "DELETE FROM sessions WHERE connection_eol > CURRENT_TIMESTAMP();";
$query = $PDO->prepare($sql);
return $query->execute();
}
function is_connected()
{
global $PDO, $SESSION_COOKIE_NAME;
if (isset($_COOKIE[$SESSION_COOKIE_NAME])) {
if (!clean_old_sessions()) {
return false;
}
$sql = "SELECT * FROM sessions INNER JOIN accounts ON sessions.user_id = accounts.id WHERE session_id = :session_id;";
$query = $PDO->prepare($sql);
$query->bindValue(":session_id", $_COOKIE[$SESSION_COOKIE_NAME]);
if ($query->execute()) {
if ($query->rowCount() === 1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
return false;
}
function disconnect()
{
global $PDO, $SESSION_COOKIE_NAME;
if (isset($_COOKIE[$SESSION_COOKIE_NAME])) {
$sql = "DELETE FROM sessions WHERE session_id = :session_id;";
$query = $PDO->prepare($sql);
$query->bindValue(":session_id", $_COOKIE[$SESSION_COOKIE_NAME]);
$query->execute();
setcookie($SESSION_COOKIE_NAME, "", time() - 3600);
}
}
function get_username_count($email)
{
global $PDO;
$sql = "SELECT email FROM accounts WHERE email = :email;";
$query = $PDO->prepare($sql);
$query->bindValue(":email", $email);
if ($query->execute()) {
return $query->rowCount();
}
return false;
}
function correct_email_password($email, $password)
{
global $PDO;
$sql = "SELECT email, password FROM accounts WHERE email = :email;";
$query = $PDO->prepare($sql);
$query->bindValue(":email", $email);
if ($query->execute()) {
foreach ($query as $row) {
return password_verify($password, $row["password"]);
}
}
return false;
}
function get_user_id_from_email($email)
{
global $PDO;
$sql = "SELECT id FROM accounts WHERE email = :email;";
$query = $PDO->prepare($sql);
$query->bindValue(":email", $email);
if ($query->execute()) {
foreach ($query as $row) {
return $row["id"];
}
}
return false;
}
function get_user_info_from_session_id($session_id, $info)
{
global $PDO, $SESSION_COOKIE_NAME;
if (isset($_COOKIE[$SESSION_COOKIE_NAME])) {
$sql = "SELECT * FROM accounts
INNER JOIN sessions
ON sessions.user_id = accounts.id
WHERE session_id = :session_id;";
$query = $PDO->prepare($sql);
$query->bindValue(":session_id", $session_id);
if ($query->execute())
foreach ($query as $row) {
switch ($info) {
case "email":
case "first_name":
case "last_name":
case "public_id":
return $row[$info];
default;
break;
}
}
}
return false;
}

92
login.php Normal file
View File

@ -0,0 +1,92 @@
<?php
// Include util functions
require_once("./assets/php/utils.php");
// Check if the user is already logged in, if yes then redirect him to welcome page
if (is_connected()) {
header("location: welcome.php");
exit;
}
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if username is empty
if (empty(trim($_POST["username"]))) {
$username_err = "Please enter your username.";
} else {
$username = trim($_POST["username"]);
}
// Check if password is empty
if (empty(trim($_POST["password"]))) {
$password_err = "Please enter your password.";
} else {
$password = trim($_POST["password"]);
}
// Validate credentials
if (empty($username_err) && empty($password_err)) {
// Check if username exists, if yes then verify password
if (get_username_count($username) == 1) {
if (correct_email_password($username, $password)) {
connect_user(get_user_id_from_email($username), false);
// Redirect user to welcome page
header("location: welcome.php");
} else {
// Display an error message if password is not valid
$username_err = "Invalid Username/Password.";
}
} else {
$username_err = "Invalid Username/Password.";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<style type="text/css">
body {
font: 14px sans-serif;
}
.wrapper {
width: 350px;
padding: 20px;
}
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? <a href="register.php">Sign up now</a>.</p>
</form>
</div>
</body>
</html>