How can I save an automatically generated password in CakePHP? - cakephp

I am trying to automatically register users. You enter an email address and it sends the user a password. Sounds simple enough, right? Here are a bunch of things that I've tried in my add action, but none of them work (as indicated).
if (!empty($this->data)) {
$this->User->create();
$random_pass = $this->Auth->password($this->generatePassword());
// Doesn't work:
$user_data['User'] = $this->data['User'];
$user_data['User']['password'] = $random_pass;
if ($this->User->save($user_data)) { /* ... */ }
// Doesn't work:
$this->User->set('password', $random_pass);
if ($this->User->save($this->data)) { /* ... */ }
// Doesn't work:
$this->data['User']['password'] = $random_pass;
if ($this->User->save($this->data)) { /* ... */ }
// Doesn't work:
$this->data['User'][0]['password'] = $random_pass;
if ($this->User->saveAll($this->data)) { /* ... */ }
}
According to Why is the CakePHP password field is empty when trying to access it using $this->data? it's because the Auth component is removing the password. Seems common enough, no? So how do I get around it?
More information
I'm using this function to generate the password. The add view only has three fields, first_name, last_name, and email (which is assigned to the username field in the Auth component).

first of all.. you can do
$random_pass = $this->Auth->password($this->generatePassword());
pr($random_pass);
to make sure there is actually data in that variable...
then you can save that data with...
$this->data['User']['password'] = $random_pass;
$this->User->save($this->data);
Also keep in mind that... during your testing you have if (!empty($this->data))
so make sure you are actually testing by entering some form of default data somewhere in your form.

Maybe you've got some validation rules defined in your User model that are not satisfied? You can try to check this by printing $this->validationErrors (or just check your User model to see if there are any rules).

JohnP answered this question in the comments. I had some junk in the beforeSave action. Removed and now it's working perfectly. Thanks again JohnP!

I am using Cake PHP 2.3.3 and following code works for me
public function recover()
{
if ($this->request->is('post') )
{
$this->loadModel('AclManagement.User');
$passwords = AuthComponent::password($this->data['User']['password']);
$this->User->query("UPDATE users SET password = '".$passwords."' WHERE password_change = '".$this->request->data['User']['id']."' ");
$this->Session->setFlash(__('Password Saved Sucessfully'), 'success');
$this->redirect(array('action' => 'login'));
} else {
$this->set('resettoken', $_REQUEST['id']);
}
}

Related

How to create user in database manually in Yii2?

I do import of users from a csv file to the database. In csv file I have some kinda username and password string. So how do I create a new user manually?
As I understand I need to getPasswordHash and generateAuthKey (last one generates random string). But probably I loose something important since when I try to log in I get an error that Username or Password is incorrect. Did anyone ever experienced such situation? Thanks in advance.
This should be the minimum required in your case. $username and $password are raw values taken from the CSV. Remember that there will be validation applied.
$user = new User();
$user->username = $username;
$user->setPassword($password);
$user->generateAuthKey();
return $user->save();
I think you forgot to set an active status of new User. You should check it in Login method of User model in your app, or in actionLogin of SiteController. For example, in my app the login method is:
public function login()
{
if ($this->validate() and $this->getUser()->status !== User::INACTIVE_STATUS) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
If you show your code we can help you faster)
So if you are importing a list of users from a csv file, you will probably process this in a loop, try:
foreach ($csv_data as $user_data) {
$user = new User();
$user->setPassword($password);
$user->username = $user_data->username // or anything else, depending on your code
$user->status = 1 // or = User::STATUS_ACTIVE, depending on your code
$user->save();
}

CakePHP 3: How to automatically log a user in after registration

I am trying to log a user in using CakePHP 3 right after registration, but I have not been successful. This is what I am doing:
function register(){
// ....
if($result = $this->Users->save($user)){
// Retrieves corresponding user that was just saved
$authUser = $this->Users->get($result->id);
// Log user in using Auth
$this->Auth->setUser($authUser);
// Redirect user
$this->redirect('/users/account');
}
}
I guess posting this question opened my eyes to a fix. This is what I did to get it to work... if there is better way, I would be glad to change it...
function register(){
// .... Default CakePHP generated code
if($result = $this->Users->save($user)){
// Retrieve user from DB
$authUser = $this->Users->get($result->id)->toArray();
// Log user in using Auth
$this->Auth->setUser($authUser);
// Redirect user
$this->redirect(['action' => 'account']);
}
}
CakePHP 3.8 × cakephp/authentication update.
Any place you were calling AuthComponent::setUser(), you should now use setIdentity():
// Assume you need to read a user by access token
$user = $this->Users->find('byToken', ['token' => $token])->first();
// Persist the user into configured authenticators.
$this->Authentication->setIdentity($user);
Source: /authentication/1/en/migration-from-the-authcomponent.html#checking-identities

Drupal 7:User information not saving when edited by allowed users

I'm currently developping a new website for an artists organization. The administrator role is allowed to create accounts and some other node content, the created accounts have the same default role called "artisan". Administrators are Artisans as well. Artisans can create and edit their own content. Both administrators and artisans should be able to edit user profile (all for admin, only their own for artisan). The fact is admin can create a user but nobody (except user1) can save user profile after edit (but it works great for other nodes). Permissions have been scanned multiple times. I have been searching everywhere with no success, what am I missing ? I made very few changes, the only related code I wrote is the following :
<?php
function canardesign_system_form_alter(&$form, &$form_state, $form_id){
global $user;
switch ($form_id){
case 'oeuvre_node_form':
$form['actions']['submit']['#submit'][] = 'canardesign_system_oeuvre_redirect';
if (in_array('artisan', array_values($user->roles))){
$form['field_auteur']['#type']= 'hidden';
$form['field_auteur']['und']['#default_value']= $user->uid;
}
break;
case 'user_profile_form':
if (in_array('artisan', array_values($user->roles))){
$form['actions']['submit']['#submit'][] = 'canardesign_system_user_profile_form_submit';
}
break;
}
}
function canardesign_system_oeuvre_redirect($form, &$form_state) {
$type=$form['#node']->type;
if(isset($type))
{
$node = node_load($form_state['nid']);
$uid=field_get_items('node', $node, 'field_auteur')[0]['target_id'];
$form_state['redirect'] = 'oeuvres/'.$uid;
}
}
function canardesign_system_user_profile_form_submit($form, &$form_state) {
drupal_goto('artisans');
}
/*default role when administrator (who is artisan as well) creates an account*/
function canardesign_system_user_insert(&$edit, $account, $category) {
global $user;
if (in_array('artisan', array_values($user->roles))){
$account->role = 'artisan';
}
}
?>
Thank you for your help.
I'm not sure if this is the cause of your issue, but calling drupal_goto() inside a submit hook is definitely problematic. It essentially shorts out the handling of the form.
This may be causing the issue by preventing other necessary code from executing.
You should instead set the redirect key of $form_state to the destination you would like the user to end up on.
Once the form handling is complete, Drupal will send the user there.
function canardesign_system_user_profile_form_submit($form, &$form_state) {
$form_state['redirect'] = 'artisans';
}

Set random password

I'm quite new to phpCake and its principles and would like to know the cleanest solution for my requirement:
I'd like to set a random password when a new user is added.
The new user should receive an email with the password.
I see two possibilities to approach the random password:
1) Set the random password in the controller:
$this->request->data['User']['password'] = 'randomPassword';
The 'randomPassword' could be got by implementing a component.
2) The random password is set in the beforeSave method inside the user model. But how could I access this password from inside the controller then? I would need this to send the password in the email which is done inside my controller.
What is the cleaner solution? Or is there a better approach?
You'd do it on a beforeSave() callback method.
Details here: http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
You can detect if they're creating a "new" user, as opposed to updating an existing one, then, if they're new, generate a password. When the user is saved, it will have the password data in it.
// User model
public function beforeSave($options = array()) {
if(!isset($this->data['User']['id'])) {
// generate password here
}
return true;
}
Per the comments on your question, I don't think it's ideal to send the actual password, but - the above answer would work for generating a token or anything else you want to use.
$randomPassword = md5(AuthComponent::user("id));
$this->request->data['User']['password'] = $randomPassword;
This will give you a giant password, you can cut to the first 5-10 chars as u wish.
$randomPassword = $substr($randomPassword, 0,10);

Phpunit password comparison

I would like to test a login function that one of the developers produced. What I would like to do is have test-users be created in my setUp and then I would like to use these users to test the login function. I would like to see that it returns the correct boolean when username and password are equal to the ones stored in our database. My problem is that when I am inserting my users at the moment I am giving the passwords in plain-text hence they are being stored in the database in plain-text, however there is an issue here. The login function hashes the password as you are trying to log in as the passwords in the database are hashed when registration is done. So basically the plain-text password I just inserted will never be matched since the login function hashes the password in an attempt to find a match. So what I would need to do is hash the test-user's password as I insert it. How would I go about doing this? This is what my code looks like at the moment:
<?php
include 'functions.php';
class Test extends PHPUnit_Framework_TestCase {
protected function setUp(){
global $mysqli;
$mysqli = new mysqli('localhost', 'xxx', 'xxxxx', 'xxxxx');
$mysqli->query("INSERT INTO members (id, username, pnumber, password) VALUES ('200', 'testbrute', '920314', 'xxxxx')");
}
public function testLogin(){
global $mysqli;
$correctPass = Login('920314','xxxxxx', $mysqli);
$this->assertTrue($correctPass);
$wrongPass = Login('920314','xxxxxxxxx', $mysqli);
$this->assertFalse($wrongPass);
$NoUserExists = Login("980611-5298","--..--..--", $mysqli);
$this->assertFalse($NoUserExists);
}
protected function tearDown(){
$mysqli = new mysqli('localhost', 'xxx', 'xxxxx', 'xxxxx');
$mysqli->query("DELETE FROM members WHERE id IN (200)");
}
}
?>
This is what the login function looks like:
function login($pnumber, $password, $mysqli) {
// Using prepared Statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE pnumber = ? LIMIT 1")) {
$stmt->bind_param('s', $pnumber); // Bind "$pnumber" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) { // If the user exists
// We check if the account is locked from too many login attempts
if(checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return "account locked";
} else {
if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
// Password is correct!
$ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$ip_address.$user_browser);
// Login successful.
return "login successful";
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
return 'pass incorrect';
}
}
} else {
// No user exists.
return 'no exist';
}
}
}
I am new to phpunit and testing in general so please be overly-descriptive.
Forget trying to test against the actual database. As a general rule, you don't want to have your tests dependent on external services if you can help it.
You can inject a mock mysqli object and specify it's behavior. Then you don't have to worry about any values being added to the database or are dependent on having the database even exist.
So in your test rather than declaring a global $mysqli do:
$mockMysqli = $this->getMockBuilder('mysqli')
->disableOriginalConstructor()
->setMethods(array('prepare'))
->getMock();
$mockMysqli->expects($this->once())
->method('prepare')
->will($this->returnValue($mockStmt) //Have to also create a mock mysqli_stmt object
Based on how your function is, you will end up with a few mock objects returning other mock objects which is a code smell that you function is doing too much. Because of this, you would be better off breaking it up into smaller pieces that can then be mocked and tested separately. I find that generally speaking if the function is hard to test, that it is not a good design and should be refactored. Most good designs end up being easy to test with one or two mock objects.

Resources