Hello everyone i am using cakephp 2.x, as i am new to here, i need to encrypt my password before it stores to database
User.ctp : I am posting like this to post
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
Controller:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
Login controller:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
How can i encrypt the password file and also how can use the Model
As you are using CakePhp go with framework's best practices.
When creating new user records you can hash a password in the
beforeSave callback of your model using appropriate password hasher
class:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
You don’t need to hash passwords before calling $this->Auth->login(). The various authentication objects will hash passwords individually.
If you are using different model than User for authentication you need to define that in AppController. In your Case you need to do something like this in AppController:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
If you wish to hash your password, try this:
$hashedPassword = AuthComponent::password('original_password');
See Here :Cakephp Password Hashing.
Related
if I click on login button, it is taking empty input values since the condition is directly going into else part of cakephp.
Below is the code:
if($this->request->is('post'))
{
if(isset($this->data['Loginsubmit']))
{
if($this->data['Reg']['email']=='')
{
echo 'hii';
}
elseif( $this->data['Reg']['password']=='')
{
echo "hi";
}
else
{
$result = $this->Reg->find('list',array('conditions'=>array('email'=>$this->request->data['Reg']['email'], 'password'=>$this->request->data['Reg']['password'],'status'=>1)));
pr($result);
if(!empty($result)){
$email=$this->request->data['Reg']['email'];
$this->Session->write('Reg', $result);
$this->redirect(array('action' => 'login'));}
else{$this->Flash->error("invalid");
}
$result = $this->Reg->find('all');
$this->set('results',$result);
}
Hi please do like this:
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->fields = array(
'email' => 'email',
'password' => 'secretword'
);
}
public function login() {
if(!$this->Auth->Reg('id')){
$this->layout="login";
if ($this->request->is('post')) {
App::uses('Validation', 'Utility');
$user=0;
if(Validation::email($this->request->data['email']))
$user = $this->Reg->find('first', array(
'conditions' => array( 'Reg.email' => $this->request->data['email'],
),'recursive' => -1 ));
if($user)
{
$this->request->data['email']=$user['Reg']['email'];
}
$this->request->data=array('Reg'=>$this->request->data);
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
else
{
return $this->redirect($this->Auth->redirectUrl());
}
}
Please review & share your feedback.
Sorry to bring this topic up again, but I've searched all the answers I can on this topic, but have not found a solution(I'm very new to cakephp):
I use the password routine to hash my password
in my AppController I have:
class AppController extends Controller {
public $components = array('DebugKit.Toolbar','Session','Auth');
}
in my UsersController I have:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
// hash the password coming in from the form using Authcomponent::password
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
/** login method */
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
//redirect to page he was trying to access before login
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setflash('Invalid username or password');
}
}
}
The issue is that I cannot log back in after adding a user: I get the setflash message. The password is being hashed correctly on the MySQL database.
Any help appreciated: I'm at a loss how to debug this.
EDIT
I've tried other solutions, from the cakephp site (no success) and 2 youtube sites (no success). I have also tried plain passwords and hashed passwords (using the default and blowfish) all with the same result.
I have added the debug statements to the code as follows:
public function login() {
pr($this->request->data); //debug
if ($this->request->is('post')) { //devbug
echo ('post request');} //debug
if ($this->request->is('post')) {
debug($this->Auth->login()); //debug
debug($this->request->data); //debug
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
The array displayed using pr($this->request->data); shows the correct data, however when I use debug($this->request->data); it shows only 5 characters in the password. Could t his be the issue (or a red herring?)
result as displayed follows:
Array
(
[User] => Array
(
[username] => user
[password] => password
)
)
post request
\app\Controller\UsersController.php (line 18)
false
\app\Controller\UsersController.php (line 19)
array(
'User' => array(
'password' => '*****',
'username' => 'user'
)
)
You should try this
AppController
class AppController extends Controller {
public $components = array(
'RequestHandler','Session',
'Auth' => array(
'Autoredirect'=>false,
'loginRedirect' => array('controller' => 'users', 'action' => 'user_dashboard'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'Did you really think you are allowed to see that?',
)
);
UsersController
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setflash('Invalid username or password');
}
}
}
Try adding this line in the login function:
public function login() {
pr($this->request->data);//LINE ADDED
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setflash('Invalid username or password');
}
}
you will see what data you are passing to the form login.
You are saving an encrypted password, but when you log in your software expects an unencrypted password.
Try to put a password unencrypted to your database and it should work.
Try this here in your app controller:
public $components = array('DebugKit.Toolbar','Session','Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish',
),
)
));
If that is still not working, please post your login-form as well.
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 am current using Usermgmt Plugin for the login function and the users management. What I want to do is to redirect the specific pages based on the group_id after they login. I am current lost with the cake.
This is the code from AppController.
var $helpers = array('Form', 'Html', 'Session', 'Js', 'Usermgmt.UserAuth');
public $components = array('Session','RequestHandler', 'Usermgmt.UserAuth');
function beforeFilter(){
$this->userAuth();
}
private function userAuth(){
$this->UserAuth->beforeFilter($this);
}
This is the login function from UsersController.
public function login() {
if ($this->request -> isPost()) {
$this->User->set($this->data);
if($this->User->LoginValidate()) {
$email = $this->data['User']['email'];
$password = $this->data['User']['password'];
$user = $this->User->findByUsername($email);
if (empty($user)) {
$user = $this->User->findByEmail($email);
if (empty($user)) {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
// check for inactive account
if ($user['User']['id'] != 1 and $user['User']['active']==0) {
$this->Session->setFlash(__('Your registration has not been confirmed please verify your email or contact to Administrator'));
return;
}
$hashed = md5($password);
if ($user['User']['password'] === $hashed) {
$this->UserAuth->login($user);
$remember = (!empty($this->data['User']['remember']));
if ($remember) {
$this->UserAuth->persist('2 weeks');
}
$OriginAfterLogin=$this->Session->read('Usermgmt.OriginAfterLogin');
$this->Session->delete('Usermgmt.OriginAfterLogin');
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
$this->redirect($redirect);
} else {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
}
}
Any help is appreciated. Thank you.
If you want to redirect them somewhere else, then change the redirect line. This assumes your User model is related to a Group model and the recursive level lets your find call pull the data.
// original
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
// new redirect, eg: /groups/view/3
$redirect = array(
'controller' => 'groups',
'action' => 'view',
$user['Group']['id']
);
$this->redirect($redirect);
I am learning cakephp by myself. I tried to create a user controller with a changepassword function. It works, but I am not sure if this is the best way, and I could not googled up useful tutorials on this.
Here is my code:
class UsersController extends AppController {
var $name = 'Users';
function login() {
}
function logout() {
$this->redirect($this->Auth->logout());
}
function changepassword() {
$session=$this->Session->read();
$id=$session['Auth']['User']['id'];
$user=$this->User->find('first',array('conditions' => array('id' => $id)));
$this->set('user',$user);
if (!empty($this->data)) {
if ($this->Auth->password($this->data['User']['password'])==$user['User']['password']) {
if ($this->data['User']['passwordn']==$this->data['User']['password2']) {
// Passwords match, continue processing
$data=$this->data;
$this->data=$user;
$this->data['User']['password']=$this->Auth->password($data['User']['passwordn']);
$this->User->id=$id;
$this->User->save($this->data);
$this->Session->setFlash('Password changed.');
$this->redirect(array('controller'=>'Toners','action' => 'index'));
} else {
$this->Session->setFlash('New passwords differ.');
}
} else {
$this->Session->setFlash('Typed passwords did not match.');
}
}
}
}
password is the old password, passwordn is the new one, password2 is the new one retyped.
Is there any other, more coomon way to do it in cake?
I see that you validate and manipulate data in the controller. Doing this in a model is generally a better practice. I implemented similar functionality just a few days ago. My change_password() method looks somewhat like this:
# app/controllers/users_controller.php
function change_password() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Password has been changed.');
// call $this->redirect() here
} else {
$this->Session->setFlash('Password could not be changed.');
}
} else {
$this->data = $this->User->findById($this->Auth->user('id'));
}
}
And here's a stripped down version of the view used with that method:
# app/views/users/change_password.ctp
echo $this->Form->create('User');
echo $this->Form->input('id');
echo $this->Form->input('current_password');
echo $this->Form->input('password1');
echo $this->Form->input('password2');
echo $this->Form->end('Submit');
The code that does something interesting is in the model. I added the fields from the form to the validate property and wrote custom validation methods. This allows me to use password1 and password2 fields in any other place in the application, for example, on the registration form.
# app/models/user.php
var $validate = array(
'current_password' => array(
'rule' => 'checkCurrentPassword',
'message' => '...'
),
'password1' => array(
'rule' => 'checkPasswordStrength',
'message' => '...',
),
'password2' => array(
'rule' => 'passwordsMatch',
'message' => '...',
)
);
Finally, in the beforeSave() callback of the model I set password to the hash of password1 to prepare the data to be stored it in the database.
The solution provided by Mike is great, but he left out the "checkCurrentPassword" function. Here is an example of that function you can place in your Model:
# app/models/user.php
public function checkCurrentPassword($data) {
$this->id = AuthComponent::user('id');
$password = $this->field('password');
return(AuthComponent::password($data['current_password']) == $password);
}
This solution gets the current user ID from the Auth component and changes the model to point to that particular user. Then it compares the hash of the current_password entered on the form with the hashed password stored for that user.
Also, here is the beforeSave function you can use to hash the new password:
# app/models/user.php
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password1'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password1']);
}
return true;
}
You can use the latest version of the cakeDC plugin. This plugin gives you all functionality of all functions related to login, logout, reset password, change password, etc. You can find the latest version here.
You can simply use the:-
Step1)
$password = $this->Auth->password($this->data['User']['password']); // It will generate the hashed password using the cakephp's Auth component.
Step2)
if($this->User->update(array('User.password'=>$password), array('User.id'=>$this->Auth->User('id')))) {
echo $this->Session->setFlash('Password changed successfully.', 'default',
array('class'=>'successMsg'));
}