簡體   English   中英

如何在yii2中使用不同的數據庫創建多個登錄訪問?

[英]How to create multiple login access with different database in yii2?

您好我正在為我的公司創建Web報告管理。 有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']);
    }
}

我認為你應該專門化你的類,以便根據你想訪問的數據庫返回正確的數據庫實例(getDB)。 例如,您可以通過調用由各種“登錄”區分的操作來執行此操作,並在此操作中將對象分配給您感興趣的正確數據庫實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM