12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- header('Content-type: application/json');
-
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
- # Gets json from POST
- $json = json_decode(file_get_contents('php://input'), true);
-
- # Input validation for username y password
- $correo = $json["correo"];
- $password = $json["password"];
-
- if(strlen($correo) == 0 or strlen($password) == 0){
- http_response_code(400);
- echo json_encode(array("error" => "Correo o password vacio."));
-
- exit();
- }
-
- include 'db.php';
-
- # Select username row
- $sql = "SELECT userid, hash FROM Login WHERE correo = '".$correo."'";
- $result = $conn->query($sql);
-
- if($result === FALSE){
- http_response_code(500);
- echo json_encode(array("error" => "Error de base de datos 1."));
-
- $conn->close();
- exit();
- }
-
- if($result->num_rows){
- # Grabs password hash
- $result = $result->fetch_assoc();
- $hash = $result["hash"];
- $userid = $result["userid"];
-
- } else {
- http_response_code(401);
- echo json_encode(array("error" => "Correo o password incorrecto."));
-
- $conn->close();
- exit();
- }
-
- # Verifies password
- if(!password_verify($password, $hash)){
- $conn->close();
-
- http_response_code(401);
- echo json_encode(array("error" => "Correo o password incorrecto."));
-
- exit();
- }
-
- $token = bin2hex(random_bytes(16));
-
- # Insert Token
- $sql = "INSERT INTO Token (token, userid) VALUES (\"".$token."\", ".$userid.") ON DUPLICATE KEY UPDATE token = \"".$token."\";";
- if($conn->query($sql) === FALSE){
- http_response_code(500);
- echo json_encode(array("error" => "Error de base de datos 2."));
-
- $conn->close();
- exit();
- }
-
- http_response_code(200);
- echo json_encode(array("token" => $token));
-
- } else {
- header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
- exit();
- }
- ?>
|