0
votes

I am current writing a database access application using CakePHP (version 2.4). For security reason, I am only given the right to read the database ("data database"). Therefore, I have no choice but to use another database ("application database") for my login system and some other application data.

This is a database accessing application, over 80% of my code is related to data database and therefore I want to keep my default database connection to data database. For model written by myself, I know I can set the database to be used by:

public $useDbConnect = $applicationDatabase;

$loginDatabase is the database configuration to my application database. It is added to the configuration already.

The problem is, I was using the authComponent of Cakephp for my login system, and the default of this component is to use the default database connection. So, when I called

$this->Auth->loggedIn(); //to check if the user have logged in or not

in any controller, it gives a error code saying:

Error: Call to a member function loggedIn() on a non-object 

I found the actual problem when I called AuthComponent in my user controller:

$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);

This is the line for hash password before save (and is also used in official guide on cakephp official site.) And it gives the following error:

Missing Database Connection

Error: A Database connection using "Mysql" was missing or unable to connect.
The database server returned this error: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.

Notice: If you want to customize this error message, create app\View\Errors\missing_connection.ctp

So, back to the question: is there a way to change the database setting used for AuthComponent?

1

1 Answers

1
votes

Firstly, to resolve the Error: Call to a member function loggedIn() on a non-object, you need to add $components = array('Auth', 'Session'); to your AppController.

To answer your next question, the AuthComponent does not set a database config to authenticate a user. It will use the database table used by the 'User' model. Thus, add the following to your User.php model:

public $useDbConfig = 'loginDatabase';

Make sure you have a database with the users table populated with username and password. Also, as mentioned in your question, add the loginDatabase config correctly to the Config/database.php file.

public $loginDb = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'somehost',
    'login' => 'someusername',
    'password' => 'somepassword',
    'database' => 'login_database', //this database should have your users table
);