Problem: In most web based system one of the most commonly used process is user authentication and page access.
This Login function is pretty typical here’s my example: Notice I set a bunch of session variables that I frequently use later in the application to display specific user information (such as dashboards etc.)
<?php /////// LOGIN ///////////////////////////////////////////////////////// function login($username, $password) { global $db; $password = md5($password); //hash password //escape the string $username = $db--->qstr($username,get_magic_quotes_gpc()); $password = $db->qstr($password,get_magic_quotes_gpc()); // check if username is unique can be made stronger using a SQL placeholders. $sql = "SELECT * FROM user WHERE Username=$username AND Passwd = $password"; $result = $db->execute($sql); if (!$result || $db->ErrorNo() != 0 ) { die("invalid result at login DBError No:".$db->ErrorNo() ); return false; } if ($result->RecordCount() >0 ) //get the first record { //setup the session details $_SESSION['user']=$result->fields['username']; $_SESSION['user_firstname']=$result->fields['firstname']; $_SESSION['user_id']=$result->fields['user_id']; $_SESSION['user_type']=$result->fields['usertype']; $_SESSION['permissions']=$result->fields['permissions']; $_SESSION['roles']=$result->fields['roles']; $_SESSION['home_url']=$result->fields['home_url']; //insert into log table return true; } else return false; } ?>
Page Roles: Using roles or groups is a convenient and easy to understand method of controlling user access to a specific page or block within a page. I typically define the roles in the database then hard code them into the page where appropriate. Here’s a function that I use to check if the user is a member of that group.
<?php /** ******************************************************************************************************** * member_of_groups : checks to see if a particular user has is a member of a particualr group * in the tag descriptions usage: member_of_groups('SALES,ACCOUNTING') , comma seperated group names based on the GROUPS table * @returns true if the user IS A MEMBER , otherwise returns FALSE * @params $groups is a comma delimited list of GROUPS in * @version version 1.0 * @author acb <[email protected]> */ function member_of_groups($groups=null) { global $CONFIG; if ( $_SESSION['show_access']==true) //Show a visual indicator that this segment of the page requires authentication { echo "</pre> <div class="lock"> <blockquote><strong> PERMISSIONS : ALLOWED GROUPS</strong> $groups</blockquote> </div> <pre> "; } if ( isset($_SESSION['user_id']) && isset($groups) ) //Check to see that the user is id is set { // $group= explode(",", $groups); // optional way of passing groups //here's we're pulling the groups associated with this user from the database $sql="SELECT count(*) FROM users_groups ug JOIN groups g ON g.gkey = ug.group_id WHERE ug.user_id = ".$_SESSION['user_id']." AND g.title IN ( $groups )"; $is_member=execSQLOne($sql); if ( $is_member >= 1) return true; else return false; } //end if else return false; } ?>
<strong> Login Attempts Alerts</strong>: Another common problem that occurs is invalid users trying to access the system with multiple username/password attempts. The simple scheme below simply keeps track of how many failed attempts occurred within a sort time frame then fires off an email to the system administrator to alert them of a problem.
$result=false; $result = login($username,$password ); //valid user if ($result) { setcookie("app[retries]", 0, time()- 3600 * 4 ); // Sets the cookie username logEvent( $_SESSION['user'] ," <img alt="" src="images/_user_log_in.png" /> <b> ".$_SESSION['username']." </b> LOGGED IN SUCCESSFULLY "); //logs an event redirect($_SESSION['home_uri']); //sends to the default users home page exit(); } else { setcookie("app[retries]", $_SESSION['retires']++, time()- 3600 * 4 ); // Sets the cookie username $_SESSION['msg'].=" Incorrect username or password, try again. Make sure you're typing the password in the correct case. Check the CAPS lock."; logEvent("visitor", FAILED LOG IN Invalid User ".$_REQUEST['username']. " Re-type password : Retry Attempt: ". $_SESSION['retires'] ); //logs an event /* Detect multiple login attempts and send email to warn user and block IP */ if ( $_SESSION['retires'] >= $max_retry_attempts) { $place_holders["{to}"]="[email protected]"; $place_holders["{subject}"]="Multiple Log-in attempts for user account: ".$_REQUEST['username']; $place_holders["{message}"]="It appears a visitor is trying to login with the user account: ".$_REQUEST['username']." and has already RE-TRIED: ". $_SESSION['retires']."times. \n\n Please check the user's Windows account is still active and not locked out, Also check that this is a valid user and not some unauthorized access. Visitor IP address: ".$_SERVER['REMOTE_ADDR']; email_useTemplate($place_holders, $invalid_attempts_template); //Send email alert Alerts : } }