Select doctrine config after login on Zend 1.11 - database

everybody! I'm doing an application with several databases where each one belongs to one specific department.
So, I have on my Bootstrap.php the method _initDoctrine() that initialize the connection with DB (meanwhile, i have only one).
public function _initDoctrine() {
$this->getApplication()->getAutoloader()
->pushAutoloader(array('Doctrine', 'autoload'));
spl_autoload_register(array('Doctrine', 'modelsAutoload'));
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
$manager->setAttribute(
Doctrine::ATTR_MODEL_LOADING, Doctrine::MODEL_LOADING_CONSERVATIVE
);
$manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, true);
$doctrineConfig = $this->getOption('doctrine');
Doctrine::loadModels($doctrineConfig['models_path']);
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'], 'doctrine');
$conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true);
return $conn;
}
In my login page, there's 3 options (databases) which the user will choose to connect.
So, there's anyway to init doctrine config after login??
PS: sorry my english

Related

Laravel 8 Fortify User UUID Login Problem

I am currently setting up a new project using Laravel 8. Out of the box, Laravel is configured to use auto-incrementing ID's for the user's ID. In the past I have overrode this by doing the following.
Updating the ID column in the user table creation migration to
$table->uuid('id');
$table->primary('id');
Adding the following trait
trait UsesUUID
{
protected static function bootUsesUUID()
{
static::creating(function ($model) {
$model->{$model->getKeyName()} = (string) Str::orderedUuid();
});
}
}
Adding the following to the user model file
use UsesUUID;
public $incrementing = false;
protected $primaryKey = 'id';
protected $keyType = 'uuid';
On this new project, I did the same as above. This seems to break the login functionality. When the email and password are entered and submitted, the form clears as though the page has been refreshed. Thing to note is there are no typical validation error messages returned as would be expected if the email and/or password is wrong.
To check that the right account is actually being found and the password is being checked properly, I added the following code to the FortifyServiceProvider boot method. The log file confirms that the user is found and the user object dump is correct too.
Fortify::authenticateUsing(function(Request $request) {
\Log::debug('running login flow...');
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
\Log::debug('user found');
\Log::debug($user);
return $user;
}
\Log::debug('user not found');
return false;
});
Undoing the above changes to the user model fixes the login problem. However, it introduces a new problem that is the login will be successful but it wont be the right account that is logged in. For example, there are 3 accounts, I enter the credentials for the second or third account, but no matter what, the system will always login using the first account.
Anyone have any suggestions or ideas as to what I may be doing wrong, or if anyone has come across the same/similar issue and how you went about resolving it?
Thanks.
After digging around some more, I have found the solution.
Laravel 8 now stores sessions inside the sessions table in the database. The sessions table has got a user_id column that is a foreign key to the id column in the users table.
Looking at the migration file for the sessions table, I found that I had forgot to change the following the problem.
From
$table->foreignId('user_id')->nullable()->index();
To
$table->foreignUuid('user_id')->nullable()->index();
This is because Laravel 8 by default uses auto incrementing ID for user ID. Since I had modified the ID column to the users table to UUID, I had forgotten to update the reference in the sessions table too.

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();
}

Has anyone created a DNN 7 user with the services framework?

I'm trying to create a user with the DNN 7 services framework. I've taken my working code from my custom registration module and modified to work within a DNN webapi function.
When I get to the UserController.CreateUser call in the code below I receive a
"\"There was an error generating the XML document.\""
exception. My user makes it into the aspnet_Users table and the DNN users table but does not make it into the DNN userportals table. Any ideas would be appreciated.
private void CreateUser()
{
//Update DisplayName to conform to Format
UpdateDisplayName();
User.Membership.Approved = PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration;
var user = User;
CreateStatus = UserController.CreateUser(ref user);
I finally found the issue. I was not setting the portal ID for my new users and DNN was excepting out when it was adding them to a portal. All it took was User.PortalId = 0 before the CreateUser call.
I have found by trial and error that the minimum needed to create a viable DNN user is:
UserInfo uiNewUser = new UserInfo();
uiNewUser.Username = "<myUsername>";
uiNewUser.Displayname = "<myDisplayname>";
uiNewUser.Email = "<myUserEmail>";
UserMembership newMembership = new UserMembership(uiNewUser);
newMembership.Password = "<myUserPassword>";
uiNewUser.Membership = newMembership;
uiNewUser.PortalID = <myPortalID>;
DotNetNuke.Security.Membership.UserCreateStatus uStatus;
uStatus = DotNetNuke.Security.Membership.MembershipProvider.Instance().CreateUser(ref uiNewUser);
RoleInfo newRole = RoleController.Instance.GetRoleByName(uiNewUser.PortalID, "Registered Users");
RoleController.Instance.AddUserRole(uiNewUser.PortalID, uiNewUser.UserID, newRole.RoleID, (RoleStatus)1, false, DateTime.MinValue, DateTime.MaxValue);
If any of these are missed out, parts of the user are created in the database, but the user may not be visible in the Admin list of users, or an Exception may be generated. Other details can be added later.

Yii Dynamic DB Connection according to user with master database

My project is on the basis of multi-tenent SaaS.
I have multiple clients (companies) and each client has multiple users - they all will use the same database layout.
Each client has their own database, so during user authentication, I want to Build a master database that associates the user with a company database for that user.
The structure of each database is identical... only the data is different.
So that we can keep the different database for the different company, that will not going to mix in data in database.
The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.
Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR , query builder ?
I saw this solution but not working for me http://www.yiiframework.com/forum/index.php?/topic/5385-dynamic-db-connection/
This is how my config file looks today for the script running one database, i want to call a master database that controls which database the user belongs to and the app uses in Yii, any idea?
<? php
$language = 'en';
$currencyBaseCode = 'USD';
$theme = 'default';
$connectionString = 'mysql:host=localhost;port=3306;dbname=master';
$username = 'root';
$password = 'YOUR PASS';
$memcacheServers = array( // An empty array means memcache is not used.
array(
'host' => '127.0.0.1',
'port' => 11211, // This is the default memcached port.
'weight' => 100,
),
);
$adminEmail = 'EMAIL ADDRESS';
$installed = true; // Set to true by the installation process.
$maintenanceMode = false; // Set to true during upgrade process or other maintenance tasks.
$instanceConfig = array(); //Set any parameters you want to have merged into configuration array.
//#see CustomManagement
$instanceConfig['components']['request']['hostInfo'] = 'website url';
$instanceConfig['components']['request']['scriptUrl'] = '/app/index.php';
$urlManager = array (); // Set any parameters you want to customize url manager.
? >
Define the master database in the config file, and use the normal AR class to connect to it to retrieve the credentials. Then, close the connection.
Then extend the AR class, specifically the getDbConnection() method. Get the relevant credentials, and pass them as a parameters to a new CDbConnection object.
The initial DB request to get the credentials is going to be a huge performance drag, so you should really store them in-memory with Redis or Memcached. Yii doesn't do that natively.
There are a few different ways around this:
Different front controllers loading different config files, each of which is dynamically generated or destroyed by a separate app.
One big database. Each record has a key to define which client it belongs to.
One big database. Tables can be duplicated by using a client name as part of the table name.
None of these will be easy with Yii, as this is not really something Yii was designed to do.

I can't log in in Kohana 3.2 ORM Auth module?

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();

Resources