/** **在请求交由action处理之前,判断用户属性,如果当前用户没有登录,则将页面跳转到登录页面,即该模块的所有操作都需要在用户登录状态下进行. * @param \yii\base\Action $action * @return bool|\yii\web\Response * @throws \yii\web\ForbiddenHttpException */ public function beforeAction($action) { if (!User::getCurrent()) { return Yii::$app->user->loginRequired(); } return parent::beforeAction($action); }
/** **在请求交由action处理之前,判断用户属性,如果当前用户没有登录,或者登录用户没有管理员权限,那么抛出403异常,即只有管理员才能进入该管理模块. * @param \yii\base\Action $action * @return bool * @throws HttpException */ public function beforeAction($action) { if (!User::getCurrent() || !Admin::getCurrent()) { throw new HttpException(403, 'You are not an admin'); } return parent::beforeAction($action); }
/** **显示修改账号登陆密码的表单(get),修改账号的登陆密码(post). * @return string whether or not the password has been changed successfully */ public function actionChangePassword() { if (Yii::$app->request->isGet) { $csrf = Yii::$app->request->csrfToken; return $this->render('change-password', ['csrf' => $csrf]); } $old_password = Yii::$app->request->post('old_password'); $new_password = Yii::$app->request->post('new_password'); $new_password_confirm = Yii::$app->request->post('new_password_confirm'); if (!$old_password || !$new_password || !$new_password_confirm) { AjaxResponse::fail(null, 'Three inputs are required'); } if ($new_password != $new_password_confirm) { AjaxResponse::fail(null, 'Your confirm password is different from the new password. Please try again.'); } $user = User::getCurrent(); if (!$user->validatePassword($old_password)) { AjaxResponse::fail(null, 'Your old password was incorrect. Please try again.'); } $user->setPassword($new_password); $user->save(); Yii::$app->user->logout(); AjaxResponse::success(); }