Kohana 3.3 check old password is correct before changing password - kohana-orm

Using Auth ORM, how can I tell if the old password is correct before changing the password. I have seen code for older versions of Kohana which uses the find_salt method, but this no longer applicable in version 3.3.
Any ideas?

There is a better way to do this using Validation class:
if($post = $this->request->post()) {
$user = Auth::instance()->get_user();
$validation = Validation::factory($post)
->rule('old_password', array(Auth::instance(), 'check_password'));
// Rules for password (model rules applies after hash)
$extra_rules = Validation::factory($post)
->rule('password', 'not_empty')
->rule('password', 'min_length', array(':value', 8))
->rule('password', 'matches', array(':validation', 'password', 'password_confirm'));
try {
if(!$validation->check()) {
throw new ORM_Validation_Exception('password', $validation);
}
$user->password = $post['password'];
$user->update($extra_rules);
}catch(ORM_Validation_Exception $e){
// Handle errors
}
}

Use the hash() method to hash the password string, after compare with the stored one.
$auth = Auth::instance();
$user = ORM::factory('user')
->where('username', '=', 'User')
->find();
if ($auth->hash($_POST['password']) == $user->password)
{
// Passwords match, change here.
}
else
{
// Passwords not match.
}

Related

How to conditionally use different database in CodeIgniter

Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .

How to update the changed username in session variable without logout or session destroy

Question:
How to update the changed username in session variable without logout or session destroy ?
For Example:
I am login with username "Ram" and this username storing in session variable User_Name,after logged in i am changing my username "Ram" into "Kumar". So this newly changed username should get updated in session variable User_Name automatically without logout from my account.
Sample Controller Code for Login:
function check_database($password)
{
// Field validation succeeded. Validate against database
$username = $this->input->post('username');
// query the database
$result = $this->civic_soft_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'UID' => $row->UID,
'User_Name' => $row->User_Name,
'User_Type' => $row->User_Type,
'User_OTP' => $row->User_OTP
// 'Login_Status' => $row->Login_Status
// 'Node_Id' => $row->Node_Id
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
NOTE:
I am using PHP,MySQL and CodeIgniter MVC Framework.
Please Help Me Friends...
I actually see what the problem is now. You are setting 'logged_in' to be an array. Not sure if that's common, but what I usually do is set 'logged_in' as a boolean and I set userdata the data that I need in another array.
However, for you case you can try this:
$newUserData = $this->session->userdata('logged_in');
if (is_array($newUserData)) {
$newUserData['User_Name'] = $new_username;
$this->session->set_userdata('logged_in', $newUserData);
}
For better usability, I would addd a function to $this->civic_soft_model called "updateUser" or something of that nature. And when that function is called, you can update all of the session data that you need to.
Insert this function to your controller and call it whenever there is an update made on the users information.
//$new_username : the username inputted by user when he is trying to update his account
function update_session($new_username){
$this->session->set_userdata('User_Name', $new_username);
}

Change sha1 password mysql and Cakephp log in

I'm very new to CakePHP.
I've recently taken over a project that was built in CakePHP v 1.2.4.8284.
I'm trying to change the password for the login page.
There is only one user stored in a mysql database.
fields - id, username, password(varchar 40), nacl(char(6), firstname, lastname
In phpAdmin, I've tried changing the password while using the SHA1 function, but that doesn't work.
I've even tried creating a new user, but the new user information will not work either.
I've narrowed it down to the usercontroller in the following if statement:
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password'])))
It looks like the password in the database should have sha1(nacl field) + sha1(password field).
But it is all wrapped in a sha1.
I'm not sure how the encryption is working.
Any help would be appreciated.
Thanks in advance.
Here is the complete login function.
function login()
{
$this->set('error', false);
if ($this->Session->read('user'))
{
$this->redirect('/test-folder/');
} else {
$this->User->set($this->data);
if ($this->data) {
//$results = $this->User->findByUsername($this->data['User']['username']);
$results = $this->User->find('first', array(
'conditions' => array('username' => $this->data['User']['username'])
));
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password']))) {
$this->Session->write('user', $this->data['User']['username']);
$this->Session->write('admin', $results['User']['group']);
$this->redirect('/test-folder/');
} else {
$this->set('error', true);
}
}
}
}
Get the Security.salt in Config/core.php: 'securitysaltvalue'
Take a password 'yourplainpassword'
UPDATE user SET password = SHA1( CONCAT('securitysaltvalue', 'yourplainpassword')) WHERE id = 123
According to your code, you should be able to generate a new Password with these steps:
1) Generate a Password, for example "test123"
2) Get the id of the user you want to change the password for, for example 123
3) Execute this SQL in your phpMyAdmin (Replace my demo values!!!)
UPDATE user SET password = CONCAT( SHA1(nacl), SHA1("test123")) WHERE id = 123
And please make a complete DB dump on that table before any changes. And better yet, test on some development instance.
The answer from #StefanoDP works, but the table name is 'users', not 'user'. So the command should be:
UPDATE users SET password=SHA1(CONCAT('securitysaltvalue','yourplainpassword')) WHERE id=123;
Don't forget to add the semicolon at the end of the statement.

PHP PDO - Testing connection before doing query?

public function smart_query($query, $options = null, $bindoptions = null)
{
// Code to Reconnect incase of timeout
try {
$this->db->query('SELECT * FROM templates');
}
catch (PDOException $e)
{
echo $e;
$pdooptions = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$this->db = new PDO("mysql:host=localhost;dbname=$this->database", "$this->username", "$this->password", $pdooptions);
}
$this->statement = $this->db->prepare($query);
if($bindoptions != null)
{
$this->bind($bindoptions);
}
$this->execute();
if($options != null)
{
// Return Single Row
if($options['rows'] == 1)
{
return $this->statement->fetch(PDO::FETCH_ASSOC);
}
// Return Multiple Rows
elseif($options['rows'] != 1)
{
return $this->statement->fetchAll(PDO::FETCH_ASSOC);
}
}
}
I've saw this code today, and got really confused.
It looks like he is trying to process a simple query, before doing the actual query.
Why is he checking if the connection is still open?
I thought that PDO only destroys it's connection upon script finishing executing automatically?
Is that correct to check if it's open or closed?
This implements a form of lazy loading.
This first time a query is executed through this class/function, the database connection may not be established yet. This is the purpose of this check, so that the consumer (you) does not have to mind about it.
The connection is then stored in the $this->db class member, for future reuse when you call this method again in the course of your script (and yes, this connection will stay open until the script ends -- unless it is closed explicitely beforehand, of course).
For information, this check is slightly inefficient. A simple $this->db->query('SELECT 1') would suffice, without the need to read a table at all.

Symfony 2 Console command for creating custom Database

I am working on a Symfony 2 project where each user have his own database. In my config.yml file I have a doctrine:dbal:orm set for a client but no connection properties because they are set at runtime and referenced by all users. I.e I only have one default dbal connection and two orm-connection and the amount of users is unlimited.
This works fine but I need to create the database and schema when the user is registered (FOS UserBundle). In the extended userbundle controller I can put my own logic.
The problem is that I cannot run the 'php app/console doctrine:database:create' since there are not parameters set for the new user.
Is there any way of specifying a custom database parameter to the console commands?
I could probably get around this by some very ugly mysql commands but I'd rather not.
Many thanks in advance!
You can create your own command using the code below as an outline:
namespace Doctrine\Bundle\DoctrineBundle\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\DBAL\DriverManager;
class CreateDatabaseDoctrineCommandDynamically extends DoctrineCommand
{
protected function configure()
{
$this
->setName('doctrine:database:createdynamic')
->setDescription('Creates the configured databases');
}
/**
* {#inheritDoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
/***
** Edit this part below to get the database configuration however you want
**/
$connectionFactory = $this->container->get('doctrine.dbal.connection_factory');
$connection = $connectionFactory->createConnection(array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => '',
'host' => 'localhost',
'dbname' => 'foo_database',
));
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path'] : $params['dbname'];
unset($params['dbname']);
$tmpConnection = DriverManager::getConnection($params);
// Only quote if we don't have a path
if (!isset($params['path'])) {
$name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
$error = false;
try {
$tmpConnection->getSchemaManager()->createDatabase($name);
$output->writeln(sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name));
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
$error = true;
}
$tmpConnection->close();
return $error ? 1 : 0;
}
}