воскресенье, 8 октября 2017 г.

Соцсеть. Дизайн страницы создания аккаунта. Урок 35.

Создание аккаунта.


В папку api переносим файл из папки classes Mail.php и папку PHPMailer.

Идем в api/index.php

<?php
require_once("DB.php");
require_once("Mail.php");

$db = new DB("127.0.0.1", "SocialNetwork", "root", "");

// 'REQUEST_METHOD' - Какой метод был использован для запроса страницы; к примеру 'GET', 'HEAD', 'POST', 'PUT'.
if ($_SERVER['REQUEST_METHOD'] == "GET") {
if ($_GET['url'] == "auth") {
} else if ($_GET['url'] == "users") {
}
} else if ($_SERVER['REQUEST_METHOD'] == "POST") {
// Создание аккаунта
if ($_GET['url'] == "users") {
$postBody = file_get_contents("php://input");
$postBody = json_decode($postBody);

$username = $postBody->username;
$email = $postBody->email;
$password = $postBody->password;
if(!$db->query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
if(strlen($username) >= 3 && strlen($username) <= 32) {
if(preg_match('/[a-zA-Z0-9_]+/', $username)) {
if(strlen($password) >= 6 && strlen($password) <= 60) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
if(!$db->query('SELECT email FROM users WHERE email=:email', array(':email'=>$email))) {
$db->query('INSERT INTO users VALUES (:id, :username, :password, :email, \'0\', \'\')', array(':id'=>null, ':username'=>$username, ':password'=>password_hash($password, PASSWORD_BCRYPT), ':email'=>$email));
Mail::sendMail('Welcome to our Social Network!', 'Your account has been created!', $email);
echo '{ "Success": "User created!" }';
http_response_code(200);
} else {
echo '{ "Error": "Email in use!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "Invalid Email!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "Invalid Password!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "Invalid username!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "Invalid username!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "User exists!" }';
http_response_code(409); // 409 Conflict («конфликт»)
}
}
// Логин
if ($_GET['url'] == "auth") {
$postBody = file_get_contents("php://input");
$postBody = json_decode($postBody);

$username = $postBody->username;
$password = $postBody->password;

if ($db->query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
// password_verify — Проверяет, соответствует ли пароль хешу
if (password_verify($password, $db->query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])) {
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = $db->query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
$db->query('INSERT INTO login_tokens VALUE (:id, :token, :user_id)', array(':id'=>null, ':token'=>sha1($token), ':user_id'=>$user_id));
echo '{ "Token": "'.$token.'" }';
} else {
echo '{ "Error": "Invalid username or password!" }';
http_response_code(401);
}
} else {
echo '{ "Error": "Invalid username or password!" }';
http_response_code(401);
}
}
} else if ($_SERVER['REQUEST_METHOD'] == "DELETE") {
if ($_GET['url'] == "auth") {
if (isset($_GET['token'])) {
if ($db->query("SELECT token FROM login_tokens WHERE token=:token", array(':token'=>sha1($_GET['token'])))) {
$db->query('DELETE FROM login_tokens WHERE token=:token', array(':token'=>sha1($_GET['token'])));
echo '{ "Status": "Success" }';
http_response_code(200);
} else {
echo '{ "Error": "Invalid token" }';
http_response_code(400);
}
} else {
echo '{ "Error": "Mal-formed request" }';
http_response_code(400);
}
}
}
else {
http_response_code(405);
}


?>


Создаем файт create-account.html


<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SocialNetwork</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/fonts/ionicons.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<link rel="stylesheet" href="assets/css/Login-Form-Clean.css">
<link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>
<div class="login-clean">
<form method="post">
<h2 class="text-center">Create Account</h2>
<div class="illustration"><i class="icon ion-ios-navigate"></i></div>
<div class="form-group">
<input class="form-control" id="username" type="text" name="username" placeholder="Username">
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" name="email" placeholder="Email">
</div>
<div class="form-group">
<input class="form-control" id="password" type="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" id="ca" type="button" data-bs-hover-animate="shake">Create Account</button>
</div><a href="#" class="forgot">Already got an account? Click here!</a></form>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
$('#ca').click(function() {

$.ajax({

type: "POST",
url: "api/users",
processData: false,
contentType: "application/json",
data: '{ "username": "'+ $("#username").val() +'", "email": "'+ $("#email").val() +'", "password": "'+ $("#password").val() +'" }',
success: function(r) {
console.log(r)
},
error: function(r) {
setTimeout(function() {
$('[data-bs-hover-animate]').removeClass('animated ' + $('[data-bs-hover-animate]').attr('data-bs-hover-animate'));
}, 2000)
$('[data-bs-hover-animate]').addClass('animated ' + $('[data-bs-hover-animate]').attr('data-bs-hover-animate'))
console.log(r)
}

});

});
</script>
</body>

</html>

Комментариев нет:

Отправить комментарий

Materialize-css. Футер

Сделаем футер и прижмем к низу страницы. Документация: https://materializecss.com/footer.html