How to conditionally use different database in CodeIgniter - mysql

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 .

Related

Get data from another Database in Codeigniter MySQL

I want to get data from another DB in MySQL except the defualt DB. I added the following line into my model in addition to the excisting code. Another DB as 'storesDB'.
$this->load->database('storesDB', TRUE);
My model as follows :
public function getEquipment($id = null)
{
$this->db->select('*');
$this->db->from('tbl_equipment');
$this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
$this->db->where("tbl_equipment.status", '1');
if ($id)
$this->db->where("tbl_equipment.id", $id);
$query = $this->db->get();
return $query->result();
}
The code is working properly. But the code got data from defualt DB not the by the 'storesDB'.
Modified code is as follows :
public function getEquipment($id = null)
{
$this->load->database('storesDB', TRUE);
$this->db->select('*');
$this->db->from('tbl_equipment');
$this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
$this->db->where("tbl_equipment.status", '1');
if ($id)
$this->db->where("tbl_equipment.id", $id);
$query = $this->db->get();
return $query->result();
}
What may be the reason?
The reason is that you don't assign the second database properly. You also need to setup the correct config for the 2nd database
$config['hostname'] = "host";
$config['username'] = "user";
$config['password'] = "pass";
$config['database'] = "storesDB";
// etc..
then you load the database:
$this->db2 = load->database($config, TRUE);
now you have $this->db, the default database and $this->db2, the second database
and continue your code like:
$this->db2->select('*');
$this->db2->from('tbl_equipment');
// etc...
I have no experience in Codeigniter, but in a standar sql query you can add the database name in front of the table to get info from another db like:
SELECT * FROM sakila.actor;
Assuming you are not connected to sakila db.
Using this aproach both databases must have same credentials

Set user permissions on each module in Yii2

I would like to set user permissions on each module.
Each module would have its table with the permissions. What is the most recommended way to do this?
Reason: My application has some optional modules for only a few clients.
UPDATE
Something like:
Table: mod_inventory_permission
id int
User_id int
Read_permission boolean
Write_permission boolean
Admin_permission boolean
You can use RBAC for it! you can set different modules in it and different permission for each module.
Yes you can do it by using Rbac which facilitate you to restrict user in same application to limited modules,controllers, or actions
You have to follow the following step i hope it will help you.
I suggest you to use the auth_ tables provided by yii2 for rbac
step 1: import all auth tables
step 2: Create different roles in auth_item tables with type = 1 and all permission with type = 2
Note
Please make sure you enter your permission in some specific pattern,i am using module/controller/action,
its up to you how you are going to implement it.
step 3: Create generic controller and extend all of your controller from this generic controller,
In your generic controller you have to check whether the user is allow to access the module,controller or action he/she want to access of not.
public function beforeAction($action) {
$module = Yii::$app->controller->module->id;
$controller = ucfirst(Yii::$app->controller->id);
$action = Yii::$app->controller->action->id;
if (Yii::$app->user->can($module)) {
if (Yii::$app->user->can($module . '/' . $controller)) {
return true;
}
if (Yii::$app->user->can($module . '/' . $controller . '/' . $action)) {
return true;
}
else {
throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
}
} else {
throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
}
}
The beforeAction function implement 3 layer authentication you can change it according to your requirements....
i hope it will help you

Write database queries in Magento custom module

I created a custom module in my Magento. This is working good. My module's name is mymodule.
Mymodule.php
class Myshop_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
public function myfunction()
{
return "Hello User";
}
}
The path of the Mymodule.php file is C:\wamp\www\magento\app\code\local\Myshop\Mymodule\Block.
Now I want to display some data from database. For example I would like to display the admin's email id. How can I display this??
I tried like this.
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
//database write adapter
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $read->fetchAll("select email from admin_user where user_id= 1");
var_dump($result);
I write these lines in Mymodule.php inside myfunction. But nothing displayed(display only "Hello User").
So my question is how to display or write database queries in magento custom module.
Please someone help me..Any help is really appreciable..
We generally avoid using adapters when magento by default provides models for the basic tables. In your case, you can fetch the admin details using following :
<?php
$userDetails = Mage::getModel('admin/user')->load(1);
//where 1 is your admin user id
echo $userDetails->getEmail();
?>
Hence, your function can be modified as :
<?php
class Myshop_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
public function myfunction()
{
$userDetails = Mage::getModel('admin/user')->load(1);
return $userDetails->getEmail();
}
}
You can get data from database in magento as
$collection = Mage::getModel("mumodule/mymodule")->getCollection();
foreach($collection as $data){
..Your Code ..
}

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.

session_regenerate_id and database handler

i am using database handler for my sessions which working fine but now i stack into a problem on authentication.
When user login with username/password i do session_regenerate_id and after that i am trying to select the current session_id.
Here is my code
session_regenerate_id();
echo $checkQ=" SELECT * FROM my_sessions WHERE id='".session_id()."' ";
......
but i dont get any results. The session_id is the correct one.
After finish load the page and copy paste the SQL Command to phpMyAdmin i get the results.
I know thats its stupid but the only reason i can think of is that session_regenerate_id() "is too slow" so when i try to read the session_id at next line the session_id has not created in database yet.
Can anyone help me!
I know it has been a while, I hope you have found an answer since this was posted, but I'll add my solution for posterity's sake.
The call to session_generate_id() will cause the value of session_id() to change:
<?php
$before = session_id();
session_regenerate_id();
$after = session_id();
var_dump($before == $after); // outputs false
This problem manifested for me because in the session write handler I was doing this (without such bogus method names, of course):
<?php
class MySQLHandler
{
function read($id)
{
$row = $this->doSelectSql($id);
if ($row) {
$this->foundSessionDuringRead = true;
}
// snip
}
function write($id, $data)
{
if ($this->foundSessionDuringRead) {
$this->doUpdateSql($id, $data);
}
else {
$this->doInsertSql($id, $data);
}
}
}
The write() method worked fine if session_regenerate_id() was never called. If it was called, however, the $id argument to write() is different to the $id passed to read(), so the update won't find any records with the new $id because they've never been inserted.
Some people suggest to use MySQL's "REPLACE INTO" syntax, but that deletes and replaces the row, which plays merry havoc if you want to have a creation date column. What I did to fix the problem was to hold on to the session ID that was passed to read, then update the session ID in the database during write using the id passed to read as the key:
<?php
class MySQLHandler
{
function read($id)
{
$row = $this->doSelectSql($id);
if ($row) {
$this->rowSessionId = $id;
}
// snip
}
function write($id, $data)
{
if ($this->rowSessionId) {
$stmt = $this->pdo->prepare("UPDATE session SET session_id=:id, data=:data WHERE session_id=:rowSessionId AND session_name=:sessionName");
$stmt->bindValue(':id', $id);
$stmt->bindValue(':rowSessionId', $this->rowSessionId);
$stmt->bindValue(':data', $data);
$stmt->bindValue(':sessionName', $this->sessionName);
$stmt->execute();
}
else {
$this->doInsertSql($id, $data);
}
}
}
I think I'm having the same problem you are having. It's unclear to me whether this is a PHP (cache) feature or a bug.
The issue is that, when using a custom SessionHandler and calling session_regenerate_id(true), the new session is not created until the script terminates. I have confirmed that by doing the same thing you did: SELECTing the new session id from the database. And the new session is not there. However, after the script finishes, it is.
This is how I fixed it:
$old_id = session_id();
// If you SELECT your DB and search for $old_id, it will be there.
session_regenerate_id(TRUE);
$new_id = session_id();
// If you SELECT your DB for either $old_id or $new_id, none will be there.
session_write_close();
session_start();
// If you SELECT your DB for $new_id, it will be there.
Therefore the solution (workaround) I came about was to force PHP to write the session. I hope this helps.