I am trying to make the login work... but when i register (using the add) function i used to have a md5, then i changed it to $this->Auth->password, and then i tried without that line.. well it logins fine the first time.. but then for some reason it changes the hash again on login it never matches the database.. i dont know how to fix this.. here is my code
<?php
class UsersController extends AppController {
var $uses = array("User");
var $components = array('Auth', 'Session');
function index()
{
$this->set('users', $this->User->find('all'));
$this->layout = 'master_layout';
}
function beforeFilter() {
$this->Auth->allow('add');
}
function add() {
if (!empty($this->data)) {
//pass is hashed already
//->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your were registered!.');
$this->redirect(array('action' => 'index'));
}
}
$this->layout = 'master_layout';
}
//IF THE DATABASE IS SET UP CORRECTLY CAKE AUTHENTICATES AUTOMATICALLY NO
//LOGIC IS NEEDED FOR LOGIN http://book.cakephp.org/view/1250/Authentication
function login() {
$this->layout = 'master_layout';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
VIEW
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
you shouldnt use password as field name on forms.
this way even empty strings will be saved and will mess up already saved ones. depending on your beforeSave method the empty string might even be saved as hash (cloaking that its actually an empty password).
see
http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/
Related
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
Guys I uploaded my site on servers and I'm facing this problem.
Usercontroller.php
<?php
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Auth', 'Acl');
function beforeFilter(){
//parent::beforeFilter();
$this->Auth->loginError = "asdad!";
$this->Auth->authError = "sdsd !.";
App::uses('CakeEmail', 'Network/Email');
$this->Auth->userModel = 'User';
$this->Auth->allow('login','register','login','step2','TakeId','kontakt');
}
function login(){
if(!empty($this->data)){
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$sprawdz = $this->User->find('first',array('conditions'=>array('User.username'=>$this->request->data['User']['username'],'User.password'=>$this->request->data['User']['password'])));
echo debug($sprawdz);
if(!empty($sprawdz)){
if($this->Auth->login($this->request->data)){
$this->redirect('/');
echo debug('you are log in!') ;
}
}
else {
$this->User->invalidate('username', 'mistake!');
}
}
}
function logout(){
$this->Auth->logout();
$this->redirect('/');
}
}
User/login.ctp
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<?php echo $this->Form->input('username');
echo $this->Form->input('password'); ?>
</fieldset>
<?php echo $this->Form->end(__('Log in')); ?>
It is like Auth does not work at all. In localhost was fine. Additionaly, users/index is empty page :)
Any ideas would be great. Thanks.
Keep it simple, and follow the tutorial which shows how to use the auth component.
For example, try this:
function login(){
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash('You have successfully logged in the system');
return $this->redirect('/');
}
$this->Session->setFlash(__('Invalid username or password, try again [warning]'));
}
}
Also please make sure Security.Salt which is responsible to hash a password with the application's salt value
You did not defined any index function in usersController, that is why it is throwing error. Try to enable debug mode on so that you can track the errors
add $this->request->data on 2nd line of your login aciton-
function login(){
if(!empty($this->request->data)){
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$sprawdz = $this->User->find('first',array('conditions'=>array('User.username'=>$this->request->data['User']['username'],'User.password'=>$this->request->data['User']['password'])));
echo debug($sprawdz);
if(!empty($sprawdz)){
if($this->Auth->login()){
$this->redirect('/');
echo debug('you are log in!') ;
}
}
else {
$this->Session->setFlash('Invalid username or password');
}
}
}
Im trying to use Employee model instead of User model in Auth component. My code is:
AppController
public $components = array('Session','Auth');
function beforeFilter(){
Security::setHash('md5');
$this->Auth->userModel = 'Employee';
$this->Auth->fields = array('username'=>'code','password'=>'password');
$this->Auth->loginAction = array('controller'=>'employees','action'=>'login');
$this->Auth->loginRedirect = array('controller'=>'pages','action'=>'home');
$this->Auth->loginError = 'Invalid employee code or password, please try again';
$this->Auth->logoutRedirect = array('controller'=>'employees','action'=>'login');
}
function beforeRender(){
$this->set('Employee',$this->Auth->user());
}
EmployeeController
function login(){
$this->layout = 'login';
}
function logout(){
$this->Redirect($this->Auth->logout());
}
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('signup');
}
function beforeRender(){
parent::beforeRender();
}
login.ctp
<?php
echo $this->Form->create('Employee',array('/employees/login'));
echo $this->Form->input('code',array('label'=>'Employee code'));
echo $this->Form->input('password');
echo $this->Form->submit('Sign in',array('class'=>'b-button'));
echo $this->Form->end();
?>
The problem is, when i click the login button, page simply refreshes. No redirect, noerror messages, no nothing.
Is there any mistake in what im doing?
EDIT
function login(){
$this->layout = 'login';
if($this->request->is('post')){
if($this->Auth->login($this->request->data)){
$this->Redirect('/pages/home');
}else{
$this->Session->setFlash('incorrect');
}
}
}
function logout(){
$this->redirect($this->Auth->logout());
}
Now its allowing logging in irrespective of the the employee code or password entered. In fact its alloing logging in even if login fields are empty.
Try the following:
echo $this->Form->create('Employee', array('controller' => 'employees', 'action' => 'login'));
And also check the user authenticity in login method of your EmployeesController.php
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login($this->request->data))
{
/*... do what you want...*/
}
else
{
this->Session->setFlash('Your username or password was incorrect.');
}
}
}
echo $this->Form->create('Employee',array('/employees/login'));
Try:
echo $this->Form->create('Employee',array('action'=>'login'));
I had similar issue . Finally here is the solution.
a) Define the tablename and fileds inside $components. Dont use before filter
public $components = array('Session', 'Acl', 'Auth' => array('authenticate' => array('Form' => array('userModel' => 'Employee','fields' => array('username' => 'code'), 'password' => 'password'))), 'Cookie');
b)Never use
$this->Auth->login($this->request->data)
this creates session for whatever garbage u post.
Instead use
$this->Auth->login()
c) Also hashing method for cakephp is not md5. You may want to remove that line.
I m trying to create a new register and login page. I have a problem in login.
1) After I register the Username and Password it is successful hashed and saved into the DB, please find the codes below: (everything is as per cake conventions)
User.php:
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
......
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
UsersController.php:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('controller' => 'Posts','action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'), 'default', array(), 'auth');
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
login.ctp:
<fieldset>
<?php echo $this->Session->flash('auth'); ?>
</fieldset>
<?php echo $this->Form->create('Users');?>
<fieldset>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login'));?>
Debug: (debug($this->data);)
From AppController:
Array
(
[Users] => Array
(
[username] => vinodronold
[password] => vinodronold
)
)
From UsersController:
Array
(
[Users] => Array
(
[username] => vinodronold
[password] => vinodronold
)
)
Problem:
Whenever I access /Users/login URL I m getting "Invalid username or password, try again" message.
Also I m unable to login although I m entering the correct username and password.
Please help.
Thanks in advance!!!
Looking at it closer, change your if statement on the login function to this:
if (!empty($this->request->data['User']) && $this->Auth->login()) {
this will fix the instant error message you get when accessing the page.
And I just noticed your form in your view is wrong. Models are singular. Change your form create to:
<?php echo $this->Form->create('User');?>
This should do it for both issues.
I need to update a particular row. This doesn't seem to work. Any help is appreciated.
View updated:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Post');
?>
Controller updated:
public function index($id = 0){
$this->Setting->id = $id;
if (empty($this->request->data)) {
$this->request->data = $this->Setting->read();
} else {
if ($this->request->is('post')) {
$this->request->data['Setting']['id'] = $id;
$this->Setting->save($this->request->data);
$this->Session->setFlash('This should have saved...');
}
}
}
Edit:
blog_state is a boolean, and works fine. It loads the value from the DB normally and saves it to the new row normally. (I need it to update the existing row it is being pulled from, which is where my problem is)
Update your view:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Page');
?>
You will also need to make sure you set the id in the function so it will populate the value correctly. The record cannot be updated unless it knows the PK ID it is updating.
The way you can accomplish this is by setting it in the request data:
$this->request->data['Setting']['id'] = $id;
Then it will automatically be set in the view.
UPDATE
It looks like your logic may be flawed. The form will not necessarily pass the ID back on the URL. So update you form like so and check again if it works. It looks like the way you currently have it it will set ID to null which will create a new record.
public function index($id = 0){
if (empty($this->request->data)) {
$this->Setting->id = $id;
$this->request->data = $this->Setting->read();
} else {
if ($this->request->is('post')) {
$this->Setting->save($this->request->data);
$this->Session->setFlash('This should have saved...');
}
}
}
Well you need to know what row it is effecting (this will usually be argument to your function).
public function index() {
// Things here
}
This will create the index page for that controller.
Create an edit function like
public function edit($id = null) {
$this->Setting->id = $id;
if (!$this->Setting->exists()) {
// Exception.
}
if ($this->Setting->save($this->request->data)) {
$this->Session->setFlash(__('Saved'));
}
}
Then you can access it like http://example.com/setting/edit/45
Make sure you have primary key id column in your DB if not override the your chosen primary key in model like below.
<?php
class Test extends AppModel{
public $primaryKey = 'primarykey column name';
}
?>