0

I'm fairly new to PHP/JS/AJAX and have just been trying to put up some kind of register/login form connected to mysql DB. However, once i try to login (register works fine, creates accounts in DB) i ALWAYS get "Invalid username or password" message. Maybe some of you would be able to show where have i made the mistake since i really cannot find it.

//login.library.php
<?php

if(isset($_POST['login']) && isset($_POST['password'])) {

$um = new UserManager;

if($um->LogIn($_POST['login'], $_POST['password'])) {

    header("Location: ".$_SERVER['HTTP_REFERER']); 

} else {

    die("Invalid username or Password.");

} 

} else { 
    die("Access to this site has been locked."); 
}

?>

UserManager.class.php:

protected $login;
protected $password;
protected $mail;
protected $id;

public function LogIn($LOGIN, $PASSWORD) {

    $this->login = $LOGIN;
    $this->password = $PASSWORD;



    if(self::isExist() && count(self::isExist()) > 0) {
         $id = self::getIdByUsername();
         $this->id = $id;


        self::log_in();
        return $this->login;

    } else {

        return false;

    }

}

protected function isExist() {

    $arr = DatabaseManager::selectBySQL("SELECT * FROM users WHERE username='".$this->login."' AND password='".md5($this->password)."' LIMIT 1");
    return $arr;

}

protected function getIdByUsername() {

    $array = DatabaseManager::selectBySQL("SELECT * FROM users WHERE username='".$this->login."' AND password='".md5($this->password)."' LIMIT 1");
    foreach($array as $key) {
        $id = $key['id'];
    }
    return $id;

}

protected function log_in() {

    $_SESSION['uid'] = $this->id;
    $_SESSION['logged'] = true;

}

Also, the login case from ModuleLoader.class.php:

case 'logowanie':
        echo '
            <div class="row logowanie">
                         <div class="col-xs-12 col-sm-8 col-md-6 col-lg-6 col-lg-offset-3 col-md-offset-3 col-sm-offset-2">
                        <h2>Zaloguj:</h2>
                        <form action="login/" method="POST" class="home_form">

                            <label for="login">Nazwa użytkownika</label>
                            <input id="login" type="text" name="login"> <br/>

                            <label for="haslo">Hasło</label>
                            <input id="haslo" type="password" name="password"> <br/>

                            <input type="submit" name="zaloguj" value="Zaloguj">
                        </form>                
                </div>

            </div>
        ';
        break;

And the .js file:

$(document).ready(function() {
 function walidacjaFormularza(id, ilosc_znakow, komunikat_ok, komunikat_blad, wzor){
$(id).on('blur', function() {
    var input = $(this);

    if (typeof wzor != 'undefined') { //uznajemy że jest to email i nie sprawdzamy innych warunków
       var email = wzor.test(input.val()); 

       if(email){
            input.removeClass("invalid").addClass("valid");
            input.next('.komunikat').text(komunikat_ok).removeClass("blad").addClass("ok");
       }
        else {
            input.removeClass("valid").addClass("invalid");
            input.next('.komunikat').text(komunikat_blad).removeClass("ok").addClass("blad");
        }
       return;
    } 

    var input_length = input.val().length;

    if(input_length >= ilosc_znakow[0] && input_length <= ilosc_znakow[1]){
        input.removeClass("invalid").addClass("valid");
        input.next('.komunikat').text(komunikat_ok).removeClass("blad").addClass("ok");
    }
    else{
        input.removeClass("valid").addClass("invalid");
        input.next('.komunikat').text(komunikat_blad).removeClass("ok").addClass("blad");

    }
});   
}

walidacjaFormularza('#username', [5,20], "Wprowadzono poprawną nazwę użytkownika.", "Nazwa użytkownika musi mieć od 5 do 20 znaków.");
walidacjaFormularza('#password', [5,25], "Wprowadzono poprawne hasło!", "Hasło musi mieć od 5  do 25 znaków.");
walidacjaFormularza('#email', [1,255], "Wprowadzono poprawny email!", "Podany email jest nieprawidłowy.", /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);


$('#zarejestruj').click(function(event){
        var username = $('#username');
        var password = $('#password');
        var email = $('#email');


        if(username.hasClass('valid') && password.hasClass('valid') && email.hasClass('valid')){
            alert("Wprowadzono poprawne dane!");    
        }
        else {
            event.preventDefault();
            alert("Uzupełnij wszystkie pola!"); 
        }
});

});

My DB is connected well through config.php file, the table name is users with columns as: ID, username, password, email. Can anyone see where I have made the mistake?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Damian Doman
  • 522
  • 8
  • 19
  • 1
    ***You shouldn't use [SHA1 password hashes](https://konklone.com/post/why-google-is-hurrying-the-web-to-kill-sha-1)*** or ***[MD5 password hashes](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure)*** and you really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. Make sure you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Nov 23 '16 at 14:50
  • 2
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! ***SQL Injection!*** *It's not just for breakfast any more!* – Jay Blanchard Nov 23 '16 at 14:50
  • Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server? – Jay Blanchard Nov 23 '16 at 14:52
  • Jay Blanchard, thanks for your quick response! So I should rather use password_hash() and password_verify() functions instead of hashing with sha1/md5 right? I will check the response in a moment, i'm currently running it on XAMPP Apache + MySQL giving it a little practice. – Damian Doman Nov 23 '16 at 15:41
  • Also, i have deleted pma database from MYSQL by accident, might it be the reason for the form not working properly? – Damian Doman Nov 23 '16 at 15:50
  • Possibly. You can check your error logs for specific errors. – Jay Blanchard Nov 23 '16 at 15:53
  • 1
    Thank you Jay Blanchard, helped me alot. By the way, your website seems to be great source of knowledge on PHP etc, so im bookmarking it, thanks once more! – Damian Doman Nov 23 '16 at 16:35

0 Answers0