CakePHP Authentication/login with 'Employee' instead of 'User'

user3580711

I am trying to get my login working but I seemed to run into a problem. Could someone please help? I am using the 'Employees' as the user of the database. Below is my code for AppController, EmployeeController, Employee and login.ctp:

App Controller:

class AppController extends Controller {

    public $components = array(
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'employees', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'employees', 'action' => 'login'),
        'authError' => 'You must be logged in to view this page.',
        'loginError' => 'Invalid Username or Password entered, please try again.'

    ));

// only allow the login controllers only
public function beforeFilter() {
    $this->Auth->allow('login');
}
}

Employees Controller:

class EmployeesController extends AppController {
//..other code
/**
 * Components
 *
 * @var array
 */
    //public $components = array('Paginator');
    public $paginate = array(
        'limit' => 25,
        'conditions' => array('status' => '1'),
        'order' => array('Employee.employee_username' => 'asc' ) 
    );

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('login','add'); 

    }



    public function login() {

        //if already logged-in, redirect
        if($this->Session->check('Auth.Employee')){
            $this->redirect(array('action' => 'index'));      
        }

        // if we get the post information, try to authenticate
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
                $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->Session->setFlash(__('Invalid username or password'));
            }
        } 
    }

    public function logout() {
        $this->redirect($this->Auth->logout());
    }

/**
 * index method
 *
 * @return void
 */
    public function index() {
        $this->paginate = array(
            'limit' => 6,
            'order' => array('Employee.employee_username' => 'asc' )
        );
        $employees = $this->paginate('Employee');
        $this->set(compact('employees'));
    }

Employee Model:

class Employee extends AppModel {
//..other code
function isUniqueUsername($check) {

        $username = $this->find(
            'first',
            array(
                'fields' => array(
                    'Employee.id',
                    'Employee.employee_username'
                ),
                'conditions' => array(
                    'Employee.employee_username' => $check['username']
                )
            )
        );

        if(!empty($username)){
            if($this->data[$this->alias]['id'] == $username['Employee']['id']){
                return true; 
            }else{
                return false; 
            }
        }else{
            return true; 
        }
    }

    /**
     * Before isUniqueEmail
     * @param array $options
     * @return boolean
     */
    function isUniqueEmail($check) {

        $email = $this->find(
            'first',
            array(
                'fields' => array(
                    'Employee.id'
                ),
                'conditions' => array(
                    'Employee.employee_email' => $check['email']
                )
            )
        );

        if(!empty($email)){
            if($this->data[$this->alias]['id'] == $email['Employee']['id']){
                return true; 
            }else{
                return false; 
            }
        }else{
            return true; 
        }
    }

    public function alphaNumericDashUnderscore($check) {
        // $data array is passed using the form field name as the key
        // have to extract the value to make the function generic
        $value = array_values($check);
        $value = $value[0];

        return preg_match('/^[a-zA-Z0-9_ \-]*$/', $value);
    }

    public function equaltofield($check,$otherfield) 
    { 
        //get name of field 
        $fname = ''; 
        foreach ($check as $key => $value){ 
            $fname = $key; 
            break; 
        } 
        return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname]; 
    } 

    /**
     * Before Save
     * @param array $options
     * @return boolean
     */
     public function beforeSave($options = array()) {
        if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = $passwordHasher->hash(
            $this->data[$this->alias]['password']
        );
    }
    // if we get a new password, hash it

        if (isset($this->data[$this->alias]['password_update'])) {

            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password_update']);

        }
    // fallback to our parent

        return parent::beforeSave($options);
    //return true;
    }

}

Login page:

<div class=“employees form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('Employee'); ?>
    <fieldset>
        <legend>
            <?php echo __('Please enter your username and password'); ?>
        </legend>
        <?php echo $this->Form->input('username');
        echo $this->Form->input('password');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
Simon

1.Adapt the config of your Auth component regarding userModel, fields and passwordHasher:

public $components = array(
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'Employee', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'Employee', 'action' => 'login'),
        'authError' => 'You must be logged in to view this page.',
        'loginError' => 'Invalid Username or Password entered, please try again.',
        'authenticate' => array(
            'Form' => array(
            'fields' => array('username' => 'username', 'password' => 'password'),
            'userModel'=>'Employee',
            'passwordHasher' => 'name of your password hasher'
            ))
    ));

2.Regarding CakePHP´s code convetion rename your controller to EmployeeController

3.In your Employee model instead your isUniqueUsername and isUniqueEmail you better use validation rule isUnique

4.Use same password hasher for creating password and update password

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Spring Security user authentication against customers and employee

how to make an "employee" "user" by default in odoo 9

Lost information after set association between user an employee in odoo 12

Hybris UAC: Employee with user access rights to create Employee cannot create an Employee

User Control instead of Buttons

Jpa createSQLQuery returns List<Object> instead of List<Employee>

CakePHP user control

Mocking an authed user in CakePHP

CakePHP: sending latest user id to admin's create_employee view

Conditional user confirmation on delete cakePHP

Django User model extended for employee. How to access the employee attribute in change_form of model admin?

Using HashSet with a user class Employee

cakephp instead of user_id how do I get for instance username in the view

How not to expire user session cakephp

CakePHP Login redirect admin/user

Add user's secondary values (Employee Details) such as Title to Google Directory

Select hr.employee by user_id in odoo 7

Display username instead of user_id in CakePHP

Devise user exists error, passing data from employee to user

Querying Active Directory using C# for user email by employee ID

Fetching Employee ID field of logged user using Azure AD

How can I use Softdeletes in the models of Employee and User?

Laravel - How to get company detail based on employee and logged user

Employee model Linked to Django User

Django Signals for User Profile (Customer and Employee)

Django-single user with multiple employee account for each organization flow

How to assign a user to an employee in Django

Assign employee to user

C# Reflection: how to get List<Employee> instead of System.Collections.Generic.List`1[Employee]?