CakePHP authentication return false - cakephp

I have an error with CakePHP, the authentication method always returns false in development environment but works fine in production environment.
When debugging $this->data in my UsersController, the password is not visible. Is this normal operation?
What is the correct way to debug this method ?
$this->data :
array(
'User' => array(
'password' => '*****',
'username' => 'martin'
)
)
My login function in UsersController.
public function login() {
if($this->request->is('post')){
if($this->Auth->login()){
// Mise à jour nombre de connexion
$this->User->updateAll(array(
'User.nb_cnx' => 'User.nb_cnx + 1'
), array(
'User.id' => $this->Auth->user('id')
));
// Mise à jour dernière date de connexion
$this->User->id = $this->Auth->user('id');
$this->User->saveField('last_cnx', date('Y-m-d H:i:s'));
// Petit nettoyage au cas où
$this->Session->delete('Article');
$this->Session->delete('Stock');
$this->Session->delete('Commande');
$this->Session->delete('RetourAdmin');
if($this->Cookie->read('Commande')){
$this->Session->write('Commande', $this->Cookie->read('Commande'));
}
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Flash->error(__('Votre nom d\'user ou mot de passe sont incorrects.'));
}
}
if($this->Session->read('Auth.User')){
$this->Session->setFlash('Vous êtes connecté!');
return $this->redirect('/');
}
}

Related

Symfony4 : Update function problem with 'data_class' => null, how can i keep my last file and not update him to null?

I created a form ProjectForm to create/edit a project with a Filetype::class to upload image. if i don't want to change my upload file he become null, cause of 'data_class' => null so i don't know how to whange this null data by my last file !
I will try to stock my last file in a var "$lastfile = $project->getCardImg();" but when my form is submitted my var become automatically null.
My Form
$builder
->add('title', TextType::class,['required'=> true,'label' => "Titre du nouveau projet"])
->add('content', TextareaType::class,['required'=> true,'label' => "Ensemble du contenu en HTML", 'attr' => ['class' => 'summernote']])
->add('githubLink', UrlType::class,['required'=> false,'label' => "Lien GitHub du projet"])
->add('demoLink', UrlType::class,['required'=> false, 'label' => "Lien de la demo du projet"])
->add('year', TextType::class,['required'=> true, 'label' => "Année de conception du projet"])
->add('technoUses', ChoiceType::class, [
'choices' => [
'html' => 'html',
'css' => 'css',
'javascript' => 'javascript',
'sass' => 'sass',
'symfony' => 'symfony',
],
'multiple' => true,
'expanded' => true,
])
->add('cardImg', FileType::class, ['required'=> false,'label' => 'Image du projet', 'data_class' => null])
->add('description', TextareaType::class,['required'=> true,'label' => "Description du projet"]);
}
My function to update a project
/**
* Edition d'un projet
*
* #Route("/admin/project/{id}/edit", name="admin_edit_project")
*
* #return Response
*/
public function editProject(Request $request, ObjectManager $manager, Projects $project){
$form = $this->createForm(ProjectFormType::class, $project);
$form->handleRequest($request);
$lastfile = $project->getCardImg();
dump($lastfile);
if ($form->isSubmitted() && $form->isValid()) {
dump($lastfile);
if($form->get('cardImg')->getData() == null){
$project->setCardImg($lastfile);
}else{
$file = $form['cardImg']->getData();
$fileName = str_replace(' ', '_', $project->getTitle()).'.'.$file->guessExtension();
// Move the file to the directory where brochures are stored
try {
$file->move(
$this->getParameter('img_project'),
$fileName
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
$project->setCardImg($fileName);
}
$manager->persist($project);
$manager->flush();
$this->addFlash(
'primary',
'Votre projet a bien était modifié !'
);
return $this->redirectToRoute('admin');
}
return $this->render('admin/project/editProject.html.twig', [
'project' => $project,
'form' => $form->createView()
]);
}
i expected to unchange my image when i update my project.
I think this should works better
/**
* Edition d'un projet
*
* #Route("/admin/project/{id}/edit", name="admin_edit_project")
*
* #return Response
*/
public function editProject(Request $request, ObjectManager $manager, Projects $project) {
$lastfile=$project->getCardImg();
$form=$this->createForm(ProjectFormType::class, $project);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
if($project->getCardImg) { //Is either a file or null
/** #var UploadedFile $file */
$file=$project->getCardImg();
//I would suggest to use Ramsey UUID to rename files.
//$fileName=Uuid::uuid1()->toString().'.'.$file->guessExtension();
$fileName=str_replace(' ', '_', $project->getTitle()).'.'.$file->guessExtension();
try {
$file->move($this->getParameter('img_project'), $fileName);
} catch(FileException $e) {
// ... handle exception if something happens during file upload
}
$project->setCardImg($fileName);
} else {
$project->setCardImg($lastfile);
}
//persist isn't needed if you edit.
//$manager->persist($project);
//Where did you init $manager?
//$manager->flush();
$this->getDoctrine()
->getManager()
->flush();
$this->addFlash('primary', 'Votre projet a bien était modifié !');
return $this->redirectToRoute('admin');
}
return $this->render('admin/project/editProject.html.twig', [
'project'=>$project,
'form'=>$form->createView(),
]);
}

cakePHP3: How to write a clean MVC code?

I would like to write my code according to the MVC paradigm in cakePHP3:
I have a formular to register an owner but as an owner is basically a user with additional informations, I have 2 SQL tables; one for a user pointing to an owner, and one for the owner.
The idea here is that a user is not necessary an owner.
So I currently wrote the code, which do what I want in the add action in the OwnerController.php.
public function add() {
$this->loadModel('Users');
$user = $this->Users->newEntity($this->request->data);
$owner = $this->Owners->newEntity($this->request->data);
$addDatas = [
'owner_id' => 'id',
'email' => $owner['email'],
'role' => 'owner',
'token' => md5(time() . '-' . uniqid()),
];
$user = $this->Users->patchEntity($user, $addDatas);
$owner->users = [$user];
if ($this->request->is('post')) {
if ($this->Owners->validate($owner)) {
if ($this->Owners->save($owner)) {
$email = new Email('gmail');
$email->template('activationLink')
->emailFormat('text')
->to($owner['email'])
->from('myemail#monsite.fr')
->subject(__('Votre inscription sur monsite.fr'))
->viewVars(['user' => $user, 'id' => $user['id']])
->send();
$this->Flash->success(__("Merci de vous être enregistré. un email a été envoyé à {0} pour activer votre compte", $owner['email']));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__("Impossible de vous enregistrer, veuillez corriger les erreurs"));
} else {
$this->Flash->error(__("Impossible de vous enregistrer, veuillez corriger les erreurs"));
}
}
$this->set(compact('owner'));
}
now, I would like to write it like that:
public function add() {
$owner = $this->Owners->newEntity($this->request->data);
if ($this->request->is('post')) {
if ($owner->addOwner($this->request->data)) {
$this->Flash->success(__("Merci de vous être enregistré. un email a été envoyé à {0} pour activer votre compte", $owner['email']));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__("Impossible de vous enregistrer, veuillez corriger les erreurs"));
}
}
$this->set(compact('owner'));
}
And so, I would have an addOwner() action in my Owner.php and let him to do everything needed.
My problem is that I don't see in the documentation how can I have access to my User model from my Owner model and more precisely, how to make the User model validate and save its record.
Maybe I'm wrong but I don't really see this way to code in the tutorials.
Owner.php
class Owner extends Entity {
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* #var array
*/
protected $_accessible = [
'email' => true,
'phone' => true,
'company' => true,
'tva_number' => true,
'address' => true,
'postcode' => true,
'city' => true,
'users' => true,
];
public function addOwner($data = array()) {
// This is where I want to create both the owner and the user
// as the owner is basically a user with additional contact infos.
// But how to access the User model here to realize the validation
// as save the record?
}
}
User.php
class User extends Entity {
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* #var array
*/
protected $_accessible = [
'username' => true,
'password' => true,
'first_name' => true,
'last_name' => true,
'email' => true,
'role' => true,
'owner' => true,
'sites_user' => true,
'active' => true,
'token' => true,
];
protected function _setPassword($password) {
return (new DefaultPasswordHasher)->hash($password);
}
}
UsersTable.php
public function initialize(array $config) {
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('Owners', [
'foreignKey' => 'owner_id',
]);
$this->belongsTo('SitesUsers', [
'foreignKey' => 'sites_users_id',
]);
}
OwnersTable.php
public function initialize(array $config) {
$this->table('owners');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Users', [
'foreignKey' => 'owner_id',
]);
}
Can you show me the relationship between the two ?
First, you should normalize your database (on your Owners entity I can see you have users which is an array of users).
Also, use CakePHP 3 naming conventions: http://book.cakephp.org/3.0/en/intro/conventions.html
Then, since this seems to be your first steps into CakePHP 3, you should try bake (CakePHP Scaffolding) your application.
Bake (CakePHP Scaffolding): http://book.cakephp.org/3.0/en/bake/usage.html
Baking an is a great way to see how you should start coding in CakePHP 3.
Hope this helps.

Refresh page after deleting data from db

I have an action to delete images from an gallery in my app. When the user clicks the "Delete" button, the image is deleted and a "success" message is displayed, but the deleted image is still in the images list, and it disappears once I press refresh.
How can I make that image disappear right after the user presses the delete button?
I already tried using $this->redirect('/Admin/Dashboard/Gallery/Delete'); but that does not allow the "success" message to be displayed.
I am using CakePHP 2.4.4.
controller
public function deleteImages($id){
$this->set('title_for_layout', 'Apagar imagens');
$this->layout = 'admin';
$this->loadModel('GalleryImage');
$this->GalleryImage->id=$id;
$this->Paginator->settings = array(
'GalleryImage' => array(
'limit' => 20,
//'maxLimit' => 100,
'order' => array('GalleryImage.modified' => 'desc') // Por exemplo
)
);
$gallery_images=$this->Paginator->paginate('GalleryImage');
$this->set('gallery_images', $gallery_images);
if($this->request->is('post')){
if(!$this->GalleryImage->exists()){
throw new NotFoundException('Erro, esta fotografia não foi encontrada.', 'default', array('class'=>'alert flashMessageDanger alert-dismissable'));
}
$options = array('conditions' => array('GalleryImage.'.$this->GalleryImage->primaryKey=>$id));
$gallery_image_delete = $this->GalleryImage->find('first', $options);
if(file_exists(WWW_ROOT."img/Gallery/" .$gallery_image_delete['GalleryImage']['name'])){
unlink(WWW_ROOT."img/Gallery/".$gallery_image_delete['GalleryImage']['name']);
$this->GalleryImage->delete();
$this->Session->setFlash('A Imagem foi excluída com sucesso.', 'default', array('class'=>'alert flashMessageSuccess alert-dismissable'));
$this->redirect('/Admin/Dashboard/Gallery/Delete');
}else{
$this->Session->setFlash('Erro, esta Imagem não existe.', 'default', array('class' => 'alert flashMessageDanger alert-dismissable'));
}
//$this->redirect('/Admin/Dashboard/Gallery/Delete');
}
}
Change the order of your code, so that the line $gallery_images = $this->Paginator->paginate('GalleryImage');, the line that gets your gallery images for display on the page, comes after your code that actually does the delete.
public function deleteImages($id){
$this->set('title_for_layout', 'Apagar imagens');
$this->layout = 'admin';
$this->loadModel('GalleryImage');
$this->GalleryImage->id=$id;
//code moved from here.
if($this->request->is('post')){
if(!$this->GalleryImage->exists()){
throw new NotFoundException('Erro, esta fotografia não foi encontrada.', 'default', array('class'=>'alert flashMessageDanger alert-dismissable'));
}
$options = array('conditions' => array('GalleryImage.'.$this->GalleryImage->primaryKey=>$id));
$gallery_image_delete = $this->GalleryImage->find('first', $options);
if(file_exists(WWW_ROOT."img/Gallery/" .$gallery_image_delete['GalleryImage']['name'])){
unlink(WWW_ROOT."img/Gallery/".$gallery_image_delete['GalleryImage']['name']);
$this->GalleryImage->delete();
$this->Session->setFlash('A Imagem foi excluída com sucesso.', 'default', array('class'=>'alert flashMessageSuccess alert-dismissable'));
$this->redirect('/Admin/Dashboard/Gallery/Delete');
}else{
$this->Session->setFlash('Erro, esta Imagem não existe.', 'default', array('class' => 'alert flashMessageDanger alert-dismissable'));
}
//$this->redirect('/Admin/Dashboard/Gallery/Delete');
}
//code moved to here.
$this->Paginator->settings = array(
'GalleryImage' => array(
'limit' => 20,
//'maxLimit' => 100,
'order' => array('GalleryImage.modified' => 'desc') // Por exemplo
)
);
$gallery_images=$this->Paginator->paginate('GalleryImage');
$this->set('gallery_images', $gallery_images);
}

The login() not found there isn't any error in my app with cakephp

VERSION CAKEPHP 2.4.5
I'm working with postgresql 9.1
hello i have this problem, that my login don't work I don't know why? There isn't any error, this is my code that I'm using:
UsersController.php
public function login() {
//if already logged-in, redirect
if($this->Session->check('Auth.User')){
$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(__('Bienvenido, '. $this->Auth->user('username')));
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalido nombre de usuario o contraseña'));
}
}
VIEW
login.ctp
App::uses('AuthComponent', 'Controller/Component');
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Porfavor ingresa tu nombre de usuario y contraseña'); ?></legend>
<?php echo $this->Form->input('username', array('label' => 'Nombre de Usuario', 'maxLength' => 60));
echo $this->Form->input('password', array('label' => 'Contraseña', 'maxLength' => 60));
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
<?php
echo $this->Html->link( "Agregar un nuevo usuario", array('action'=>'add') );
?>
model user.php
public function beforeSave($options = array()) {
// hash our password
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
// if we get a new password, hash it
if (isset($this->data[$this->alias]['password_update']) && !empty($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);
}
AppController.php
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'Tu tienes que estas logueado para ver la pagina.',
'loginError' => 'Invalido nombre de usuario ingresado.'
));
// only allow the login controllers only
public function beforeFilter() {
$this->Auth->allow('login');
}
public function isAuthorized($user) {
// Here is where we should verify the role and give access based on role
return true;
} }
In AppController, add inside Auth (after loginError):
'authenticate' => array('Form')
And in your view, you don't need to import AuthComponent
ok this the answer
FISRT AND IMPORTANT MY VESION OF CAKE PHP IS 2.4.5
I did read:
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords
and I after of this I did a lot debugs and I see that my password is not the same that the pasword of mi Database. but this not that simple because i didn't know, how have the same encriptation, and I didn't know what encryptation I was using, so I look for a lot answer here in stackoverflow and this is the best.
CakePHP 2.1 Auth->login() not working, but adding user does
the key to all this is here
public function beforeFilter() {
Security::setHash('sha1');//this is the encryption very important
$this->Auth->allow('login','add', 'index');
}
now this is my code final:
MODEL
User.php
<?php
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public $name ='User';
public $validate = array(
'username' => array(
'nonEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Un nombre de usuario es requerido',
'allowEmpty' => false
),
'between' => array(
'rule' => array('between', 5, 15),
'required' => true,
'message' => 'Los nombre de usuario deben contener entre 5 y 15 caracteres'
),
'unique' => array(
'rule' => array('isUniqueUsername'),
'message' => 'Este nombre de usuario esta en uso.'
),
'alphaNumericDashUnderscore' => array(
'rule' => array('alphaNumericDashUnderscore'),
'message' => 'Nombre de usuario solo puede contener letras numeros y barra baja'
),
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Una contraseña es requerida'
),
'min_length' => array(
'rule' => array('minLength', '6'),
'message' => 'Contraseña debe contener 6 caracteres'
)
),
'password_confirm' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Por favor confirme su contraseña'
),
'equaltofield' => array(
'rule' => array('equaltofield','password'),
'message' => 'Ambas contraseñas deben ser iguales.'
)
),
'nombre' => array(
'nonEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Ingresar un nombre es requerido',
'allowEmpty' => false
),
),
'apellido' => array(
'nonEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Ingresar un apellido es requerido',
'allowEmpty' => false
),
),
'email' => array(
'required' => array(
'rule' => array('email', true),
'message' => 'Porfavor ingrese un correo electronico'
),
'unique' => array(
'rule' => array('isUniqueEmail'),
'message' => 'Este correo esta en uso',
),
'between' => array(
'rule' => array('between', 6, 60),
'message' => 'Nombres usuario debe contener de 6 a 60 caracteres'
)
),
'tipo_usuario' => array(
'valid' => array(
'rule' => array('inList', array('administrador', 'azucar', 'soya', 'avicola')),
'message' => 'Porfavor ingrese un tipo de usuario valido',
'allowEmpty' => false
)
),
'password_update' => array(
'min_length' => array(
'rule' => array('minLength', '6'),
'message' => 'Contraseña debe tener 6 caracteres',
'allowEmpty' => true,
'required' => false
)
),
'password_confirm_update' => array(
'equaltofield' => array(
'rule' => array('equaltofield','password_update'),
'message' => 'Ambos deberian ser iguales.',
'required' => false,
)
)
);
/**
* Before isUniqueUsername
* #param array $options
* #return boolean
*/
function isUniqueUsername($check) {
$username = $this->find(
'first',
array(
'fields' => array(
'User.id',
'User.username'
),
'conditions' => array(
'User.username' => $check['username']
)
)
);
if(!empty($username)){
if($this->data[$this->alias]['id'] == $username['User']['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(
'User.id'
),
'conditions' => array(
'User.email' => $check['email']
)
)
);
if(!empty($email)){
if($this->data[$this->alias]['id'] == $email['User']['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()) {
// hash our password
if (!$this->id) {
$passwordHasher = new SimplePasswordHasher();
$this->data['User']['password'] = $passwordHasher->hash($this->data['User']['password']);
}
// if we get a new password, hash it
if (isset($this->data[$this->alias]['password_update']) && !empty($this->data[$this->alias]['password_update'])) {
$this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password_update']);
}
// fallback to our parent
//return parent::beforeSave($options);
return true;
}
}
?>
impotartant
AppController.php
<?php
/**
* Application level Controller
*
* This file is application-wide controller file. You can put all
* application-wide controller-related methods here.
*
* 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 http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* #package app.Controller
* #link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'Tu tienes que estas logueado para ver la pagina.',
'loginError' => 'Invalido nombre de usuario ingresado.',
'authorize'=> array('Controller'),
'authenticate' => array('Form')
));
// only allow the login controllers only
public function beforeFilter() {
Security::setHash('sha1');
$this->Auth->allow('login','add', 'index');
}
public function isAuthorized($user) {
// Here is where we should verify the role and give access based on role
return true;
}
}
Important
UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $helpers = array('Html','Form');
public $name = 'Users';
public $paginate = array(
'limit' => 25,
'conditions' => array('aprobacion' => '1'),
'order' => array('User.username' => 'asc' )
);
public function beforeFilter() {
parent::beforeFilter();
}
public function login() {
// if we get the post information, try to authenticate
debug(Security::hash($this->data['User']['password']));
debug($this->data);
if ($this->request->is('post')) {
debug($this->Session->check('Auth.User'));
if ($this->Auth->login()) {
$this->Session->setFlash(__('Bienvenido, '. $this->Auth->user('username')));
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalido nombre de usuario o contraseña'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function index() {
$this->paginate = array(
'limit' => 6,
'order' => array('User.username' => 'asc' )
);
$users = $this->paginate('User');
$this->set(compact('users'));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('El usuario fue creado'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Posiblemente el usuario no fue creado. Intente de nuevo'));
}
}
}
public function edit($id = null) {
if (!$id) {
$this->Session->setFlash('Porfavor provea un id de usuario');
$this->redirect(array('action'=>'index'));
}
$user = $this->User->findById($id);
if (!$user) {
$this->Session->setFlash('El id proporcionado no es valido');
$this->redirect(array('action'=>'index'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id;
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('El usuario fue modificado'));
$this->redirect(array('action' => 'edit', $id));
}else{
$this->Session->setFlash(__('Disponible solo para actualizar tu usuario.'));
}
}
if (!$this->request->data) {
$this->request->data = $user;
}
}
public function delete($id = null) {
if (!$id) {
$this->Session->setFlash('Porfavor provea un id de usuario');
$this->redirect(array('action'=>'index'));
}
$this->User->id = $id;
if (!$this->User->exists()) {
$this->Session->setFlash('El id proporcionado no es valido');
$this->redirect(array('action'=>'index'));
}
if ($this->User->saveField('aprobacion', 0)) {
$this->Session->setFlash(__('Usuario borrado'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Usuario no fue borrado'));
$this->redirect(array('action' => 'index'));
}
public function activate($id = null) {
if (!$id) {
$this->Session->setFlash('Porfavor provea un id de usuario');
$this->redirect(array('action'=>'index'));
}
$this->User->id = $id;
if (!$this->User->exists()) {
$this->Session->setFlash('El id proporcionado no es valido');
$this->redirect(array('action'=>'index'));
}
if ($this->User->saveField('aprobacion', 1)) {
$this->Session->setFlash(__('Usuario re-activado'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Usuario no fue re-activado'));
$this->redirect(array('action' => 'index'));
}
}
?>
NOw
login.ctp
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo ('Porfavor ingresa tu nombre de usuario y contraseña'); ?></legend>
<?php
echo $this->Form->input('username', array('label' => 'Nombre de Usuario', 'maxLength' => 60));
echo $this->Form->input('password', array('label' => 'Contraseña', 'maxLength' => 60));
?>
</fieldset>
<?php echo $this->Form->end(('Login')); ?>
</div>
<?php
echo $this->Html->link( "Agregar un nuevo usuario", array('action'=>'add') );
?>
just use imagination for edit.ctp, add.ctp

CakePHP $this->Auth->login() return false

I created a User with the hash provided by the Cake .. But when I go to log in, says 'Invalid username or password'. But it's all right.
The $this->Auth->login(); always returns false...
Crontroller
class MastersController extends AppController{
public function login(){
if ($this->request->is('post')) {
debug($this->Auth->login());
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout(){
$this->redirect($this->Auth->logout());
}}
AppController
class AppController extends Controller {
public $components = array('Session', 'Cookie', 'Auth');
function beforeFilter() {
$this->loadModel('Master');
$this->Auth->userModel = 'Master';
$this->Auth->allow('*');
// Action da tela de login
$this->Auth->loginAction = array(
'masters' => false,
'controller' => 'masters',
'action' => 'login'
);
// Action da tela após o login (com sucesso)
$this->Auth->loginRedirect = array(
'masters' => true,
'controller' => 'masters',
'action' => 'index'
);
// Action para redirecionamento após o logout
$this->Auth->logoutRedirect = array(
'masters' => false,
'controller' => 'pages',
'action' => 'login'
);
$this->Auth->authorize = array('controller');
if (!isset($this->params['masters']) || !$this->params['masters'])
$this->Auth->allow('*','login');
$this->Auth->loginError = __('Usuário e/ou senha incorreto(s)', true);
$this->Auth->authError = __('Você precisa fazer login para acessar esta página', true);
}
public function isAuthorized($masters){
return TRUE;
}}
VIEW login.ctp
echo 'Formulário de login';
echo $this->Session->flash('auth');
echo $this->Session->flash();
echo $this->Form->create('Master', array('controller'=>'masters','action'=>'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Entrar');
Model
class Master extends AppModel{
public $name = 'Master';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Usuario requerido.'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Senha requerida.'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
I don't know why it is giving this error .. This all seems ok!
I changed one letter of Security.salt, as he asked ..
Help me :)
I need it for work
debug($this->Auth->login());
if ($this->Auth->login()) {}
is a bad idea.
the first will log you in,
the second call will then - of course - return false (since you are already logged in).
If you really need to test this way, halt the code:
debug($this->Auth->login()); die();
I had the same problem and what fixed it for me was changing $this->alias to User, so beforeSave() now looks like
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}

Resources