Professional CodeIgniter

(singke) #1

Chapter 6: Creating a Dashboard


185


You ’ re going to remedy that situation very quickly while you ’ re working inside the user admin area. In
fact, it ’ s likely that you ’ re already logged in, so none of this will impede your work in progress. If you ’ re
not already logged in, do so now. That way, none of the following work “ locks you out ” of the system.

The first thing you ’ re going to do is add dohash() to your addUser() and updateUser() functions
in the MAdmins model. The dohash() function uses SHA1 to encrypt a string (really, it ’ s a hash, but the
end result is a scrambled string) and is therefore ideal for obfuscating passwords in database storage.


In Chapter 3 , you set a 32 - character string as your encryption key in config.php. CodeIgniter will use
this key as the salt for dohash(). If you haven ’ t set that key before this point, do so now.

function addUser(){
$data = array(‘username’ = > $_POST[‘username’],
‘email’ = > $_POST[‘email’],
‘status’ = > $_POST[‘status’],
‘password’ = > substr(dohash($_POST[‘password’]),0,16)
);
$this- > db- > insert(‘admins’,$data);
}

function updateUser(){
$data = array(‘username’ = > $_POST[‘username’],
‘email’ = > $_POST[‘email’],
‘status’ = > $_POST[‘status’],
‘password’ = > substr(dohash($_POST[‘password’]),0,16)
);
$this- > db- > where(‘id’,id_clean($_POST[‘id’]));
$this- > db- > update(‘admins’,$data);
}

Now that you have that change in your code, immediately edit the admin user and type kids into the
password field, and click Submit. If you were to view the database record for that user in the database,
you ’ d see that the password field contained a nonsense string of random characters.

Before leaving this topic, you have to do one more thing. You have to add the dohash() function to
verifyUser(). The basic idea is very simple: Take the submitted password from the user and run
dohash() on it. Then compare that value with the value stored in the database. If they match up, you
have a legitimate password!


function verifyUser($u,$pw){
$this- > db- > select(‘id,username’);
$this- > db- > where(‘username’,$u);
$this- > db- > where(‘password’, substr(dohash($pw),0,16) ;
$this- > db- > where(‘status’, ‘active’);
$this- > db- > limit(1);
$Q = $this- > db- > get(‘admins’);

if ($Q- > num_rows() > 0){
$row = $Q- > row_array();
$_SESSION[‘userid’] = $row[‘id’];
Free download pdf