Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\modules\users\controllers;
- use app\components\rbac\RbacComponent;
- use app\services\MailService;
- use Yii;
- use app\controllers\BaseController;
- use yii\db\Expression;
- use yii\filters\AccessControl;
- use app\models\user\User;
- use app\models\user\UserSearch;
- use yii\web\ForbiddenHttpException;
- use yii\web\NotFoundHttpException;
- use yii\filters\VerbFilter;
- /**
- * Users managing controller for the `users` module
- */
- class ManageController extends BaseController
- {
- /**
- * @inheritdoc
- */
- public function behaviors()
- {
- return [
- 'verbs' => [
- 'class' => VerbFilter::className(),
- 'actions' => [
- 'delete' => ['POST'],
- 'reset' => ['POST'],
- ],
- ],
- 'access' => [
- 'class' => AccessControl::className(),
- 'only' => ['index', 'view', 'create', 'update', 'delete', 'reset'],
- 'rules' => [
- [
- 'actions' => ['index', 'view'],
- 'allow' => true,
- 'roles' => [RbacComponent::VIEW_USERS_KEY],
- ],
- [
- 'actions' => ['create'],
- 'allow' => true,
- 'roles' => [RbacComponent::CREATE_USERS_KEY],
- ],
- [
- 'actions' => ['update', 'reset'],
- 'allow' => true,
- 'roles' => [RbacComponent::EDIT_USERS_KEY],
- ],
- [
- 'actions' => ['delete'],
- 'allow' => true,
- 'roles' => [RbacComponent::DELETE_USERS_KEY],
- ],
- ],
- ],
- ];
- }
- /**
- * 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,
- 'company' => $this->company,
- ]);
- }
- /**
- * Displays a single User model.
- * @param string $id
- * @return mixed
- */
- public function actionView($id)
- {
- return $this->render('view', [
- 'model' => $this->findModel($id),
- 'company' => $this->company,
- ]);
- }
- /**
- * 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 (Yii::$app->request->isPost) {
- $load = $model->load(Yii::$app->request->post());
- if (!$model->password) {
- $password = Yii::$app->getSecurity()->generateRandomString(6);
- } else {
- $password = $model->password;
- }
- $model->password = $password;
- $model->username = $model->email;
- $model->company_id = $this->company->id;
- $model->created_date = new Expression('NOW()');
- } else {
- $load = false;
- }
- if ($load) {
- if (User::find()->where("email = :email", [":email" => $model->email])->exists()) {
- \Yii::$app->session->setFlash('error', 'This email address has already been taken.');
- $load = false;
- }
- }
- if ($load && $model->validate()) {
- $model->setPassword($password);
- $model->generateAuthKey();
- if ($model->save()) {
- // Role:
- $auth = \Yii::$app->authManager;
- $auth->companyId = $this->company->id;
- $roles = RbacComponent::getRolesArray();
- $auth->assign($auth->createRole($roles[$model->role_name]), $model->getPrimaryKey());
- // Email:
- if (Yii::$app->request->post('send_email')) {
- $mail = new MailService($model);
- $mail->invite($this->company, $password);
- }
- }
- \Yii::$app->session->setFlash('success', 'The user has been created successfully.');
- return $this->redirect(['view', 'id' => $model->id]);
- } else {
- return $this->render('create', [
- 'model' => $model,
- 'company' => $this->company,
- ]);
- }
- }
- /**
- * Updates an existing User model.
- * If update is successful, the browser will be redirected to the 'view' page.
- * @param string $id
- * @return mixed
- */
- public function actionUpdate($id)
- {
- $model = $this->findModel($id);
- if (empty($_POST['User']['password'])) {
- $currentPasswordHash = $model->password;
- $passwordIsUpdated = false;
- } else {
- $currentPasswordHash = \Yii::$app->security->generatePasswordHash($_POST['User']['password']);
- $passwordIsUpdated = true;
- }
- if (Yii::$app->request->isPost) {
- $load = $model->load(Yii::$app->request->post());
- } else {
- $load = false;
- }
- if ($load) {
- if (User::find()->where("email = :email AND id != :id", [":email" => $model->email, ":id" => $id])->exists()) {
- \Yii::$app->session->setFlash('error', 'This email address has already been taken.');
- $load = false;
- }
- }
- if ($load && $model->validate()) {
- $model->password = $currentPasswordHash;
- $model->save();
- $model->updateRole();
- if ($passwordIsUpdated) {
- $mail = new MailService($model);
- $mail->passwordChanged($this->company, $_POST['User']['password']);
- }
- \Yii::$app->session->setFlash('success', 'The user has been updated successfully.');
- return $this->redirect(['view', 'id' => $model->id]);
- } else {
- return $this->render('update', [
- 'model' => $model,
- 'company' => $this->company,
- ]);
- }
- }
- /**
- * Reset password.
- * @param integer $id
- * @return \yii\web\Response
- * @throws NotFoundHttpException
- */
- public function actionReset($id)
- {
- $model = $this->findModel($id);
- $error = false;
- if ($model->status_id == User::STATUS_NOT_ACTIVE) {
- $error = true;
- \Yii::$app->session->setFlash('error', 'The account is not active.');
- }
- if ($model->password_reset_token) {
- $error = true;
- \Yii::$app->session->setFlash('error', 'A password restoring for this account has already been requested.');
- }
- if (!$error) {
- $model->generatePasswordResetToken();
- $model->save();
- $mail = new MailService($model);
- $mail->reset(false);
- \Yii::$app->session->setFlash('success', 'The password has been reset.');
- }
- return $this->redirect(['view', 'id' => $model->id]);
- }
- /**
- * Deletes an existing User model.
- * If deletion is successful, the browser will be redirected to the 'index' page.
- * @param integer $id
- * @return \yii\web\Response
- * @throws ForbiddenHttpException
- * @throws NotFoundHttpException
- * @throws \Exception
- * @throws \Throwable
- */
- public function actionDelete($id)
- {
- $model = $this->findModel($id);
- if ($model->id == $this->company->owner_id) {
- throw new ForbiddenHttpException('You can not delete the owner.');
- }
- $model->delete();
- \Yii::$app->session->setFlash('success', 'The user has been deleted successfully.');
- 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 string $id
- * @return User the loaded model
- * @throws NotFoundHttpException if the model cannot be found
- */
- protected function findModel($id)
- {
- if (($model = User::find()
- ->with(['company'])
- ->where(['id' => $id, 'company_id' => Yii::$app->user->identity->company_id])
- ->one()) !== null) {
- return $model;
- } else {
- throw new NotFoundHttpException('The requested page does not exist.');
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement