0

This is my Model, I am querying the database, retreving what i need form it, then comparing. Except the query is treating the salt not as a column name, but as a string, which is fine, except it's treating the word salt as the string, not the data from the database. How can i get around this?

function login($username, $password) {          
    $this->db->query("SELECT firstname, username, password, salt FROM table_name WHERE username='$username' AND password = 'sha1(salt.$password'");
    $this->db->limit(1);`

    $query = $this->db->get();

    if($query->num_rows() == 1) {
        return $query->result(); //Data is true
    } else {
        return false; //Data is false
    }
}
Jerodev
  • 32,252
  • 11
  • 87
  • 108

1 Answers1

0

There's a few things at play here. First off you are adding the ' to the hash. Second concatenating in SQL doesn't use the . operator. Try the following instead:

SELECT firstname, username, password, salt 
FROM table_name 
WHERE username='$username' 
    AND password = sha1(CONCAT(salt,'$password'))

Please ensure that both $username and $password are properly sanitised otherwise you are prone to SQL injection. Even better would be to use Prepared Statements. Not sure how this is done in CodeIgniter but info can be seen here: How can I prevent SQL injection in PHP?
Edit: Query bindings will do the job in CodeIgniter https://ellislab.com/codeIgniter/user-guide/database/queries.html

Community
  • 1
  • 1
Jim
  • 22,354
  • 6
  • 52
  • 80
  • Hi, thanks for the reply. I noticed there were some syntax errors in my original code afterwards, that was me in a hurry. I've applied this to the model, but it still seems to be returning an incorrect password, yet if i hardcode in the salt (copied from the database) it works. Still seems to be treating the word 'salt' as a string, not a query. Any clue? Thanks in advance. –  Oct 10 '14 at 09:00
  • @Bakitai Hi, I had quotes around the sha1 in my original answer which shouldn't be there. The revision should be correct. If it's not can you echo out the SQL? – Jim Oct 10 '14 at 09:04
  • It seems to be making progress. I'm now recieving this error.. [Microsoft][ODBC SQL Server Driver][SQL Server]'sha1' is not a recognized built-in function name. Would it be wise to define a variable first and sha this value before entering it into the query? –  Oct 10 '14 at 09:07
  • @Bakitai Your question has the `MySQL` tag so my answer was based on that. SQL server doesn't have a `sha1` function. You may want to look into the [HASHBYTES](http://msdn.microsoft.com/en-us/library/ms174415.aspx) function as an alternative. – Jim Oct 10 '14 at 09:17
  • Ah, dammit, still a rookie with this and was in a hurry. Thanks for the replies, i'll accept the answer for future users on Mysql. Thanks again! –  Oct 10 '14 at 09:19