Symfony2 SonataAdminBundle Password field encryption - security

I have FOSUserBundle to manage my users, and SonataAdminBundle to manage my website... I have a problem, whenever I try to change/add a password to any user, the password isn't encoded into sha512, but it does when the user register itself inside fosuserbundle registration page...
So there isn't any problem with Symfony2 configuration neither fosuserbundle config, it may be inside SonataAdminBundle somewhere, or maybe into my admin class...
<?php
// src/Acme/DemoBundle/Admin/PostAdmin.php
namespace Web\DificilBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Web;
class UserAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('firstname')
->add('lastname')
->add('username')
->add('email')
->add('password', 'password') // -> I WANT THIS TO BE ENCODED INTO SHA512!
->add('roles','choice',array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('security.role_hierarchy.roles'),'multiple'=>true ));
//->add('body')
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('firstname')
->add('lastname')
->add('username')
->add('email')
->add('password')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('firstname')
->add('lastname')
->add('username')
->add('password')
->add('email')
->add('facebookid')
->add('roles');
//->add('password', 'password')
;
}
}

Found a solution for everyone who has the same problem as me, just on your admin class, where you define your Create/Update form, use this and your password will be perfectly encrypted and ready to log into your new user ;)
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
;
}

Related

Migrating Cakephp2 Authentication to Cakephp 3

I'm moving an app from CakePHP 2 to CakePHP 3. There is a new hashing algorithm for Cake3. I'd like the existing users to be able to login to the app using their old passwords and for those passwords to then be updated to the new algorithm.
Unfortunatly, I can't get the correct hash to match up to what is in the database.
$person = $this->Auth->identify();
if(!$person){ # maybe they have old sha1 password?
$oldhash = Security::hash($this->request->data['password'],
'sha1', "oldsalt");
$person = $this->People->find()->where(['password' => $oldhash])->where(['email' =>$this->request->data['email'] ])->first();
if($person){
$person->password = Security::hash($this->request->data['password']);
$this->People->save($person);
}
}
The user is not found and if i debug the $oldhash out I get a different string than what is stored in the password field for that user.
What am I doing wrong?
Fallback classes
According to the documentation:
CakePHP provides a clean way to migrate your users’ passwords from one algorithm to another, this is achieved through the FallbackPasswordHasher class. Assuming you are migrating your app from CakePHP 2.x which uses sha1 password hashes, you can configure the AuthComponent as follows:
You will have to create an Custom Password Hasher class src/Auth/. A Custom Password hasher wil look something like this:
namespace App\Auth;
use Cake\Auth\AbstractPasswordHasher;
class LegacyPasswordHasher extends AbstractPasswordHasher {
public function hash($password)
{
return sha1($password);
}
public function check($password, $hashedPassword)
{
return sha1($password) === $hashedPassword;
} }
and then add it to passwordhasher in authenticate as fallback like this:
'authenticate' => [
'Form' => [
'passwordHasher' => [
'className' => 'Fallback',
'hashers' => [
'Default',
'Legacy'
]
]
]
]
The first name appearing in the hashers key indicates which of the classes is the preferred one, but it will fallback to the others in the list if the check was unsuccessful.
legacy is the Custom Password Hasher.
Updating the password
To update the users' password to the new hash you only have to add this code to your login procedure:
if ($this->Auth->authenticationProvider()->needsPasswordRehash()) {
$user = $this->Users->get($this->Auth->user('id'));
$user->password = $this->request->data('password');
$this->Users->save($user);
}
Documentation
More information about Changing hashing Algorithms
More information about the Custom Password Hasher
I had a CakePHP 2 app using Blowfish. Here's how I made it work with CakePHP 3:
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
// ...
'fields' => [
'username' => 'email',
'password' => 'pass', // make sure you match this with your corresponding login.ctp input name
],
// ...
'passwordHasher' => [
'className' => 'Fallback',
'hashers' => [
'Default' => ['hashType' => PASSWORD_BCRYPT],
]
],
// ...
]
],
Hope it helps someone googling this issue

how to sign up with different fields in kohana

The Model_Auth_User class in Kohana uses 'username', 'email','password' to create a new user
what if i want it to take only 'email', 'password' and also modify the validation to validate 'email_confirm' instead of 'password_confirm'
Finally i did it, All what I have to doe is to comment some lines which add the rules of validating user input
open C:\xampp\htdocs\kohana\modules\orm\classes\Model\Auth\User.php
and comment lines from 33:38 inclusive as following:
public function rules()
{
return array(
//as we don't have a username we don't need to validate it!
// 'username' => array(
// array('not_empty'),
// array('max_length', array(':value', 32)),
// array(array($this, 'unique'), array('username', ':value')),
// ),
'password' => array(
array('not_empty'),
),
'email' => array(
array('not_empty'),
array('email'),
array(array($this, 'unique'), array('email', ':value')),
),
);
}
You only keep the rules for validating what you need
Avoid changing of the system folder contents. Otherwise your changes will be lost after the next upgrade.
The more correct approach is to override the validation rules.
In file application/classes/Model/user.php:
<?php
class Model_User extends Model_Auth_User
{
public function rules()
{
$rules = parent::rules();
unset($rules['username']);
return $rules;
}
}
?>

Kohana auth model

I'm new to kohana 3.2 and i couldnt find any answer regrading the auth module.
this is my code and forsome reason ever since i changed the user model to extend model_auth_user
the validation isnt being done prooperly. The password field can be inserted empty and no excpetion will be caught and same if the password_confirm and password fields are different:
public function action_new()
{
if ($_POST){
try
{
$user = ORM::factory('user')
->values(array(
'username' => $_POST['username'],
'email' => $_POST['email'],
'password' => $_POST['password'],
'password_confirm' => $_POST['password_confirm']));
$user->save();
$user->add('roles', ORM::factory('role', array('name' => 'login')));
$this->request->redirect('user/index');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors();
}
}
$view = View::factory('user/new')
->bind('errors',$errors); //pass the info to the view
$this->response->body($view); //show the view
}
thanks
You can override run_filter() method to force Kohana ignore password filtering in case of empty value. For example, put this code to your User_Model:
protected function run_filter($field, $value)
{
if ($field === "password" AND $value === "")
return "";
parent::run_filter($field, $value);
}
Try code sample from Model_Auth_User::create_user();
$user->save(Model_User::get_password_validation($_POST)->rule('password', 'not_empty'));
This validation execute before filters(hashing password). After hashing - blank password becomes not empty string.

Kohana 3.2: Custom error message for a custom validation rule?

I am using a custom method for a validation rule in my model (using Kohana 3.2). I am following the format listed on the documentation.
// Calls A_Class::a_method($value);
array(array('A_Class', 'a_method')),
But I can't seem to figure out how to add a custom error message if the rule fails.
Any help?
For this example we will assume a modal "user" and validating the field "username"
/application/classes/model/user.php
class Model_User extends ORM
{
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('A_Class::a_method', array(':value')),
)
);
}
}
A_Class
public static function a_method($value)
{
// Validate and return TRUE or FALSE
}
/application/messages/forms/user.php
Added a forms folder so show we can select message file to load with errors. Message file matches model name (user)
return array(
'username' => array(
'not_empty' => 'Custom error message for not_empty method',
'A_Class::a_method' => 'Custom error message for you own validation rule...'
),
);
Now in your controller to validate and display the error messages
class Controller_User extends Controller
{
// User model instance
$model = ORM::factory('user');
// Set some data to the model
$model->username - 'bob';
// Try to validate and save
try
{
$model->save()
}
catch (ORM_Validation_Exception $e)
{
// Loads messages from forms/user.php
$errors = $e->errors('forms');
// See the custom error messages
echo Debug::vars($errors);
)
)

drupal 6 programmatically log user in

I'm trying to log in a user as part of a form submit, but why is the following not working:
$user = db_fetch_object(db_query("SELECT * FROM users WHERE mail = '%s' AND pass = '%s'", $mail, md5($pass)));
if ($user) {
// Authenticate user and log in
$params = array(
'name' => $user->name,
'pass' => trim($user->pass)
);
// Authenticate user
$account = user_authenticate($params);
}
if I dump $user I can see the correct values, but if I dump the account it's empty.
You are passing the hashed password to ´user_authenticate()´, while the function expects the clear password (it will hash it itself indirectly when loading the account via ´user_load()´).
So changing your $params array declaration to
$params = array(
'name' => $user->name,
'pass' => $pass
);
should make your example work.
BTW, you could use user_load() yourself to avoid querying the database directly:
$user = user_load(array('mail' => $mail, 'pass' => trim($pass), 'status' => 1));
(The 'status' => 1 will restrict results to active users - you can leave that out, of course, if you really want to allow log ins to disabled accounts ;)

Resources