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.
Related
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();
}
I created a CRUD that allows me to create users, societies and schools in a back office.
However, for an unknown reason, I can't log in with a created user with the password I gave him.
Here is my controller (the part where the user is created)
/**
* Creates a new User entity.
*
* #Route("/new", name="user_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$user = new User();
$form = $this->createForm('UserBundle\Form\UserType', $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPassword());
$user->setPassword($password);
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_show', array('id' => $user->getId()));
}
return $this->render('user/new.html.twig', array(
'user' => $user,
'form' => $form->createView(),
));
}
After registering a new user, when I check it in the fos_user table, I can see that the password has been encrypted. However, if I try to login with the password I used, I simply get "bad credential" from my login form.
I can't figure out why.
Tell me if you need to see another file, I'll update my question
Any idea ?
Thank you in advance
The correct way to create user and set password in FOSUserBundle is the following:
$userManager = $this->container->get('fos_user.user_manager');
$userAdmin = $userManager->createUser();
$userAdmin->setUsername('System');
$userAdmin->setEmail('system#example.com');
$userAdmin->setPlainPassword('test');
$userAdmin->setEnabled(true);
$userManager->updateUser($userAdmin, true);
Password is kept encrypted in database. And to make it harder to bruteforce, database contains an additional field, named salt. You don't store it in your code, that's why it's impossible later to check password. But actually, you don't have to encrypt password and store it in database. User model contains a special method for it, setPlainPassword, which is intended to encrypt password populate both fields salt and password in database with correct values.
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);
Well, thats a trouble. The code is simple:
public function action_index()
{
$post = $this->request->post();
if ($post) {
// if I type it like this, manually - it will work
$success = Auth::instance()->login('admin','password');
}
if (isset($success) and $success) { echo "Пользователь залогинен"; }
}
Unfortunately it log in only a first record in the database, which is admin as by default config was in the table, If I create a new user. Like this:
$auth = Auth::instance();
$user = new Model_User();
$user->username = "Victor";
$user->$auth->hash_password('psw123');
$user->email = "me#email.com";
$user->save();
And than use it like I said, only with a real data as
$post["email"] or $post["username"] with $post["password"]
code:
if ($post) {
// the values from posts: 'Victor' or 'me#email.com` & 'psw123'
$success = Auth::instance()->login('me#email.com','psw123');
}
it will not log in me.
upd I can't login as admin, but all working perfectly if I'll change the role to login (it's 1 in the database). But if the role will be set to 2 (it's an admin role) it will not accept me, even do not make an instance of Auth.
$post = $this->request->post();
$success = Auth::instance()->login($post['email'], $post['pass']);
if ($success)
{
echo "SUCCESS!";
}
Once again, if the role will be 2 (it means admin) this is not will Success me instead of login role.
What can be a reason of this trouble?
I'm assuming you're using a default ORM auth driver. You don't need to hash your password when saving a new user - it is done automatically by a filter in the model. So saving a new user should look something like that:
$user = ORM::factory("user");
$user->username = "Victor";
$user->password = "psw123";
$user->email = "me#email.com";
$user->save();
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']);
}
}