Skip to content

Instantly share code, notes, and snippets.

@brandoncordell
Created January 28, 2011 06:54
Show Gist options
  • Save brandoncordell/799934 to your computer and use it in GitHub Desktop.
Save brandoncordell/799934 to your computer and use it in GitHub Desktop.
dZero Auth - CodeIgniter library
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* dZero authentication library
*
* @package dZero Auth Library
* @category authentication
* @author Daniel Nolan (daniel.nolan@dZerodesign.com) & Brandon Cordell (brandon.cordell@dZerodesign.com)
* @copyright Copyright (c) 2009 dZero Web Design & Development.
* @link http://dzerodesign.com
* @version 1.0
*
*/
class Dzero_auth {
function Dzero_auth() {
$this->CI =& get_instance();
}
/**
* Loads the login form
*
* @access public
* @param none
* @return login form
*/
function login(){
force_ssl();
$data['title'] = 'Login';
$data['main_content'] = $this->CI->config->item('forms').'login_form';
$this->CI->load->view($this->CI->config->item('container'), $data);
}
function validate_credentials() {
$this->CI->load->library('form_validation');
$this->CI->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->CI->form_validation->set_rules('username', 'Username', 'trim|required');
if($this->CI->config->item('enable_recaptcha') && $this->CI->config->item('use_captcha_login'))
$this->CI->form_validation->set_rules('recaptcha_challenge_field', 'reCaptcha', 'required|recaptcha_matches');
$this->CI->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->CI->form_validation->run() == FALSE) {
$data['title'] = 'Login';
$data['main_content'] = $this->CI->config->item('forms').'login_form';
$this->CI->load->view($this->CI->config->item('container'), $data);
}
else {
$this->CI->load->model('user_model');
$query = $this->CI->user_model->validate();
if($query) {
$data = $this->CI->user_model->get_user_data();
if($data->num_rows() == 1)
$row = $data->row();
$user_data = array(
'id' => $row->id,
'username' => $row->username,
'is_logged_in' => true,
'role' => $row->role,
'email' => $row->email
);
$this->CI->session->set_userdata($user_data);
if($user_data['role'] == 'user') {
redirect($this->CI->config->item('user_login_redirect'), 'location');
}
elseif($user_data['role'] == 'admin' || $user_data['role'] == 'superadmin') {
redirect($this->CI->config->item('admin_login_redirect'), 'location');
}
}
else
{
$role = '';
$this->deny_access($role);
}
}
}
function is_super_admin() {
if ($this->CI->session) {
$_username = $this->CI->session->userdata('username');
$_role = $this->CI->session->userdata('role');
if ($_username != false AND $_role != false AND $_role=='superadmin')
return true;
}
return false;
}
function is_admin() {
if ($this->CI->session) {
$_username = $this->CI->session->userdata('username');
$_role = $this->CI->session->userdata('role');
if ($_username != false && $_role != false AND ($_role == 'admin' OR $_role == 'superadmin'))
//returns the user id
return true;
}
// if user_id not activated or not existent
return false;
}
function is_valid_user() {
if ($this->CI->session) {
if ($this->get_user_name() != '')
return true;
}
// if user not activated or not existent
return false;
}
function check($_lock_to_role=null, $_only=null) {
// check who did the request and build role hierarchy
$_who_is = $this->CI->session->userdata('role');
// if we have a role stored in DB session for this user
if ($this->CI->session AND !empty($_who_is))
{
// gets the locked role hierarchy value
$_hierarchy = $this->CI->config->item('roles');
// if we didn't specify to who we will reserve the action
// let's restrict it to registered users
if ($_lock_to_role==null)
{
$_lock_to_role='user';
}
// let's see who did we reserve the area to
$_lock_hierarchy = $_hierarchy[$_lock_to_role];
// let's see who requested to access this area
$_request_hierarchy = $_hierarchy[$_who_is];
// let's see if we decided to restrict access ONLY to a given category
switch ($_only)
{
case true:
$_request_hierarchy == $_lock_hierarchy ? $_condition = true : $_condition = false;
break;
// only false or not specified
default:
$_request_hierarchy <= $_lock_hierarchy ? $_condition = true : $_condition = false;
break;
}
// if who did the request doesn't have enough credentials
if ($_condition==false)
{
$this->deny_access($_who_is);
}
}
// it means it is a guest because it has no role stored in DB_session
else
{
$this->deny_access($_who_is);
}
}
function belongs_to_group($_group=null, $_only=null) {
if ($this->CI->session) {
$_username = $this->CI->session->userdata('user_name');
$_who_is = $this->CI->session->userdata('role');
if ($_username != false AND $_who_is != false) {
// if we didn't specify who we are looking for
// let's look if the request comes from an 'user'
if ($_group == null)
{
$_group='user';
}
$_groups = explode(",", $_group);
$_group = array();
// eliminate possible whitespaces at the beginning and end
// of groups names passed as parameters to this function
foreach($_groups as $_grp)
{
$_group[] = trim($_grp);
}
// let's see if we decided to check if
// it belongs ONLY to a given group
switch ($_only)
{
// $_only = true
case true: //we decided to check if it belongs ONLY to a given group
in_array($_who_is, $_group) ? $_condition = true : $_condition = false;
break;
// $_only false or not specified
// we decided to check if it belongs AT LEAST to a given group
default:
// gets the locked role hierarchy value
$_hierarchy = $this->CI->config->item('roles');
// let's see who we are looking for
foreach ($_group as $value)
{
$_group_hierarchy []= $_hierarchy[$value];
}
$_group_hierarchy = max($_group_hierarchy);
// let's see who accessed. we need to get the
// role-hierarchy-value of the visitor that did the request
$_who_hierarchy = $_hierarchy[$_who_is];
$_who_hierarchy <= $_group_hierarchy ? $_condition = true : $_condition = false;
break;
}
// if who did the request doesn't have enough credentials
if ($_condition==true)
{
return TRUE;
}
}
}
// if condition==false, session turned off or user not found (namely not logged in) in ci_session
return false;
}
function get_user_name()
{
if ($this->CI->session)
// returns username string of currently logged in user
return $this->CI->session->userdata('username');
// returns empty string if user not logged in
return '';
}
function register() {
$data['title'] = 'Register';
$data['main_content'] = $this->CI->config->item('forms').'register_form';
$this->CI->load->view($this->CI->config->item('container'), $data);
}
function create_user() {
$this->CI->load->library('form_validation');
$this->CI->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->CI->form_validation->set_rules('firstname', 'First', 'trim|required|maxlength[20]');
$this->CI->form_validation->set_rules('lastname', 'Last', 'trim|required|maxlength[20]');
$this->CI->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|check_email');
$this->CI->form_validation->set_rules('username', 'Valid username rules', 'trim|required|minlength[6]|maxlength[16]|check_username');
$this->CI->form_validation->set_rules('password', 'Valid username rules', 'trim|required|minlength[5]|maxlength[15]');
$this->CI->form_validation->set_rules('password2', 'Passwords must match!', 'matches[password]|trim|required|minlength[5]|maxlength[15]');
if($this->CI->config->item('enable_recaptcha') && $this->CI->config->item('use_captcha_login'))
$this->CI->form_validation->set_rules('recaptcha_challenge_field', 'reCaptcha', 'required|recaptcha_matches');
if ($this->CI->form_validation->run() == FALSE) {
$data['title'] = 'Register';
$data['main_content'] = $this->CI->config->item('forms').'register_form';
$this->CI->load->view($this->CI->config->item('container'), $data);
}
else {
$user = array('username' => $this->CI->input->post('username'),
'password' => $this->_encode($this->CI->input->post('password')),
'email' => $this->CI->input->post('email'),
'role' => 'user');
$this->CI->load->model('user_model');
$id = $this->CI->user_model->new_user($user);
$user_profile = array('id' => $id,
'firstname' => $this->CI->input->post('firstname'),
'lastname' => $this->CI->input->post('lastname'));
$this->CI->load->model('profile_model');
$this->CI->profile_model->new_user($user_profile);
echo 'success!!';
}
}
function deny_access($role) {
// if visitor is a GUEST
if ($role == '') {
// First, we have to store the requested page in order
// to serve it back to the visitor after a successful login.
$this->CI->session->set_flashdata('requested_page',$this->CI->uri->uri_string());
// Then we redirect to the login form with a 'access denied'
// message. Maybe if the visitor can log in,
// he'll get some more permissions...
$msg = $this->CI->lang->line('no_credentials_guest');
$this->CI->session->set_flashdata('error',$msg);
redirect('site/login', 'location');
}
// else if visitor is a USER
else {
$msg = $this->CI->lang->line('no_credentials_user');
$this->CI->session->set_flashdata('error',$msg);
// if visitor came to this site with an http_referer
if (isset($_SERVER['HTTP_REFERER']))
{
$referer = $_SERVER['HTTP_REFERER'];
if (preg_match("|^".base_url()."|", $referer) == 0)
{
// if http_referer is from an external site,
// users are taken to the page defined in the config file
redirect($this->CI->config->item('FAL_denied_from_ext_location'));
}
else
{
// if we came from our website, just go to this page back
// but maybe we arrived here because of the
// 'redirect to requested page', so in order not to
$this->CI->session->keep_flashdata('requested_page');
header("location:".$_SERVER['HTTP_REFERER']);
exit();
}
}
// if visitor did not come to this site with an http_referer,
// redirect to the page defined in the config file too
else
{
//@todo add this to config file currently broken!
redirect($this->CI->config->item('FAL_denied_from_ext_location'), 'location');
}
}
}
function logout() {
$this->CI->session->sess_destroy();
redirect('site/login');
}
// --------------------------------------------------------------------
/**
* Returns the currently logged in user's property from the session.
*
* A property is what he gave when registering (like 'email'),
* or something calculated server-side (like 'last_visit').
* Returns an empty string if no user is logged in.
*
* Uses Class db_session method "userdata".
*
* @param string $prop can be 'id', 'user_name', 'country_id', 'email', 'role', 'last_visit', 'created', 'modified'
* @return prop string of currently logged in user
* @return empty string if user not logged in or prop unknown
*/
function get_user_property($prop)
{
if ($this->CI->session)
// returns property string of currently logged in user
return $this->CI->session->userdata($prop);
// returns empty string if user not logged in
return '';
}
// --------------------------------------------------------------------
/**
* Returns the property $prop of the user identified by $id from the database.
*
* A property is what he gave when registering (like 'email'),
* or something calculated server-side (like 'last_visit').
*
* @param integer $id the id of the user you are interested in
* @param string $prop can be 'id', 'user_name', 'country_id', 'email', 'role', 'last_visit', 'created', 'modified'
* @return prop string of the user identified by $id
* @return 'unknown user' if user unknown
* @return empty string if prop unknow
*/
function get_user_property_from_id($id, $prop) {
$query = $this->CI->user_model->get_user_by_id($id);
if ($query->num_rows() == 1) {
$row = $query->row();
if (isset($row->{$prop})) return $row->{$prop};
else return '';
}
else {
return $this->CI->lang->line('unknown_user');
}
}
function _encode($password) {
$majorsalt=null;
// if encryption key is set let's use it
if ($this->CI->config->item('encryption_key')!='') {
// concatenates the encryption key and the password
$_password = $this->CI->config->item('encryption_key').$password;
}
else {$_password=$password;}
$_pass = str_split($_password);
// encrypts every single letter of the password
foreach ($_pass as $_hashpass) {
$majorsalt .= md5($_hashpass);
}
// encrypts the string combinations of every single encrypted letter
// and finally returns the encrypted password
return $password=md5($majorsalt);
}
function forgot_pass_step_one() {
$this->CI->load->library('form_validation');
$this->CI->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->CI->form_validation->set_rules('username', 'Username', 'trim|required|maxlength[20]');
$this->CI->form_validation->set_rules('email', 'Email', 'trim|required|maxlength[20]|valid_email');
if ($this->CI->form_validation->run() == FALSE) {
$data['title'] = 'Forgot Password';
$data['main_content'] = $this->CI->config->item('forms').'forgot_password_1';
$this->CI->load->view($this->CI->config->item('container'), $data);
} else {
$this->CI->load->model('password_recovery_model');
$user = $this->CI->input->post('username');
$email = $this->CI->input->post('email');
$query = $this->CI->password_recovery_model->get_user_id($user, $email);
if(!$query) {
$this->CI->session->set_flashdata('error', 'Username/Email did not match our records');
redirect('/site/forgot_password/stepOne', 'location');
} else {
$user = $this->CI->session->userdata('fp_username');
$id = $this->CI->session->userdata('fp_user_id');
if(isset($user) || !empty($user) || isset($id) || !empty($id)) {
$this->CI->session->unset_userdata('fp_username');
$this->CI->session->unset_userdata('fp_user_id');
}
foreach($query as $row) {
$this->CI->session->set_userdata('fp_username', $row['username']);
$this->CI->session->set_userdata('fp_user_id', $row['id']);
}
redirect('/site/forgot_password/stepTwo', 'location');
}
}
}
function forgot_pass_step_two() {
/* Make sure that you have authenticated USER! */
$user = $this->CI->session->userdata('fp_username');
$id = $this->CI->session->userdata('fp_user_id');
if(!isset($user) || empty($user) || !isset($id) || empty($id))
{
//GTFO!!
redirect('/', 'location');
}
$this->CI->load->model('password_recovery_model');
$first_query = $this->CI->password_recovery_model->get_security_questions($id);
if(!$first_query)
{
echo 'something went wrong...';
return;
}
$this->CI->load->library('form_validation');
$this->CI->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->CI->form_validation->set_rules('question1', 'Question', 'trim|required');
$this->CI->form_validation->set_rules('question2', 'Question', 'trim|required');
$this->CI->form_validation->set_rules('question3', 'Question', 'trim|required');
if ($this->CI->form_validation->run() == FALSE)
{
$data['results'] = $first_query;
$data['title'] = 'Answer Security Questions';
$data['main_content'] = $this->CI->config->item('forms').'forgot_password_2';
$this->CI->load->view($this->CI->config->item('container'), $data);
}
else
{
$query = $this->CI->password_recovery_model->get_security_answers($id);
if(!$query)
{
echo 'something went wrong... ';
return;
}
else
{
$error = FALSE;
foreach($query as $key => $value)
{
$answers[] = strtolower($value['answer']);
}
$question_one = strtolower($this->CI->input->post('question1'));
$question_two = strtolower($this->CI->input->post('question2'));
$question_three = strtolower($this->CI->input->post('question3'));
if(!in_array($question_one, $answers))
{
$error = TRUE;
$error_one = 'Wrong security answer';
}
elseif (!in_array($question_two, $answers))
{
$error = TRUE;
$error_two = 'Wrong security answer';
} elseif (!in_array($question_three, $answers))
{
$error = TRUE;
$error_three = 'Wrong security answer';
}
if($error)
{
$data['results'] = $first_query;
if(isset($error_one))
$data['sec_error']['error1'] = $error_one;
if(isset($error_two))
$data['sec_error']['error2'] = $error_two;
if(isset($error_three))
$data['sec_error']['erro3'] = $error_three;
$data['title'] = 'Answer Security Questions';
$data['main_content'] = $this->CI->config->item('forms').'forgot_password_2';
$this->CI->load->view($this->CI->config->item('container'), $data);
}
$auth = $this->CI->session->userdata('auth');
if(isset($auth) || !empty($auth))
{
$this->CI->session->unset_userdata('auth');
}
$this->CI->session->set_userdata('auth', 'TRUE');
redirect('/site/forgot_password/stepThree', 'location');
}
}
}
function forgot_pass_step_three() {
/* Make sure that you have authenticated USER! */
$user = $this->CI->session->userdata('fp_username');
$id = $this->CI->session->userdata('fp_user_id');
$auth = $this->CI->session->userdata('auth');
if(!isset($user) || empty($user) || !isset($id) || empty($id))
{
//GTFO!!
redirect('/', 'location');
}
elseif (!isset($auth) || empty($auth))
{
//GTFO!!
redirect('/', 'location');
}
$this->CI->load->library('form_validation');
$this->CI->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->CI->form_validation->set_rules('password', 'Password', 'trim|required|maxlength[20]');
$this->CI->form_validation->set_rules('password2', 'Password', 'trim|required|maxlength[20]|match[password]');
if ($this->CI->form_validation->run() == FALSE) {
$data['title'] = 'Reset Password';
$data['main_content'] = $this->CI->config->item('forms').'forgot_password_3';
$this->CI->load->view($this->CI->config->item('container'), $data);
} else {
$this->CI->load->model('password_recovery_model');
$query = $this->CI->password_recovery_model->reset_password($user, $this->CI->input->post('password'));
if(!$query) {
echo 'error!!';
return;
}
$data = array('fp_username' => '',
'fp_user_id' => '',
'auth' => '');
$this->CI->session->unset_userdata($data);
}
}
}
/* End of file dzero_auth.php */
/* Location: ./application/libraries/dzero_auth.php */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment