UsersController.php 8.96 KB
<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;

/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 */
class UsersController extends AppController
{

    // "l'" utilisateur (et non pas "le utilisateur")
    protected function getArticle()
    {
        return "L'";
    }

    // 1) AVANT connexion
    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->LdapAuth->allow([
            'logout'
        ]);
    }

    // 2) APRES connexion
    /**
     * Give authorization for users
     * 
     * @param
     *            $user
     * @return boolean
     */
    public function isAuthorized($user)
    {
        // $configuration = $this->confLabinvent;
        // $role = $this->Users->find()->where(['username' => $user[$configuration->authentificationType_ldap][0]])->first()['role'];
        // $action = $this->request->getAttribute('params')['action'];
        $action = $this->getActionPassed();
        
        // Actions de CE controleur accessibles à tous les profils
        // if (in_array($action, ['index', 'view', 'getLdapLogin', 'getLdapEmail','indexRecap'])) return true;
        if (in_array($action, [
            'getLdapLogin',
            'getLdapEmail',
            'indexRecap'
        ]))
            return true;
        
        // Inutile car déjà dit dans parent::isAuthorized()
        // Super-Admin peut accéder à toutes les actions de CE controleur
        // if ($role == 'Super Administrateur') return true;
        
        // Par défaut refuser
        // return false;
        return parent::isAuthorized($user);
    }

    public function login()
    {
        if ($this->request->is('post')) {
            
            $user = $this->LdapAuth->connection();
            // debug($user);
            
            if ($user != FALSE) {
                $this->LdapAuth->setUser($user);
                
                return $this->redirect($this->LdapAuth->redirectUrl());
            }
            $this->Flash->error(__('Login ou mot de passe invalide, réessayez'));
        }
    }

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

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $this->paginate = [
            'contain' => [
                'GroupesMetiers',
                'GroupesThematiques',
                'SurCategories'
            ]
        ];
        $users = $this->paginate($this->Users);
        
        // Affichage informations disponible pour l'utilisateur connecté
        $this->myDebug($this->LdapAuth->user());
        
        $this->set('nbUsers', $this->Users->find('all')
            ->count());
        
        $this->set(compact('users'));
        $this->set('_serialize', [
            'users'
        ]);
    }

    /**
     * Index_recap method
     *
     * @return \Cake\Network\Response|null
     */
    public function indexRecap()
    {
        $this->paginate = [
            'contain' => [
                'GroupesMetiers',
                'GroupesThematiques',
                'SurCategories'
            ]
        ];
        $users = $this->paginate($this->Users->find('all', [
            'conditions' => [
                'role =' => 'Responsable'
            ]
        ]));
        
        // Affichage informations disponible pour l'utilisateur connecté
        $this->myDebug($this->LdapAuth->user());
        
        $this->set('nbUsers', $this->Users->find('all', [
            'conditions' => [
                'role =' => 'Responsable'
            ]
        ])
            ->count());
        
        $this->set(compact('users'));
        $this->set('_serialize', [
            'users'
        ]);
    }

    /**
     * View method
     *
     * @param string|null $id
     *            User id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => [
                'GroupesMetiers',
                'GroupesThematiques',
                'SurCategories'
            ]
        ]);
        
        $this->set('user', $user);
        $this->set('_serialize', [
            'user'
        ]);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('L\'utilisateur a bien été ajouté.'));
                return $this->redirect([
                    'action' => 'view',
                    $user->id
                ]);
            } else {
                $this->Flash->error(__('L\'utilisateur n\'a pas pu être ajouté.'));
            }
        }
        $groupesMetiers = $this->Users->GroupesMetiers->find('list', [
            'keyField' => 'id',
            'valueField' => 'nom'
        ]);
        $groupesThematiques = $this->Users->GroupesThematiques->find('list', [
            'keyField' => 'id',
            'valueField' => 'nom'
        ]);
        $sur_categorie = $this->Users->SurCategories->find('list', [
            'keyField' => 'id',
            'valueField' => 'nom'
        ]);
        $users = TableRegistry::get('LdapConnections')->getListUsers();
        // tri des utilisateurs par nom
        sort($users);
        $utilisateurs = [];
        for ($i = 0; $i < sizeof($users); $i ++) {
            $utilisateurs[$users[$i]] = $users[$i];
        }
        
        $this->set(compact('user', 'groupesMetiers', 'utilisateurs', 'groupesThematiques', 'sur_categorie'));
        $this->set('_serialize', [
            'user'
        ]);
    }

    /**
     * Edit method
     *
     * @param string|null $id
     *            User id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
        if ($this->request->is([
            'patch',
            'post',
            'put'
        ])) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('L\'utilisateur a bien été édité.'));
                return $this->redirect([
                    'action' => 'view',
                    $id
                ]);
            } else {
                $this->Flash->error(__('L\'utilisateur n\'a pas pu être édité.'));
            }
        }
        $groupesMetiers = $this->Users->GroupesMetiers->find('list', [
            'keyField' => 'id',
            'valueField' => 'nom'
        ]);
        $groupesThematiques = $this->Users->GroupesThematiques->find('list', [
            'keyField' => 'id',
            'valueField' => 'nom'
        ]);
        $sur_categorie = $this->Users->SurCategories->find('list', [
            'keyField' => 'id',
            'valueField' => 'nom'
        ]);
        $this->set(compact('user', 'groupesMetiers', 'groupesThematiques', 'sur_categorie'));
        $this->set('_serialize', [
            'user'
        ]);
    }

    /**
     * Delete method
     *
     * @param string|null $id
     *            User id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod([
            'post',
            'delete'
        ]);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__('L\'utilisateur a bien été supprimé.'));
        } else {
            $this->Flash->error(__('L\'utilisateur n\'a pas pu être supprimé.'));
        }
        return $this->redirect([
            'action' => 'index'
        ]);
    }

    // called from Javascript (Ajax)
    public function getLdapLogin($userName)
    {
        $u = TableRegistry::get('LdapConnections')->getListLoginUsers();
        
        if ($u[$userName] !== null) {
            $this->set('login', $u[$userName]);
        }
        
        $this->viewBuilder()->layout = 'ajax';
    }

    // called from Javascript (Ajax)
    public function getLdapEmail($userName)
    {
        $u = TableRegistry::get('LdapConnections')->getListEmailUsers();
        
        if ($u[$userName] !== null) {
            $this->set('email', $u[$userName]);
        } else {
            $this->set('email', ' ');
        }
        
        $this->viewBuilder()->layout = 'ajax';
    }
}