Auth Component für alle Controller

44 views
Skip to first unread message

Andreas Gisler

unread,
May 13, 2013, 1:37:52 PM5/13/13
to cakep...@googlegroups.com
Hallo zusammen

Ich bin neu im CakePHP. Ich konnte nun mithilfe eines Tutorials ein Login erstellen. Jedoch weiss ich nun nicht wie ich dieses Login für alle Pages verwenden kann. Kann mir Jemand hier weiterhelfen? 
Unten findet ihr diverse Files. Ich es eigentlich so hinbekommen, dass egal auf welcher Seite man landet zuerst gecheckt wird, ob man eingeloggt ist. Falls dies nicht der Fall ist, ein Login Screen erscheint. 
Vielen Dank

login.ctp:
<h2>Login</h2>

<?php

echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');

?>

userscontroller.php:
<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController {

    
        public $name = 'Users';
        
        public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('add');
        }
        
        public function isAuthorized($user) {
            if ($user['role'] == 'admin') {
                return true;
            }
            if (in_array($this->action, array('edit', 'delete'))) {
                if ($user['id'] != $this->request->params['pass'][0]) {
                    return false;
                }
            }
            return true;
        }
/**
 * index method
 *
 * @return void
 */
        public function login() {
            if ($this->request->is('post')) {
                if ($this->Auth->login()) {
                    $this->redirect($this->Auth->redirect());
                } else {
                    $this->Session->setFlash('Ihre Username/Passwort Kombination war falsch');
                }
            }
        }
    
        public function logout() {
            $this->redirect($this->Auth->logout());
        }
        
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
public function view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
}

/**
 * add method
 *
 * @return void
 */
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}

/**
 * admin_index method
 *
 * @return void
 */
public function admin_index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
public function admin_view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
}

/**
 * admin_add method
 *
 * @return void
 */
public function admin_add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
public function admin_edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
public function admin_delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
}

appcontroller.php:
<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package app.Controller
 */
class AppController extends Controller {
public $components = array(
            'Session',
            'Auth'=>array(
                'loginRedirect'=>array('controller'=>'users', 'action'=>'index'),
                'logoutRedirect'=>array('controller'=>'users', 'action'=>'index'),
                'authError'=>"Sie können sich nicht anmelden",
                'authorize'=>array('Controller')
            )
        );
        
        public function isAuthorized($user) {
            return true;
        }
        
        //Zugriff für non loged in users
        public function beforeFilter() {
            $this->Auth->allow('index', 'view');
            $this->set('logged_in', $this->Auth->loggedIn());
            $this->set('current_user', $this->Auth->user());
        }
}

users.php:
<?php
App::uses('AppModel', 'Model');
/**
 * User Model
 *
 */
class User extends AppModel {

/**
 * Display field
 *
 * @var string
 */
        public $name = 'User';
public $displayField = 'name';
        
        public $validate = array(
            'name'=>array(
                'Bitte tippen Sie Ihren Namen ein.'=>array(
                    'rule'=>'notEmpty',
                    'message'=>'Bitte tippen Sie Ihren Namen ein.'
                )
            ),
            'username'=>array(
                'Der Benutzername muss zwischen 5 und 15 Zeichen besitzen.'=>array(
                    'rule'=>array('between', 5, 15),
                    'message'=>'Der Benutzername muss zwischen 5 und 15 Zeichen besitzen.'
                ),
                'Dieser Benutzername ist schon besetzt.'=>array(
                    'rule'=>'isUnique',
                    'message'=>'Dieser Benutzername ist schon besetzt.'
                )
            ),
            'email'=>array(
                'Bitte eine gültige E-Mail Adresse angeben.'=>array(
                    'rule'=>array('email'),
                    'message'=>'Bitte eine gültige E-Mail Adresse angeben.'
                )
            ),
            'password'=>array(
                'Not empty'=>array(
                    'rule'=>'notEmpty',
                    'message'=>'Bitte Passwort eintippen.'
                ),
                'Match passwords'=>array(
                    'rule'=>'matchPasswords',
                    'message'=>'Ihr Passwort stimmt nicht überein.'
                )
            ),
            'password_confirmation'=>array(
                'Not empty'=>array(
                    'rule'=>'notEmpty',
                    'message'=>'Bitte bestätigen Sie Ihr Passwort.'
                )
            )
        );
        
        public function matchPasswords($data) {
            if ($data['password'] == $this->data['User']['password_confirmation']) {
                return true;
            }
            $this->invalidate('password_confirmation', 'Ihr Passwort stimmt nicht überein.');
            return false;
        }
        
        public function beforeSave($options = array()) {
            if (isset($this->data['User']['password'])) {
                $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
            }
            return true;
        }

}

Mathias Ratheike

unread,
May 15, 2013, 6:30:32 AM5/15/13
to cakep...@googlegroups.com
Hallo Andreas,

damit ich das richtig verstehe:
Du m�chtest alle Seiten deiner Webseite von einem Login abh�ngig machen,
abgesehen von dem Login und der Registrierung selbst, richtig?

AppController:
public function beforeFilter() {
$this->Auth->deny(); // F�r alle Seiten der Webseite wird ein Login
ben�tigt
}

UserController:
public function beforeFilter() {
$this->Auth->allow('login','register'); // login und register-Action im
UserController auch ohne Login abarbeiten
parent::beforeFilter(); // Funktion beforeFilter des AppController mit
einbeziehen
}

Gru�
Mathias

Am 13.05.2013 19:37, schrieb Andreas Gisler:
> Hallo zusammen
>
> Ich bin neu im CakePHP. Ich konnte nun mithilfe eines Tutorials ein
> Login erstellen. Jedoch weiss ich nun nicht wie ich dieses Login f�r
> alle Pages verwenden kann. Kann mir Jemand hier weiterhelfen?
> Unten findet ihr diverse Files. Ich es eigentlich so hinbekommen, dass
> egal auf welcher Seite man landet zuerst gecheckt wird, ob man
> eingeloggt ist. Falls dies nicht der Fall ist, ein Login Screen erscheint.
> Vielen Dank
>
> */_login.ctp:_/*
> <h2>Login</h2>
>
> <?php
>
> echo $this->Form->create();
> echo $this->Form->input('username');
> echo $this->Form->input('password');
> echo $this->Form->end('Login');
>
> ?>
>
> *_userscontroller.php:_*
> *_appcontroller.php:_*
> * @linkhttp://book.cakephp.org/2.0/en/controllers.html#the-app-controller
> */
> class AppController extends Controller {
> public $components = array(
> 'Session',
> 'Auth'=>array(
> 'loginRedirect'=>array('controller'=>'users',
> 'action'=>'index'),
> 'logoutRedirect'=>array('controller'=>'users',
> 'action'=>'index'),
> 'authError'=>"Sie k�nnen sich nicht anmelden",
> 'authorize'=>array('Controller')
> )
> );
> public function isAuthorized($user) {
> return true;
> }
> //Zugriff f�r non loged in users
> public function beforeFilter() {
> $this->Auth->allow('index', 'view');
> $this->set('logged_in', $this->Auth->loggedIn());
> $this->set('current_user', $this->Auth->user());
> }
> }
>
> *_users.php:_*
> 'Bitte eine g�ltige E-Mail Adresse angeben.'=>array(
> 'rule'=>array('email'),
> 'message'=>'Bitte eine g�ltige E-Mail Adresse angeben.'
> )
> ),
> 'password'=>array(
> 'Not empty'=>array(
> 'rule'=>'notEmpty',
> 'message'=>'Bitte Passwort eintippen.'
> ),
> 'Match passwords'=>array(
> 'rule'=>'matchPasswords',
> 'message'=>'Ihr Passwort stimmt nicht �berein.'
> )
> ),
> 'password_confirmation'=>array(
> 'Not empty'=>array(
> 'rule'=>'notEmpty',
> 'message'=>'Bitte best�tigen Sie Ihr Passwort.'
> )
> )
> );
> public function matchPasswords($data) {
> if ($data['password'] ==
> $this->data['User']['password_confirmation']) {
> return true;
> }
> $this->invalidate('password_confirmation', 'Ihr Passwort
> stimmt nicht �berein.');
> return false;
> }
> public function beforeSave($options = array()) {
> if (isset($this->data['User']['password'])) {
> $this->data['User']['password'] =
> AuthComponent::password($this->data['User']['password']);
> }
> return true;
> }
>
> }
>
> --
> --
> Bitte bei Fragen immer auch die aktuell verwendete cakePHP Version
> angeben und
> wenn m�glich auch das verwendete Betriebssystem und die PHP Version. Danke.
> Sie erhalten diese Nachricht, weil Sie Mitglied sind von Google
> Groups-Gruppe "CakePHP-de f�r deutsche CakePHP Entwickler".
> F�r das Erstellen von Beitr�gen in dieser Gruppe senden Sie eine E-Mail
> an cakep...@googlegroups.com
> Um sich von dieser Gruppe abzumelden, senden Sie eine E-Mail an
> cakephp-de-...@googlegroups.com
> Weitere Optionen finden Sie in dieser Gruppe unter
> http://groups.google.com/group/cakephp-de?hl=de
> ---
> Sie haben diese Nachricht erhalten, weil Sie der Google Groups-Gruppe
> CakePHP-de f�r deutsche CakePHP Entwickler beigetreten sind.
> Um Ihr Abonnement f�r diese Gruppe zu beenden und keine E-Mails mehr von
> dieser Gruppe zu erhalten, senden Sie eine Email an
> cakephp-de+...@googlegroups.com.
> Weitere Optionen: https://groups.google.com/groups/opt_out
>
>

--
------------------------------------------
Ihr Partner in Sachen Web-Programmierung:
Mathias Ratheike

MRNetworks
http://www.mrnetworks.de/

Kontakt:
Tel: +49 151 222 922 50
Skype: mratheike
Xing: https://www.xing.com/profile/Mathias_Ratheike
Reply all
Reply to author
Forward
0 new messages