Created
January 11, 2017 15:18
-
-
Save notgosu/a175475421e611d501aa7601b0b676a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Author: Pavel Naumenko | |
*/ | |
namespace console\controllers; | |
use common\models\User; | |
use yii\base\InvalidConfigException; | |
use yii\console\Controller; | |
use yii\rbac\DbManager; | |
use yii\rbac\Role; | |
/** | |
* Class UserController | |
* @package console\controllers | |
*/ | |
class UserController extends Controller | |
{ | |
/** | |
* @param $email | |
* @param $name | |
* @param $password | |
* @throws \yii\base\Exception | |
*/ | |
public function actionCreate($email, $name, $password) { | |
$user = new User(); | |
$user->setAttributes( | |
[ | |
'username' => $name, | |
'auth_key' => \Yii::$app->security->generateRandomString(), | |
'password_hash' => \Yii::$app->security->generatePasswordHash($password), | |
'password_reset_token' => \Yii::$app->security->generateRandomString() . '_' . time(), | |
'email' => $email, | |
'status' => \common\models\User::STATUS_ACTIVE, | |
'created_at' => time(), | |
'updated_at' => time(), | |
], | |
false | |
); | |
if ($user->save()) { | |
$authManager = $this->getAuthManager(); | |
\Yii::$app->db->createCommand()->insert($authManager->assignmentTable, [ | |
'item_name' => \common\models\User::ROLE_USER, | |
'user_id' => $user->id, | |
'created_at' => time(), | |
])->execute(); | |
echo "Created\n"; | |
} else { | |
echo "Failed\n"; | |
} | |
} | |
/** | |
* @param $userId | |
* @throws InvalidConfigException | |
* @throws \yii\db\Exception | |
*/ | |
public function actionSetAdminRole($userId) { | |
$user = User::findOne($userId); | |
$authManager = $this->getAuthManager(); | |
\Yii::$app->db->createCommand()->update($authManager->assignmentTable, | |
['item_name' => \common\models\User::ROLE_ADMIN], | |
['user_id' => $user->id] | |
)->execute(); | |
} | |
/** | |
* @param $role | |
* @param $userId | |
* | |
* @return mixed | |
*/ | |
public function assignRole($userId, $role) | |
{ | |
$assignment = $this->getAuthManager()->getAssignment($role->name, $userId); | |
if (!$assignment) { | |
return $this->getAuthManager()->assign($role, $userId); | |
} | |
return $assignment; | |
} | |
/** | |
* @throws yii\base\InvalidConfigException | |
* @return DbManager | |
*/ | |
protected function getAuthManager() | |
{ | |
$authManager = \Yii::$app->getAuthManager(); | |
if (!$authManager instanceof DbManager) { | |
throw new InvalidConfigException('You should configure "authManager" component to use database before executing this migration.'); | |
} | |
return $authManager; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment