Advertisement
Guest User

Untitled

a guest
Aug 11th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.85 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\modules\users\controllers;
  4.  
  5. use app\components\rbac\RbacComponent;
  6. use app\services\MailService;
  7. use Yii;
  8. use app\controllers\BaseController;
  9. use yii\db\Expression;
  10. use yii\filters\AccessControl;
  11. use app\models\user\User;
  12. use app\models\user\UserSearch;
  13. use yii\web\ForbiddenHttpException;
  14. use yii\web\NotFoundHttpException;
  15. use yii\filters\VerbFilter;
  16.  
  17. /**
  18.  * Users managing controller for the `users` module
  19.  */
  20. class ManageController extends BaseController
  21. {
  22.    
  23.     /**
  24.      * @inheritdoc
  25.      */
  26.     public function behaviors()
  27.     {
  28.         return [
  29.             'verbs' => [
  30.                 'class' => VerbFilter::className(),
  31.                 'actions' => [
  32.                     'delete' => ['POST'],
  33.                     'reset' => ['POST'],
  34.                 ],
  35.             ],
  36.             'access' => [
  37.                 'class' => AccessControl::className(),
  38.                 'only' => ['index', 'view', 'create', 'update', 'delete', 'reset'],
  39.                 'rules' => [
  40.                     [
  41.                         'actions' => ['index', 'view'],
  42.                         'allow' => true,
  43.                         'roles' => [RbacComponent::VIEW_USERS_KEY],
  44.                     ],
  45.                     [
  46.                         'actions' => ['create'],
  47.                         'allow' => true,
  48.                         'roles' => [RbacComponent::CREATE_USERS_KEY],
  49.                     ],
  50.                     [
  51.                         'actions' => ['update', 'reset'],
  52.                         'allow' => true,
  53.                         'roles' => [RbacComponent::EDIT_USERS_KEY],
  54.                     ],
  55.                     [
  56.                         'actions' => ['delete'],
  57.                         'allow' => true,
  58.                         'roles' => [RbacComponent::DELETE_USERS_KEY],
  59.                     ],
  60.                 ],
  61.             ],
  62.         ];
  63.     }
  64.  
  65.     /**
  66.      * Lists all User models.
  67.      * @return mixed
  68.      */
  69.     public function actionIndex()
  70.     {
  71.         $searchModel = new UserSearch();
  72.         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
  73.  
  74.         return $this->render('index', [
  75.             'searchModel' => $searchModel,
  76.             'dataProvider' => $dataProvider,
  77.             'company' => $this->company,
  78.         ]);
  79.     }
  80.  
  81.     /**
  82.      * Displays a single User model.
  83.      * @param string $id
  84.      * @return mixed
  85.      */
  86.     public function actionView($id)
  87.     {
  88.         return $this->render('view', [
  89.             'model' => $this->findModel($id),
  90.             'company' => $this->company,
  91.         ]);
  92.     }
  93.  
  94.     /**
  95.      * Creates a new User model.
  96.      * If creation is successful, the browser will be redirected to the 'view' page.
  97.      * @return mixed
  98.      */
  99.     public function actionCreate()
  100.     {
  101.         $model = new User();
  102.  
  103.         if (Yii::$app->request->isPost) {
  104.             $load = $model->load(Yii::$app->request->post());
  105.  
  106.             if (!$model->password) {
  107.                 $password = Yii::$app->getSecurity()->generateRandomString(6);
  108.             } else {
  109.                 $password = $model->password;
  110.             }
  111.  
  112.             $model->password = $password;
  113.             $model->username = $model->email;
  114.             $model->company_id = $this->company->id;
  115.             $model->created_date = new Expression('NOW()');
  116.         } else {
  117.             $load = false;
  118.         }
  119.  
  120.         if ($load) {
  121.             if (User::find()->where("email = :email", [":email" => $model->email])->exists()) {
  122.                 \Yii::$app->session->setFlash('error', 'This email address has already been taken.');
  123.                 $load = false;
  124.             }
  125.         }
  126.  
  127.         if ($load && $model->validate()) {
  128.             $model->setPassword($password);
  129.             $model->generateAuthKey();
  130.  
  131.             if ($model->save()) {
  132.                 // Role:
  133.                 $auth = \Yii::$app->authManager;
  134.                 $auth->companyId = $this->company->id;
  135.                 $roles = RbacComponent::getRolesArray();
  136.                 $auth->assign($auth->createRole($roles[$model->role_name]), $model->getPrimaryKey());
  137.  
  138.                 // Email:
  139.                 if (Yii::$app->request->post('send_email')) {
  140.                     $mail = new MailService($model);
  141.                     $mail->invite($this->company, $password);
  142.                 }
  143.             }
  144.  
  145.             \Yii::$app->session->setFlash('success', 'The user has been created successfully.');
  146.             return $this->redirect(['view', 'id' => $model->id]);
  147.         } else {
  148.             return $this->render('create', [
  149.                 'model' => $model,
  150.                 'company' => $this->company,
  151.             ]);
  152.         }
  153.     }
  154.  
  155.     /**
  156.      * Updates an existing User model.
  157.      * If update is successful, the browser will be redirected to the 'view' page.
  158.      * @param string $id
  159.      * @return mixed
  160.      */
  161.     public function actionUpdate($id)
  162.     {
  163.         $model = $this->findModel($id);
  164.  
  165.         if (empty($_POST['User']['password'])) {
  166.             $currentPasswordHash = $model->password;
  167.             $passwordIsUpdated = false;
  168.         } else {
  169.             $currentPasswordHash = \Yii::$app->security->generatePasswordHash($_POST['User']['password']);
  170.             $passwordIsUpdated = true;
  171.         }
  172.  
  173.         if (Yii::$app->request->isPost) {
  174.             $load = $model->load(Yii::$app->request->post());
  175.         } else {
  176.             $load = false;
  177.         }
  178.  
  179.         if ($load) {
  180.             if (User::find()->where("email = :email AND id != :id", [":email" => $model->email, ":id" => $id])->exists()) {
  181.                 \Yii::$app->session->setFlash('error', 'This email address has already been taken.');
  182.                 $load = false;
  183.             }
  184.         }
  185.  
  186.  
  187.         if ($load && $model->validate()) {
  188.             $model->password = $currentPasswordHash;
  189.             $model->save();
  190.             $model->updateRole();
  191.  
  192.             if ($passwordIsUpdated) {
  193.                 $mail = new MailService($model);
  194.                 $mail->passwordChanged($this->company, $_POST['User']['password']);
  195.             }
  196.            
  197.             \Yii::$app->session->setFlash('success', 'The user has been updated successfully.');
  198.             return $this->redirect(['view', 'id' => $model->id]);
  199.         } else {
  200.             return $this->render('update', [
  201.                 'model' => $model,
  202.                 'company' => $this->company,
  203.             ]);
  204.         }
  205.     }
  206.  
  207.     /**
  208.      * Reset password.
  209.      * @param integer $id
  210.      * @return \yii\web\Response
  211.      * @throws NotFoundHttpException
  212.      */
  213.     public function actionReset($id)
  214.     {
  215.         $model = $this->findModel($id);
  216.         $error = false;
  217.  
  218.         if ($model->status_id == User::STATUS_NOT_ACTIVE) {
  219.             $error = true;
  220.             \Yii::$app->session->setFlash('error', 'The account is not active.');
  221.         }
  222.  
  223.         if ($model->password_reset_token) {
  224.             $error = true;
  225.             \Yii::$app->session->setFlash('error', 'A password restoring for this account has already been requested.');
  226.         }
  227.  
  228.         if (!$error) {
  229.             $model->generatePasswordResetToken();
  230.             $model->save();
  231.  
  232.             $mail = new MailService($model);
  233.             $mail->reset(false);
  234.  
  235.             \Yii::$app->session->setFlash('success', 'The password has been reset.');
  236.         }
  237.  
  238.         return $this->redirect(['view', 'id' => $model->id]);
  239.     }
  240.  
  241.     /**
  242.      * Deletes an existing User model.
  243.      * If deletion is successful, the browser will be redirected to the 'index' page.
  244.      * @param integer $id
  245.      * @return \yii\web\Response
  246.      * @throws ForbiddenHttpException
  247.      * @throws NotFoundHttpException
  248.      * @throws \Exception
  249.      * @throws \Throwable
  250.      */
  251.     public function actionDelete($id)
  252.     {
  253.         $model = $this->findModel($id);
  254.  
  255.         if ($model->id == $this->company->owner_id) {
  256.             throw new ForbiddenHttpException('You can not delete the owner.');
  257.         }
  258.  
  259.         $model->delete();
  260.         \Yii::$app->session->setFlash('success', 'The user has been deleted successfully.');
  261.  
  262.         return $this->redirect(['index']);
  263.     }
  264.  
  265.     /**
  266.      * Finds the User model based on its primary key value.
  267.      * If the model is not found, a 404 HTTP exception will be thrown.
  268.      * @param string $id
  269.      * @return User the loaded model
  270.      * @throws NotFoundHttpException if the model cannot be found
  271.      */
  272.     protected function findModel($id)
  273.     {
  274.         if (($model = User::find()
  275.                 ->with(['company'])
  276.                 ->where(['id' => $id, 'company_id' => Yii::$app->user->identity->company_id])
  277.                 ->one()) !== null) {
  278.             return $model;
  279.         } else {
  280.             throw new NotFoundHttpException('The requested page does not exist.');
  281.         }
  282.     }
  283.    
  284. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement