如何在yii2中使用不同的数据库创建多个登录访问?

时间:2015-02-23 08:49:48

标签: php login yii2

您好我正在为我的公司创建网络报告管理。有3个数据库登录,所以我需要制作3个不同的登录功能。问题是当登录应用程序试图与每个实现identityInterface的类找到同一性时。 例如我有

FORM A -> Login to Mysql
FORM B -> Login to Postgresql
FORM C -> Login to Mysql

当我登录使用表格A时,其他表格B和表格C也会登录。

这是我的配置

<?php

$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'defaultRoute' => 'web',
    'components' => ['urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' => [],
        ],
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'vOVnTnH6zKE10R21oPfSz81DELj0W9GK',
            'enableCsrfValidation'=>true,
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\User',
            'loginUrl' => 'site/login',
        ],
        'admin' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\web\Admin',
            'enableAutoLogin' => true,
            'loginUrl' => 'adminfaspay',
        ],
        'member' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\web\Member',
            'enableAutoLogin' => true,
            'loginUrl' => 'web/dochecklogin',
        ],
        'merchant' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\report\Merchant',
            'enableAutoLogin' => false,
            'loginUrl' => 'home/login',
        ],

        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file basename(path)y default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
        'db2' => require(__DIR__ . '/dbmssql.php'),
        'db3' => require(__DIR__ . '/dbmsorcl.php'),
        'db4' => require(__DIR__ . '/dbmsmysql.php'),
        'db5' => require(__DIR__ . '/dbposgre.php'),
    ],

    'timeZone' => 'UTC',
    'params' => $params,
    'modules' => [
        'gridview' => [
        'class' => '\kartik\grid\Module'
        // enter optional module parameters below - only if you need to
        // use your own export download action or custom translation
        // message source
        // 'downloadAction' => 'gridview/export/download',
        // 'i18n' => []
        ]
    ],
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

return $config;

我的会员.php

<?php

namespace app\models\web;
use Yii;

use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;

class Member extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public $authKey;

    public static function getDb()
    {
        return \Yii::$app->db5;  // use the "db2" application component
    }

    public static function tableName()
    {
        return 'member_merchant';
    }

    public function rules()
    {
        return [
            [['email', 'password'], 'required']
        ];
    }
    public function attributeLabels()
    {
        return [
            'id' => 'User id',
            'email' => 'Email',
            'password' => 'Password'
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
              $users = self::find()
                ->where(["id" => $id])
                ->one();
        return $users;
    }
    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($email) {

        $users = self::find()
                ->where(["email" => $email])
                ->one();

        if (!count($users)) {
            return null;
        }

        return $users;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }
}

Admin.php

<?php

namespace app\models\web;
use Yii;

use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;

class Admin extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public $authKey;

    public static function getDb()
    {
        return \Yii::$app->db5;  // use the "db2" application component
    }

    public static function tableName()
    {
        return 'admin';
    }

    public function rules()
    {
        return [
            [['username', 'password'], 'required']
        ];
    }
    public function attributeLabels()
    {
        return [
            'id' => 'User id',
            'username' => 'Username',
            'password' => 'Password'
        ];
    }
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
              $users = self::find()
                ->where(["id" => $id])
                ->one();
        return $users;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username) {

        $users = self::find()
                ->where(["username" => $username])
                ->one();

        if (!count($users)) {
            return null;
        }

        return $users;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }
}

Merchant.php

<?php

namespace app\models\report;
use Yii;

use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;

class Merchant extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public $authKey;

    public static function tableName()
    {
        return 'usys.usex';
    }

    public function rules()
    {
        return [
            [['passwd', 'user_uid'], 'required']
        ];
    }
    public function attributeLabels()
    {
        return [
            'user_uid' => 'User id',
            'username' => 'Username',
            'password' => 'Password'
        ];
    }
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
              $users = self::find()->with('userGroups')->with('userBois')
                ->where(["usex_uid" => $id])
                ->one();
        return $users;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username) {
        $users = self::find()
                ->where(["user_uid" => $username])
                ->one();

        if (!count($users)) {
            return null;
        }

        return $users;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->usex_uid;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->passwd === $password;
    }

    public function getUserGroups()
    {
        return $this->hasOne(UserGroup::className(), ['usex_uid' => 'usex_uid']);
    }

    public function getUserBois()
    {
        return $this->hasMany(UserBoi::className(), ['usex_uid' => 'usex_uid']);
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您应该专门化您的类,以便根据您希望访问的数据库返回正确的数据库实例(getDB)。 例如,您可以通过调用由各种“登录”区分的操作来执行此操作,并在此操作中将对象分配给您感兴趣的正确数据库实例。