I have a simple login form, just like the Cake Blog Tutorial.
It works like a charm when I use 'UsersController' and 'User' model naming conventions, passing the rights queries in debug.
But when I change it to other name, Alunos in my case, it generates no QUERY and give me 'Incorrect username and/or password.'.
My login.ctp
<H1> Login </H1>
<?php
debug($this->data);
echo $this->Form->create('Aluno', array('action' => 'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
My AppController
<?php
class AppController extends Controller {
public $components = array (
'Session',
'Auth' => array (
'loginAction' => array ('controller'=>'alunos', 'action'=>'login'),
'loginRedirect'=>array ('controller'=>'alunos', 'action'=>'inicio'),
'logoutRedirect'=>array ('controller'=>'alunos', 'action'=>'index'),
'authError'=>"Ops, você não está autorizado a fazer isso.",
'authorize'=>array('Controller'),
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
$this->Auth->allow('index', 'add');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And my 'AlunosController.php' (see that its not USERSController, like common codes)
<?php
class AlunosController extends AppController {
public $name = 'Alunos';
public function beforeFilter(){
parent::beforeFilter();
}
public function index() {}
public function login(){
debug($this->Auth->login());
if ($this->request->is('post')) {
if ($this->Auth->login()){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Incorrect username and/or password.');
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function add() {
debug($this->Auth->login());
if($this->request->is('post')) {
if ($this->Aluno->save($this->request->data)) {
$this->Session->setFlash('Cadastrado.');
}else {
$this->Session->setFlash('Falha no cadastro.');
}
}
}
public function inicio() {
debug($this->Auth->login());
}
}
?>
My debug($this->data) in login.ctp result:
array(
'Aluno' => array(
'password' => '*****',
'username' => 'anyuser'
)
)
What am I doing wrong?
Add this code to your app controller:
function beforeFilter() {
$this->Auth->userModel = 'Aluno'; <-- Should be singular. My mistake
parent::beforeFilter();
}
UPDATE FOR CAKE2
// Place in beforeFilter() of AppController.php
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'Aluno'
)
);
Your problem is because you are not telling cake what to use for a user table. This is why your first instance works, and the second does not.
Change this:
echo $this->Form->create('Aluno', array('action' => 'login'));
to:
echo $this->Form->create('Alunos', array('url' => 'alunos/login'));
To call Alunos Controller's login() method.
Related
Hello Everyone i'm trying to login after i have successfully add user data into database, but login is not working,I'm new to cakephp.Please Help me out.
here is the code
appcontroller:
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar' ,'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);}
UsersController:
public function login(){
if ($this->request->is('Post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}//$this->Flash->error(__('Invalid username or password, try again'));
}
}
login.ctp:
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('login');
?>
Add password hashing to your User model
User.php
App::uses('AppModel', 'Model');
class User extends AppModel {
public function beforeSave($options = array()) {
if(isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
}
}
after that truncate your user table and save fresh user and then check again the login.
I'm facing trouble with my login system. I managed to register my user in my database but whenever I try to log in, it keeps prompting "Invalid email or password, try again".
This is my model:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('email', 'A email is required')
->add('email', 'valid' , ['rule'=> 'email'])
->add('email', [
'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
])
->requirePresence('email','create')
->notEmpty('password', 'A password is required')
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['admin', 'author']],
'message' => 'Please enter a valid role'
]);
}
}
My controller:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Network\Exception\NotFoundException;
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['add', 'logout']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid email or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users', $this->Users->find('all'));
}
public function view($id)
{
if (!$id) {
throw new NotFoundException(__('Invalid user'));
}
$user = $this->Users->get($id);
$this->set(compact('user'));
}
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Email already existed.'));
}
$this->set('user', $user);
}
}
AppController:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function isAuthorized($user)
{
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
return false;
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display']);
}
}
login.ctp
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your username and password') ?></legend>
<?= $this->Form->input('email') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
I think the problem comes from the AppController
Have a quick look at this : CookBook CakePHP 3.0 Example Bookmarker Part 1
The login part is here : CookBook CakePHP 3.0 Example Bookmarker Part 2
Find the similarities with your project, try to make an analogy, a relation.
Thanks guys! Managed to find the answer after referring to the tutorials. Turns out i miss out
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
All good now! Cheers =)
I'm using cakePHP building a website. The login function works fine in local, but after I post them onto the server, I cannot login with existing username and password. The page doesn't either let me log in, or give me an error message which is supposed to show up when there are issues. I tried almost every solution in stackoverflow but can't solve it. Here's my code.
Model:
class User extends AppModel {
public function beforeSave($options = array()) {
/* password hashing */
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
AppController:
class AppController extends Controller {
public function webroot() {
}
public $components = array('DebugKit.Toolbar','Session',
/* add Auth component and set the urls that will be loaded after the login and logout actions is performed */
'Auth' => array(
'loginRedirect' => array('controller' => 'Home', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);
public function beforeFilter() {
/* set actions that will not require login */
$this->Auth->allow('index','display', 'view');
}
}
UsersController:
class UsersController extends AppController {
public $components = array('Auth');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function login() {
if ($this->request->is('post')) {
/* login and redirect to url set in app controller */
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect('/Home'));
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
/* logout and redirect to url set in app controller */
return $this->redirect($this->Auth->logout());
}
public function index() {
$this->User->recursive = 0;
$this->set('Users', $this->paginate());
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash;
return $this->redirect(array('controller' => 'Home','action' => 'index'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
View:
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<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')); ?>
Another glitch I think I should mention is, as the code shows, when I add a new username and pw, the page should redirect me to Home. This also works fine locally, but on server it doesn't redirect, HOWEVER, the username and password is successfully stored into database when I added it.
I'm really stuck and have no clue what the problem is, any help is appreciated, thanks.
Update
errors in error.log :
2014-05-14 05:16:21 Error: [MissingActionException] Action UsersController::js() could not be found.
Exception Attributes: array (
'controller' => 'UsersController',
'action' => 'js',
)
Request URL: /users/js/lightbox.min.js
2014-05-14 05:16:21 Error: [MissingActionException] Action UsersController::js() could not be found.
Exception Attributes: array (
'controller' => 'UsersController',
'action' => 'js',
)
Request URL: /users/js/jquery-1.11.0.min.js
I baked a cakephp application with a users table, and I'm trying to get authentication to work using the Blowfish hash. My password field is a varchar(255), so it should be long enough to store the hash. Everything in the app is the default baked output, expect for what follows.
This issue is that I can't log in after creating a user; I always get "Access Denied". What's the best way of troubleshooting this?
AppController.php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public function beforeFilter(){
$this->Auth->allow('index', 'view');
}
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email'),
'passwordHasher' => 'Blowfish'
)
),
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index'),
'authError' => "Access Denied",
'authorize' => array('Controller'),
)
);
public function isAuthorized($user){
return true;
}
}
User.php (model)
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
public function beforeSave($options = array()) {
if (!empty($this->data['User']['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data['User']['password'] = $passwordHasher->hash($this->data['User']['password']);
}
return true;
}
UsersController.php
public function login(){
if ($this->request->is('post')) {
if($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
else {
$this->Session->setFlash('Access Denied');
}
}
}
login.ctp
echo $this->Form->create('user');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->button('Log In', array('type' => 'submit');
echo $this->Form->end();
'debug($this->request); die;' in login function gives the following output. should password be * or should it be the hashed version of the input?
data => array(
'user' => array(
'password' => '*****',
'email' => 'test#test.com'
)
)
1)listen to #waspinator echo $this->Form->create('User');
2)
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
remove it ad put it in AppController and it should be
App::uses('AuthComponent', 'Controller/Component');
3)comment this lines
//public function beforeFilter(){
// $this->Auth->allow('index', 'view');
//}
//public function isAuthorized($user){
// return true;
//}
4) for first time put this on top of user controller so you can save your password
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('edit', 'index', 'view);
}
echo $this->Form->create('user');
should be
echo $this->Form->create('User');
This question already has answers here:
Login Script in 2.4.2 is not working
(2 answers)
Closed 8 years ago.
my problem is : 'when i enter wrong username-password combination, it still redirects me to index page, while it should be redirected to login page again '.. what is the problem ??Pl help me... i am atteching my code...
here is AppController:
class AppController extends Controller {
public $components=array('DebugKit.Toolbar',
'Session','Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'login'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index')
));
public function beforeFilter(){
$this->Auth->allow('index','register');
}
}
here is UsersController:
class UsersController extends AppController
{
public $name='Users';
public $uses=array('user');
public $helpers = array('Html', 'Form','Session');
public function beforeFilter() {
parent::beforeFilter();
}
public function index()
{
}
public function login() {
if ($this->request->is('post')) {
/* login and redirect to url set in app controller */
if ($this->Auth->login($this->request->data)) {
$this->Session->setFlash(__('Successful!!!'));
$this->Session->write('user',$this->data['user']['username'],time()+3600);
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
// else{ echo "fail";exit;}
}
public function logout() {
/* logout and redirect to url set in app controller */
$this->Session->destroy();
return $this->redirect($this->Auth->logout());
}
public function register() {
if ($this->request->is('post')) {
$this->user->create();
if ($this->user->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('controller' => 'users','action' => 'index'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
here is User Model:
<?php
class User extends AppModel
{
var $name='User';
var $validate=array(
'username'=> array(
'rule'=>'notEmpty',
'message'=>'Enter Your USername'),
'password'=>array(
'rule'=>'notEmpty',
'message'=>'Enter your Password'
),
'Confirm_password'=>array(
'rule'=>'match',
'message'=>'password not match, try again'
)
);
public function match(){
if($this->data['user']['password']===$this->data['user']['Confirm_password'])
{
return true;
}
return false;
}
public function beforeSave($options = array()) {
/* password hashing */
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
here is my login ctp:
<h2>LOGIN-MYSITE</h2>
<?php echo $this->Form->create('user',array('action'=>'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('LOGIN');
?>
Remove 'index' from
$this->Auth->allow('index','register');
Keep
$this->Auth->allow('register');