I'm using Yii2 Framework and dektrium/yii2-user
module to handle authentication in restful environment.
This is my API directory structure:
api
├── config
│ ├── api.php
│ ├── bootstrap.php
│ ├── params.php
│ └── routes.php
├── index.php
├── modules
│ └── v1
│ ├── controllers
│ │ └── UserController.php
│ ├── models
│ │ └── User.php
│ └── Module.php
└── runtime
api.php
...
$config = [
...
'components' => [
'user' => [
'identityClass' => 'app\api\modules\v1\models\User',
'enableAutoLogin' => false,
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => require(__DIR__ . '/routes.php'),
],
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=DBname',
'username' => 'DBusername',
'password' => 'DBpassword',
'charset' => 'utf8'
],
],
'modules' => [
'v1' => [
'class' => 'app\api\modules\v1\Module',
'controllerNamespace' => 'app\api\modules\v1\controllers',
],
],
...
];
...
UserController.php
class UserController extends ActiveController
{
public $modelClass = 'app\api\modules\v1\models\User';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
];
return $behaviors;
}
}
User.php
use dektrium\user\models\User as Base;
class User extends Base
{
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
}
While I'm trying to make HTTP POST request by curl like this:
curl -H 'Accept:application/json' -H "Authorization: Bearer <Token>" http://<url>/api/v1/users
I get this as the result:
"name": "Exception",
"message": "Call to a member function getDb() on null",
"code": 0,
"type": "Error",
"file": "<project path>/vendor/dektrium/yii2-user/traits/ModuleTrait.php",
"line": 28,
Line 28 in ModuleTrait.php:
public static function getDb()
{
return \Yii::$app->getModule('user')->getDb();
}
When I was checking the result in each step, I found out that \Yii::$app->getModule('user')
value is null
.
Do you have any idea how to fix this error?
You do not have user
module - you could try adding a valid one:
'modules' => [
'v1' => [
'class' => 'app\api\modules\v1\Module',
'controllerNamespace' => 'app\api\modules\v1\controllers',
],
'user' => [
'class' => 'dektrium\user\Module',
'admins' => ['your_admin_username'],
'enableRegistration' => false,
'enableConfirmation' => false,
'mailer' => ['welcomeSubject' => 'welcome in my application '],
],
// ...
],
// ...