用戶管理模塊yii2-user

引入dektrium/yii2-user的代碼

github上的託管地址:https://github.com/dektrium/yii2-user,
使用composer方式引入類php

composer require "dektrium/yii2-user:0.9.*@dev"

配置main.php的組件

請確保你沒有在你的配置文件中使用user組件配置前端

配置以下:git

'modules' => [
    'user' => [
        'class' => 'dektrium\user\Module',
    ],
],

更新數據表

$ php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations

修改視圖模板

跳轉地址使用了url美化,請確保配置了urlManager組件github

@app\views\layouts\main.php文件中將後端

if (Yii::$app->user->isGuest) {
    $menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
    $menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
    $menuItems[] = '<li>'
    . Html::beginForm(['/site/logout'], 'post')
    . Html::submitButton(
        'Logout (' . Yii::$app->user->identity->username . ')',
        ['class' => 'btn btn-link']
    )
    . Html::endForm()
    . '</li>';
}

替換爲bash

if (Yii::$app->user->isGuest) {
    $menuItems[] = ['label' => 'Sign in', 'url' => ['/user/security/login']];
    $menuItems[] = ['label' => 'Register', 'url' => ['/user/registration/register'], 'visible' => Yii::$app->user->isGuest];
} else {
    $menuItems[] = ['label' => 'Sign out (' . Yii::$app->user->identity->username . ')',
    'url' => ['/user/security/logout'],
    'linkOptions' => ['data-method' => 'post']];
}

輸入你項目網址,效果以下

yii2-user

當你註冊新用戶後,該擴展默認會發送郵件,必須郵箱驗證後才能正式登錄,若是須要修改配置參數請查閱官方文檔yii2

若是你想在一個域中使用獨立的會話,即登錄前端的session不能用來登錄後端

@frontend\config\main.php中配置項以下cookie

'components' => [
    'user' => [
        'identityCookie' => [
            'name' => '_frontendIdentity',
            'path' => '/',
            'httpOnly' => true,
        ],
    ],
    'session' => [
        'name' => 'FRONTENDSESSID',
        'cookieParams' => [
            'httpOnly' => true,
            'path' => '/',
        ],
    ],
],

@backend\config\main.php中配置項以下session

'components' => [
    'user' => [
        'identityCookie' => [
            'name' => '_backendIdentity',
            'path' => '/admin',
            'httpOnly' => true,
        ],
    ],
    'session' => [
        'name' => 'BACKENDSESSID',
        'cookieParams' => [
            'httpOnly' => true,
            'path' => '/admin',
        ],
    ],
],

錯誤排查

1.用戶登錄後,點擊註銷登錄,錯誤提示爲
After logging in I'm redirected back without any sign of being logged inapp

解決方案:在main.php 組件中修改user

'user' => [
    'class' => 'app\components\User',
    'identityClass' => 'dektrium\user\models\User',
],
相關文章
相關標籤/搜索