如何进行自动授权

时间:2020-08-30 17:56:18

标签: php

注册后,我想在我的网站上进行自动授权。 (在成功注册用户后立即登录)。我做什么和拥有什么:

我有auth.php

<?php

session_start();

function getRandom16IV()  {
    // get iv for encryption
    $alph = array_merge(range('A', 'Z'), range('a', 'z'));
    $result = "";
    $i = 0;
    while ($i != 16) {
        $result = $result . $alph[array_rand($alph, 1)];
        $i++;
    }
    return $result;
}

function getRandom255Key() {
    // get key from encryprion
    $numbers = range(1, 9);
    $result = "";
    $i = 0;
    while ($i != 255) {
        $result = $result . $numbers[array_rand($numbers, 1)];
        $i++;
    }
    return $result;
}
// get login or password values
$log_mail = $_POST['login_mail'];
$pwd      = $_POST['pwd'];
// get params for DB from config.php
include("config.php");
$con = mysqli_connect($db_ip, $db_login, $db_pwd , $db_name);
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// process inputs
$login_mail = $_POST['login_mail'];
$pwd = stripslashes($_POST['pwd']);
$pwd = mysqli_real_escape_string($con, $pwd);

// check if user exist
$query    = "SELECT login, pwd, email FROM `users`";
$result   = mysqli_query($con, $query);

// if user exist
$user_exist = false;
while($row = $result->fetch_assoc()) {
    if ($row["login"] == $login_mail or $row["email"] == $login_mail) {
        if ($row["pwd"] == $pwd) {
            $user_exist = true;
        }
    }
}


// authorize if user exist in DB
if ($user_exist == true) {
    include("config.php");
    include("get_from_db_functions.php");
    $key = getRandom255Key();
    $iv = getRandom16IV();
    
    $encrypt_result = openssl_encrypt($login_mail, $encr_method, $key, $options=0, $iv);

    $bday = getBday($login_mail);
    $age = calcAge($bday);

    setcookie("login_encr", $encrypt_result, time() + (86400 * 30 * 31 * 12), "/"); // год
    setcookie("logged_in", "true", time() + (86400 * 30 * 31 * 12), "/");
    setcookie("age", $age, time() + (86400 * 30 * 31 * 12), "/");
    
    $query    = "SELECT id FROM `users`WHERE login='$login_mail' OR email='$login_mail' LIMIT 1";
    $result   = mysqli_query($con, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        setcookie("id", $row['id'], time() + (86400 * 30 * 31 * 12), "/");
    }
    
    $query    = "UPDATE `users` SET encr_iv='$iv', encr_key='$key' WHERE login='$login_mail' OR email='$login_mail'";
    $result   = mysqli_query($con, $query);
    
    $_SESSION['auth-errors'] = array(); // no errors array
    
} else {
    // we have errors while authorization
    $_SESSION['auth-errors'] = array(
        'e1' => "Wrong login or password"
    );

}

$con->close();

header("Location: ../index.php");

?>

registration.php

// user registration... in sucessfull case I use this post request trying to authorize:
// set post fields

session_start();

header('Content-Type: charset=utf-8');

include("config.php");
include("get_from_db_functions.php");
include("user_params_operations.php");

function validateInputs() {
    
    $valid = true;
    $errorMessage = array();
    foreach ($_POST as $key => $value) {
        if (empty($_POST[$key])) {
            $valid = false;
        }
    }
    if($valid == false) {
        $errorMessage[] = "Need to fill all fields";
    }
    return;
}

$registration_result = validateInputs();
$_SESSION['registration_errors'] = $registration_result;

$con = setConnection();

$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($con, $name);
$surname = stripslashes($_POST['surname']);
$surname = mysqli_real_escape_string($con, $surname);
$login = stripslashes($_POST['login']);
$login = mysqli_real_escape_string($con, $login);
$pwd = stripslashes($_POST['pwd']);
$pwd = mysqli_real_escape_string($con, $pwd);
$email = stripslashes($_POST['email']);
$email = mysqli_real_escape_string($con, $email);
$bday = stripslashes($_POST['date']);
$bday = mysqli_real_escape_string($con, $bday);

// check if user exist
$user_check_query = "SELECT id FROM users WHERE login='$login' OR email='$email' LIMIT 1";
$result = mysqli_query($con, $user_check_query);
$user = mysqli_fetch_assoc($result);

if ($user) {
    // if user exist return error
    if ($_SESSION['registration_errors'] == null) {
        $_SESSION['registration_errors'] = array();
    }
    if ($user['login'] === $login) {
        array_push($_SESSION['registration_errors'], "user already exist");
    } else if ($user['email'] === $email) {
        array_push($_SESSION['registration_errors'], "usere already exist");
    }
} else {
    
    $query    = "INSERT INTO `users` (name, surname, login, pwd, birthdate, email, encr_iv, encr_key) VALUES ( '$name', '$surname', '$login', '$pwd', '$bday', '$email', '', '')";
    $result   = mysqli_query($con, $query);
    
    
    $getid = "SELECT id FROM users WHERE login='$login' OR email='$email' LIMIT 1";
    $result = mysqli_query($con, $getid);
    while ($row = mysqli_fetch_assoc($result)) {
        $id = $row['id'];
        $age = calcAgeByBirthDate($bday);
        $query    = "INSERT INTO `user_params` (user_id, age, happiness_level, good_habbits, bad_habbits, max_lifespan, expected_lifespan)
                    VALUES ('$id', '$age', 0, '', '', 0, 0)";
        $res   = mysqli_query($con, $query);
    }



    // set post fields
    $post = [
        'login_mail' => $login,
        'pwd' => $pwd
    ];

    $ch = curl_init('auth.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    // execute!
    $response = curl_exec($ch);

    // close the connection, release resources used
    curl_close($ch);

    // do anything you want with your response
    // var_dump($response);
}



$con->close();
header("Location: ../profile.php");

如果我单独使用auth,它可以正常工作,可以正常注册,但不能按我的要求进行授权(通过注册后的发帖请求)。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

在此处使用cURL并不是解决方案。 cURL函数将对文件发出新的不同HTTP请求,客户端将不是用户的浏览器,而是Web服务器PHP正在运行。任何会话/登录cookie都将保存在网络服务器上,但应存储在用户的浏览器中。

您必须使用include语句从其他PHP脚本加载和运行代码。它应该类似于include 'auth.php';,但执行起来“太多”。您只需要生成和发送Cookie的部分。根据代码的工作方式和系统的结构,您可以将“生成并发送登录cookie”部分提取到单独的PHP脚本或新函数中。因此,您将编写诸如include 'sendauthcookie.php';sendLoginCookies($login_mail);之类的内容以生成登录cookie并将其发送到用户的浏览器。可以从您的“ auth.php”文件以及“ registration.php”文件中调用此代码。

答案 1 :(得分:1)

最佳解决方案将用户详细信息存储在与Encrypt的会话中。

并使用它!

编辑更改

registration.php

// set post fields
$_SESSION['en_user'] = encrypt($login);
$_SESSION['en_pass'] = encrypt($pwd);
header("Location: auth.php");
//end

encrypt.php

function encrypt($payload) {
  $key ='whatxxxxwhatever';
  $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
  $encrypted = openssl_encrypt($payload, 'aes-256-cbc', $key, 0, $iv);
  $var = base64_encode($encrypted . '::' . $iv);
  $var = strtr($var, '+/=', '-_,');
  return $var;
}

function decrypt($garble) {
    $garble = strtr($garble, '-_,', '+/=');
    $key ='whatxxxxwhatever';
    list($encrypted_data, $iv) = explode('::', base64_decode($garble), 2);
    return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}

auth.php

//include encrypt.php
if(isset($_POST['login_mail']) && isset($_POST['pwd']))
{
    $log_mail = $_POST['login_mail'];
    $pwd      = $_POST['pwd'];
}elseif(isset($_SESSION['en_user']) && isset($_SESSION['en_pass']))
{
    $log_mail = decrypt($_SESSION['en_user']);
    $pwd      = decrypt($_SESSION['en_pass']);
}else{
    unset($_SESSION['en_user']); 
    unset($_SESSION['en_pass']); 
    exit;
}

在“数据库”中使用会话以确保安全。

尝试一下