簡體   English   中英

如何驗證用戶是代理還是管理員 yii2

[英]How to verify if the user is agent or administrator yii2

我為用戶制作了表格:PK - ID、用戶名、密碼、狀態、角色對於我在模型中聲明的角色 const ROLE_ADMIN = 1, const ROLE_VISITOR = 2;

如果用戶是管理員,我想允許登錄,如果用戶是訪客,我想拒絕登錄。 我將導入所有用戶,但只有少數用戶可以訪問該應用程序,因此我想拒絕任何其他用戶的登錄。

為了這

[
  'allow' => true,
  'roles' => ['@'],
],

我應該在哪里聲明要使用的函數而不是'allow' => true, 'allow'=>function並驗證是否$this->role == 1

提前感謝您提出任何建議。

控制器 :

<?php

namespace app\controllers;

use Yii;
use app\models\User;
use app\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UsersController implements the CRUD actions for User model.
 */
class UsersController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],      
        ];
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new User();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

模型:

<?php

namespace app\models;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $username
 * @property string $password
 * @property int $status
 * @property int $role
 *
 * @property Equipment[] $equipments
 * @property UserEquipmentMapping[] $userEquipmentMappings
 */
class User extends ActiveRecord implements IdentityInterface 
{
    /**
     * {@inheritdoc}
     */

    const STATUS_AVAILABLE = 1;
    const STATUS_DISABLED = 2;

    const ROLE_ADMIN = 1;
    const ROLE_VISITOR = 2;

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

    /**
     * {@inheritdoc}
     */


    public function rules()
    {
        return [
            [['username', 'password', 'status', 'role'], 'required'],
            [['status', 'role'], 'integer'],
            [['username', 'password'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'status' => 'Status',
            'role' => 'Role',
        ];
    }

    /**
     * Gets query for [[Equipments]].
     *
     * @return \yii\db\ActiveQuery|EquipmentQuery
     */
    public function getEquipments()
    {
        return $this->hasMany(Equipment::className(), ['user_for_id' => 'id']);
    }

    /**
     * Gets query for [[UserEquipmentMappings]].
     *
     * @return \yii\db\ActiveQuery|UserEquipmentMappingQuery
     */
    public function getUserEquipmentMappings()
    {
        return $this->hasMany(UserEquipmentMapping::className(), ['user_id' => 'id']);
    }

    /**
     * {@inheritdoc}
     * @return UserQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new UserQuery(get_called_class());
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findByUsername($username)
    {
        #$u  =  static::findOne($username);#
        #print_r($username);die;
    
        $u = User::find()
            ->where(['username' => $username])
            ->one();
        
        return $u;
    }

    public function getUsername()
    {
        #$u = User::find()
        #   ->where(['username' => $username])
        #   ->one();
        
        return $this->username;
        #return $this->hasOne(User::className(), ['username' => 'username_id']);
    }

        public function getAuthKey()
    {
        
    }

    /**
     * @inheritdoc
     */

    public function getId()
    {
        return $this->id;
    }

    public function getRole(){
        return $this->role;
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
     
    }

    public function validateAuthKey($authKey)
    {
       
    }

    public function validatePassword($password)
    {

        return $this->password === $password;
    }
    
/*  public function rules()
    {
        return array(
            array('last_name','first_name','age','username','password', 'safe'),
        );
    }
    */
}

如果您試圖允許一組“普通”用戶的操作和一組管理員的操作,那么可能值得查看高級模板,它允許您在前端和后端分別分配權限。 但是,如果我理解您對此答案的第一個版本的評論,那么您實際上打算從另一個上下文(Active Directory)導入一組完整的用戶,然后授予其中一些對您的 Yii2 應用程序的管理員訪問權限.

你說如果用戶是admin,你想允許登錄,或者如果用戶是visitor,你要拒絕登錄,這仍然有點含糊不清。 您實際上不是說非管理員只是客人(Yii 使用的術語)嗎?

如果訪問者無法登錄,則無法將他們彼此區分開來,您不需要 - 事實上我建議您可能不應該 - 將他們與管理員放在同一張表中。 您可能會更好地簡單地將登錄名分配給您的管理員,並使用您在上面發布的代碼來控制這些:1) 一個用於操作的控制器和 2) 您的身份界面,以及 /models/LoginForm.php。

然后,您將為 Active Directory 用戶創建一個單獨的表,並帶有自己的模型、視圖和控制器,您可以在其中授予管理員權限以對這些記錄執行 CRUD 功能。

您需要在其中一個控制器中執行一個操作來顯示登錄表單,並且基本模板中有一個現成的操作,其模型為 models/LoginForm.php,是您最容易編寫/更改代碼的地方登錄管理員(並可能忽略“普通”用戶/訪問者)。 但是,如果您將表格分開,它將開箱即用 - 因為只有您的管理員才會在它引用的表格中。

然后您可以使用控制器中的行為來允許或拒絕對不同級別的用戶(角色)的訪問。 這是一個很好的教程在這里 請注意,Guest 的行為語法是一個問號(與經過身份驗證的用戶的@ 符號相反)。 這里的一個很好的提示是不要在同一個控制器中混合公開可見和僅限管理員的操作,因為它簡化了必要的行為代碼。

我建議的最后一件事是,如果您要使用權限層次結構,您應該按照與您使用的順序相反的順序重新排列您的用戶權限級別(常量) - 值越高,權限越大. 我傾向於使用 7 級系統(實際上是 6 + 1,其中 0 是沒有任何權限,6 是超級用戶),但與一組系統結合使用,以便用戶對每個系統都有權限。 這對於我構建或使用的每個系統來說已經足夠了,但是對於您的需求來說聽起來有些過分。

總之,聽起來您可以通過 IdentityInterface 使用的表中的管理員、不同表中的 Active Directory 用戶以及簡單的來賓/身份驗證用戶描述來實現您想要的。

暫無
暫無

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

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