Files
better_guestbook/api/auth/login.php
T

50 lines
1.3 KiB
PHP
Executable File

<?php
// Load API Library
require "../api.php";
$api = new gbAPI(false);
// Check Request Body
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
$api->answer(400, [
"error" => "false_request_method",
"error_text" => "Only POST allowed"
]);
}
if (!isset($_POST["username"]) || !isset($_POST["password"])) {
$api->answer(400, [
"error" => "missing_fields",
"error_text" => "Some fields are missing"
]);
}
$username = $_POST["username"];
$password = $_POST["password"];
// Prepare SQL Command
$hash = password_hash($password, PASSWORD_DEFAULT);
$command = "SELECT username, password FROM users WHERE username = :username AND password = :password";
$args = [
":username" => $username,
":password" => $hash
];
// Execute SQL Command
$result = $api->dbCommand($command, true, true, $args);
// Check Result
if ($result && password_verify($password, $result["password"])) {
// Login successful. Generate Auth Token
$token = $api->generateToken($username);
// Set cookies
setcookie("auth_token", $token, time() + 86400, "/");
setcookie("username", $username, time() + 86400, "/");
}else{
$api->answer(401, [
"error" => "unauthorized",
"error_text" => "A user with this password does not exists."
]);
}