Can't get Auth login to work with CakePHP 2.0 - forms

I'm trying to get a simple login form to work using CakePHP 2.0... just Auth, no ACLs for now.
I'm able to see the form and enter the email and password as they are in the database, but I just get returned to the form and the flash error message is displayed. Here is my code:
AppController:
class AppController extends Controller
{
function beforeFilter()
{
$this->Auth->userModel = 'Users';
$this->Auth->fields = array('username' => 'email', 'password' => 'password'); //have to put both, even if we're just changing one
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'hotels', 'action' => 'dashboard');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
}
}
login.ctp:
<?php
echo $this->Form->create('User', array('action' => 'login'));
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
UsersController:
class UsersController extends AppController
{
var $name = 'Users';
var $helpers = array('Html','Form');
var $components = array('Auth','Session');
function beforeFilter()
{
$this->Auth->allow("logout");
parent::beforeFilter();
}
function index() { } //Redirects to login()
function login()
{
if ($this->Auth->login())
{
$this->redirect($this->Auth->redirect());
} else
{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
function logout()
{
$this->redirect($this->Auth->logout());
}
}
?>
I appreciate any help with this. Thanks!

The "Invalid username or password, try again" error is displayed after you hit login?
There are a few things you should check:
• Is the output of $this->Auth->login() identical to the information in your database? Put debug($this->Auth->login()) to see the output in your login method after the form is submitted.
• Are the passwords correctly hashed in the database?
• Try making the AuthComponent available to all your controllers not just the UsersController.
• Not sure if this makes a difference, but call parent::beforeFilter(); before anything else in your controller's beforeFilter method.
EDIT:
Is see that you're trying to validate based on email and password. As a default AuthComponent expects a username and password. You have to explicitly state that you want the email and password to be validated by $this->Auth->login(). This comes from the 2.0 documentation:
public $components = array(
'Auth'=> array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
The fact that you're not seeing any SQL output is to be expected, I believe.

Also you must check if your field "password" in database is set to VARCHAR 50.
It happens to me that I was truncating the hashed password in DB and Auth never happened.

if you are not using defalut "username", "password" to auth, you cant get login
e.g., you use "email"
you should edit component declaration in your controller containing your login function:
$component = array('Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'mot_de_passe')
)
)
));

Becareful with cakephp's conventions. You should change this "$this->Auth->userModel = 'Users';" to "$this->Auth->userModel = 'User';" because User without plural is the Model's convention in cake. That worked for me and also becareful with the capital letters. it almost drived me crazy. Good luck.

public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'Events',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'Users',
'action' => 'login',
'home'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username','password' => 'password')
)
)
)
);

Editing the component declaration in AppController did the trick for me. If you have the fields named other than "username" and "password" you should always specify them. In your case it would be
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username' => 'email','password' => 'password')
)
)
)
);

There is a bug in the cakephp tutorial.
$this->Auth->login() should be changed to
$this->Auth->login($this->request->data)

Related

ReCaptcha with ZF3 wrong value

I use the newest Zend Framework available, and now i want to use ReCaptcha on my form. Together with some other elements, the ReCaptcha element is defined by:
$pubKey = 'replaced by the actual pubkey';
$privKey = 'replaced by the actual privkey';
$recaptcha = new \Zend\Captcha\ReCaptcha(['pubKey' => $pubKey, 'privKey' => $privKey]);
$this->add(array(
'attributes' => array (
'data-role' => 'none',
),
'name' => 'captcha',
'type' => 'captcha',
'options' => array(
'captcha' => $recaptcha,
),
));
This code validates the form in the controller:
public function contactAction () {
$contactForm = new ContactForm();
if($this->getRequest()->isPost()) {
$contactForm->setData($this->getRequest()->getPost());
if($contactForm->isValid()){
// send actual mail
return $this->redirect()->toRoute('page', ['lang' => $this->translator->getLocale(), 'page' => 'contact']);
}
}
$viewModel = new ViewModel ([
'contactForm' => $contactForm
]);
$viewModel->setTemplate('application/index/contact');
return $viewModel;
}
And finally, this is the view:
<?= $this->form($contactForm); ?>
To me, this code is pretty straightforward and should work. However, on sending the contact form, it displays the error 'Captcha value is wrong'. Any ideas?
You have to name the element according to the rules of Google. With this code, it works like a breeze
$pubKey = 'replaced by the actual pubkey';
$privKey = 'replaced by the actual privkey';
$recaptcha = new \Zend\Captcha\ReCaptcha(['pubKey' => $pubKey, 'privKey' => $privKey]);
$this->add(array(
'name' => 'g-recaptcha-response',
'type' => 'captcha',
'options' => [
'captcha' => $recaptcha,
]
));
Anyways, as always the ZF Docs are very short and lack examples.

Zend Framework 2 - Gobal Variable that are accessible to controller/model that are initialize in local.php or global.php

Hello everyone please someone help me how to create a global variable in zend framework 2 to be use in table prefix that are accessible in controller and model.
Thanks and regards to all.
In your config/database.local.php you can define which you want globally
<?
return array(
'service_manager' => array(
'factories' => array(
//'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'Zend\Db\Adapter\Adapter' => function ($serviceManager) {
$adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
$adapter = $adapterFactory->createService($serviceManager);
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
return $adapter;
}
),
),
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=testdb;host=localhost',
'username' => 'root',
'password' => '',
),
'msg' => array(
'add' => 'Data Inserted Successfully',
'edit' => 'Data Updated Successfully',
'delete' => 'Data Deleted Successfully',
),
);
?>
Controller File:
DemoController.php
<?php
namespace Demo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class DemoController extends AbstractActionController
{
public function indexAction($cms_page_name='whyus')
{
/*Call config file to fetch current cms page id-- fetch config file from database.local.php*/
$config = $this->getServiceLocator()->get('Config');
$all_msg = $config['msg'];
}
}
?>

Hashing passwords and AuthComponent

I'm trying to login in my CakePHP 2.0 application but I always get the login error.
In the official documentation and the tutorial I've read how to hash the passwords, but I still get the login error, here is how I did it:
// Users Model
public function beforeSave ($options = array ()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
// Users Controller
public $components = array ('Acl', 'Session',
'Auth' => array (
'authenticate' => array (
// login e logout sono di default i seguenti controller e views
// 'loginRedirect' => array ('controller' => 'users', 'action' => 'login'),
// 'logoutRedirect' => array ('controller' => 'users', 'action' => 'logout'),
'Form' => array (
'fields' => array (
// il valore default
'username' => 'email'
),
'scope' => array (
'User.active' => 1
)
)
),
'authError' => 'Login error message I get'
));
public function login () {
if ($this->request->is('post')) { // if the request came from post data and not via http (useful for security)
// the password is hashed in User Model in beforeSave method as read on documentation
// debug ($this->data);
if ($this->Auth->login()) {
$id = $this->Auth->user('id');
return $this->redirect(array('controller'=>'users', 'action'=>$id, $this->Auth->user('username')));
} else {
$this->Session->setFlash('Login error message', 'default', array(), 'auth');
}
}
}
In the view I have this:
// the view login.ctp
echo $this->Form->text('User.email', array('id'=>'email', 'value'=>'your#email.com'));
echo $this->Form->password('User.password', array('id'=>'password', 'value'=>'password'));
If I try to debug the data I get this:
// in the controller
debug($this->data);
// in the view
Array
(
[User] => Array
(
[email] => the#email.com
[password] => thepass // not hashed
)
)
I can't login because I get always the Login error message. How can I fix it?
Vitto,
(1) Which error message is displayed?
(2) Just for the record, be sure sessionFlash is printed at layout!
echo $this->Layout->sessionFlash();
(3) How did you set your Auth component? For example, in my AppController I've set this way:
public $components = array(
'Session',
'Cookie',
'Acl',
/**
* Default is authorize option is ActionsAuthorize.
* In this case, system uses AclComponent to check for permissions on an action level.
* learn more: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
*/
'Auth'=> array(
'authorize' => array(
'Actions' => array('actionPath' => 'controllers')
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'password')
)
)
)
);
(4) Finally, I believe (must be sure) there is no need to manually hash password to perform login. At least, after correct configuration, this code works for me:
if ($this->request->is('post')) {
if ($this->Auth->login()) {
// recirect stuffs

CakePHP not showing my form errors

I'm trying to create a login form for my web application.
Form validation errros are not showing even though I'm using the $validate Array.
user.php
public $validate = array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'notEmpty',
'required' => true
),
'isEmail' => array(
'rule' => 'email'
),
'isUnique' => array(
'rule' => 'isUnique'
)
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty'
),
'minLength' => array(
'rule' => array('minLength', 8)
)
)
);
I can't see an error in my user model, so I show you my controller and my view.
users_controller.php
class UsersController extends AppController {
public $name = 'Users';
public $helpers = array(
'Form'
);
public function login() {
if(!empty($this->data)) {
if ($this->Auth->user() != null) {
$this->Session->setFlash('You are now logged in.', 'flash/success');
$this->redirect('/');
} else {
$this->Session->setFlash('You could not get logged in. Please see errors below.', 'flash/error');
}
}
}
login.ctp
echo $this->Form->create('User', array('action' => 'login'));
echo $this->Form->input('User.email', array(
'label' => __('email address:', true),
'error' => array(
'notEmpty' => __('Email address must not be blank.', true),
'isEmail' => __('Email address must be valid.', true),
)
));
echo $this->Form->input('User.password', array('label' => __('password:', true)));
echo $this->Form->end('Log in');
I hope you can help me. I can't find my mistake since hours. Is there maybe a component or an helper which I need to include?
put echo $this->Session->flash('auth'); before form->create. You don't have to validate login form, Auth will take care of that for you. Read the cookbook: http://book.cakephp.org/view/1250/Authentication
Since you are using Auth, the minLength validation for password is useless.
Validation doesn't occur automatically unless you're saving into the database. Change the first line of the login method in the controller to
if( !empty( $this->data ) && $this->User->validates() ) {
...

Zend Navigation, how can i use it with params in the url ? I tried it with params in navigation without changes :(

I have got a problem with the zend navigation.
I use the zend navigation, and its ok when i call something like this in the url:
www.website/article_new, www.website/article_list,
www.website/friends_new, ...
But I want to call the site with some params like this:
www.website/article_new/123452/2335/45633246,
www.website/friends_new/23453/3453524/34554
I try it about to set some params, but this doesnt function.
I put the navigation in the bootstrap and in the layout I use it. Its a Navigation with some breadcumps where display:true and display:false.
Here is a code from my bootstrap:
$navigation = new Zend_Navigation(array(
array(
'label' => 'Home',
'controller' => 'index',
'action' => 'index',
'class' => 'menuF'
),
array(
'label' => 'Article',
'controller' => 'Article_List',
'id' => 'article',
'action' => 'index',
'class' => 'menu',
'pages' => array(
array(
'label' => 'Neu',
'id' => 'article',
'controller' => 'Article_New',
'action' => 'index',
'class' => 'submenu'
)
)
).....
And the code from the layout.phtml. On this code I show if the breadcump is shown or not.
foreach($container as $page) {
$par = $active;
if ($page != $active && $page->getClass()!='menu' && $page->getClass()!='menuF' && $page->getID()!=$par->getID()) {
$page->setClass('submenu');
} else {
$found = $container->findAllBy('ID', $active->getID());
foreach($found AS $p){
if($p->getClass()!='menu'&&$p->getClass()!='menuF'){
$p->setClass('sub');
}
}
}
}
echo $this->navigation()->menu()->renderMenu($this->nav);
Hope anybody can help me!
Thanks for all!
Best regards
Tom
I found myself the mistake!
I want to call something like this:
www.website/article/344435/23452345
surely this throws a mistake, because there isnt any action like 344435
with something like this
www.website/article/show/var1/2435234/var2/2345234352
its ok.
the rest is something for routing!
Big sorry to all!
Greats Tom
Try to use the route name instead of the module, controler and action system.
array(
'label' => 'Article',
'route' => 'Article_List',
'id' => 'article',
'class' => 'menu',
...
)
The router will handle all the URL parsing and return the correct variables.