Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- İlk Başda mysql'den tablo ve kolonları oluşduruyoruz .
- [CODE]CREATE TABLE `secure_login`.`members` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- `username` VARCHAR(30) NOT NULL,
- `email` VARCHAR(50) NOT NULL,
- `password` CHAR(128) NOT NULL,
- `salt` CHAR(128) NOT NULL
- ) ENGINE = InnoDB;[/CODE
- [CODE]CREATE TABLE `secure_login`.`login_attempts` (
- `user_id` INT(11) NOT NULL,
- `time` VARCHAR(30) NOT NULL
- ) ENGINE=InnoDB[/CODE]
- Config Dosyamızı oluşduruyoruz
- [CODE]<?php
- define("HOST", "localhost"); // The host you want to connect to.
- define("USER", "USER"); // The database username.
- define("PASSWORD", "PASSWORD"); // The database password.
- define("DATABASE", "secure_login"); // The database name.
- define("CAN_REGISTER", "any");
- define("DEFAULT_ROLE", "member");
- define("SECURE", FALSE);
- ?>
- [/CODE]
- DB config Bağlantı Dosyası oluşduruyoruz .
- [CODE]<?php
- include_once 'psl-config.php'; // As functions.php is not included
- $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
- ?>[/CODE]
- 1 Adet function.php oluşdurup fonksiyonları giriyoruz .
- [CODE]<?php
- include_once 'psl-config.php';
- function sec_session_start() {
- $session_name = 'sec_session_id'; // Set a custom session name
- $secure = SECURE;
- // This stops JavaScript being able to access the session id.
- $httponly = true;
- // Forces sessions to only use cookies.
- if (ini_set('session.use_only_cookies', 1) === FALSE) {
- header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
- exit();
- }
- // Gets current cookies params.
- $cookieParams = session_get_cookie_params();
- session_set_cookie_params($cookieParams["lifetime"],
- $cookieParams["path"],
- $cookieParams["domain"],
- $secure,
- $httponly);
- // Sets the session name to the one set above.
- session_name($session_name);
- session_start(); // Start the PHP session
- session_regenerate_id(); // regenerated the session, delete the old one.
- }
- function login($email, $password, $mysqli) {
- // Using prepared statements means that SQL injection is not possible.
- if ($stmt = $mysqli->prepare("SELECT id, username, password, salt
- FROM members
- WHERE email = ?
- LIMIT 1")) {
- $stmt->bind_param('s', $email); // Bind "$email" to parameter.
- $stmt->execute(); // Execute the prepared query.
- $stmt->store_result();
- // get variables from result.
- $stmt->bind_result($user_id, $username, $db_password, $salt);
- $stmt->fetch();
- // hash the password with the unique salt.
- $password = hash('sha512', $password . $salt);
- if ($stmt->num_rows == 1) {
- // If the user exists we check if the account is locked
- // from too many login attempts
- if (checkbrute($user_id, $mysqli) == true) {
- // Account is locked
- // Send an email to user saying their account is locked
- return false;
- } else {
- // Check if the password in the database matches
- // the password the user submitted.
- if ($db_password == $password) {
- // Password is correct!
- // Get the user-agent string of the user.
- $user_browser = $_SERVER['HTTP_USER_AGENT'];
- // XSS protection as we might print this value
- $user_id = preg_replace("/[^0-9]+/", "", $user_id);
- $_SESSION['user_id'] = $user_id;
- // XSS protection as we might print this value
- $username = preg_replace("/[^a-zA-Z0-9_\-]+/",
- "",
- $username);
- $_SESSION['username'] = $username;
- $_SESSION['login_string'] = hash('sha512',
- $password . $user_browser);
- // Login successful.
- return true;
- } else {
- // Password is not correct
- // We record this attempt in the database
- $now = time();
- $mysqli->query("INSERT INTO login_attempts(user_id, time)
- VALUES ('$user_id', '$now')");
- return false;
- }
- }
- } else {
- // No user exists.
- return false;
- }
- }
- }
- function checkbrute($user_id, $mysqli) {
- // Get timestamp of current time
- $now = time();
- // All login attempts are counted from the past 2 hours.
- $valid_attempts = $now - (2 * 60 * 60);
- if ($stmt = $mysqli->prepare("SELECT time
- FROM login_attempts
- WHERE user_id = ?
- AND time > '$valid_attempts'")) {
- $stmt->bind_param('i', $user_id);
- // Execute the prepared query.
- $stmt->execute();
- $stmt->store_result();
- // If there have been more than 5 failed logins
- if ($stmt->num_rows > 5) {
- return true;
- } else {
- return false;
- }
- }
- }
- unction login_check($mysqli) {
- // Check if all session variables are set
- if (isset($_SESSION['user_id'],
- $_SESSION['username'],
- $_SESSION['login_string'])) {
- $user_id = $_SESSION['user_id'];
- $login_string = $_SESSION['login_string'];
- $username = $_SESSION['username'];
- // Get the user-agent string of the user.
- $user_browser = $_SERVER['HTTP_USER_AGENT'];
- if ($stmt = $mysqli->prepare("SELECT password
- FROM members
- WHERE id = ? LIMIT 1")) {
- // Bind "$user_id" to parameter.
- $stmt->bind_param('i', $user_id);
- $stmt->execute(); // Execute the prepared query.
- $stmt->store_result();
- if ($stmt->num_rows == 1) {
- // If the user exists get variables from result.
- $stmt->bind_result($password);
- $stmt->fetch();
- $login_check = hash('sha512', $password . $user_browser);
- if ($login_check == $login_string) {
- // Logged In!!!!
- return true;
- } else {
- // Not logged in
- return false;
- }
- } else {
- // Not logged in
- return false;
- }
- } else {
- // Not logged in
- return false;
- }
- } else {
- // Not logged in
- return false;
- }
- }
- function esc_url($url) {
- if ('' == $url) {
- return $url;
- }
- $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
- $strip = array('%0d', '%0a', '%0D', '%0A');
- $url = (string) $url;
- $count = 1;
- while ($count) {
- $url = str_replace($strip, '', $url, $count);
- }
- $url = str_replace(';//', '://', $url);
- $url = htmlentities($url);
- $url = str_replace('&', '&', $url);
- $url = str_replace("'", ''', $url);
- if ($url[0] !== '/') {
- // We're only interested in relative links from $_SERVER['PHP_SELF']
- return '';
- } else {
- return $url;
- }
- }
- <?[/CODE]
- Giriş Sayfası oluşduruyoruz şimdi
- [CODE]<?php
- include_once 'db_connect.php';
- include_once 'functions.php';
- sec_session_start(); // Our custom secure way of starting a PHP session.
- if (isset($_POST['email'], $_POST['p'])) {
- $email = $_POST['email'];
- $password = $_POST['p']; // The hashed password.
- if (login($email, $password, $mysqli) == true) {
- // Login success
- header('Location: ../protected_page.php');
- } else {
- // Login failed
- header('Location: ../index.php?error=1');
- }
- } else {
- // The correct POST variables were not sent to this page.
- echo 'Invalid Request';
- }[/CODE]
- Çıkış yani logout.php oluşduruyoruz .
- [CODE]<?php
- include_once 'functions.php';
- sec_session_start();
- // Unset all session values
- $_SESSION = array();
- // get session parameters
- $params = session_get_cookie_params();
- // Delete the actual cookie.
- setcookie(session_name(),
- '', time() - 42000,
- $params["path"],
- $params["domain"],
- $params["secure"],
- $params["httponly"]);
- // Destroy session
- session_destroy();
- header('Location: LOCATION YOU WANT IT TO GO');[/CODE]
- 1 Adet forms.js Oluşduruyoruz
- [CODE]function formhash(form, password) {
- // Create a new element input, this will be our hashed password field.
- var p = document.createElement("input");
- // Add the new element to our form.
- form.appendChild(p);
- p.name = "p";
- p.type = "hidden";
- p.value = hex_sha512(password.value);
- // Make sure the plaintext password doesn't get sent.
- password.value = "";
- // Finally submit the form.
- form.submit();
- }
- function regformhash(form, uid, email, password, conf) {
- // Check each field has a value
- if (uid.value == '' ||
- email.value == '' ||
- password.value == '' ||
- conf.value == '') {
- alert('You must provide all the requested details. Please try again');
- return false;
- }
- // Check the username
- re = /^\w+$/;
- if(!re.test(form.username.value)) {
- alert("Username must contain only letters, numbers and underscores. Please try again");
- form.username.focus();
- return false;
- }
- // Check that the password is sufficiently long (min 6 chars)
- // The check is duplicated below, but this is included to give more
- // specific guidance to the user
- if (password.value.length < 6) {
- alert('Passwords must be at least 6 characters long. Please try again');
- form.password.focus();
- return false;
- }
- // At least one number, one lowercase and one uppercase letter
- // At least six characters
- var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
- if (!re.test(password.value)) {
- alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
- return false;
- }
- // Check password and confirmation are the same
- if (password.value != conf.value) {
- alert('Your password and confirmation do not match. Please try again');
- form.password.focus();
- return false;
- }
- // Create a new element input, this will be our hashed password field.
- var p = document.createElement("input");
- // Add the new element to our form.
- form.appendChild(p);
- p.name = "p";
- p.type = "hidden";
- p.value = hex_sha512(password.value);
- // Make sure the plaintext password doesn't get sent.
- password.value = "";
- conf.value = "";
- // Finally submit the form.
- form.submit();
- return true;
- }[/CODE]
- ve Son olarak login.php'mizi ekliyoruz .
- [CODE]<?php
- include_once 'includes/db_connect.php';
- include_once 'includes/functions.php';
- sec_session_start();
- if (login_check($mysqli) == true) {
- $logged = 'in';
- } else {
- $logged = 'out';
- }
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <title>Secure Login: Log In</title>
- <link rel="stylesheet" href="styles/main.css" />
- <script type="text/JavaScript" src="js/sha512.js"></script>
- <script type="text/JavaScript" src="js/forms.js"></script>
- </head>
- <body>
- <?php
- if (isset($_GET['error'])) {
- echo '<p class="error">Error Logging In!</p>';
- }
- ?>
- <form action="includes/process_login.php" method="post" name="login_form">
- Email: <input type="text" name="email" />
- Password: <input type="password"
- name="password"
- id="password"/>
- <input type="button"
- value="Login"
- clickon="formhash(this.form, this.form.password);" />
- </form>
- <p>If you don't have a login, please <a href="register.php">register</a></p>
- <p>If you are done, please <a href="includes/logout.php">log out</a>.</p>
- <p>You are currently logged <?php echo $logged ?>.</p>
- </body>
- </html>[/CODE]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement