PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/protected/modules/users/controllers/UserController.php

https://bitbucket.org/graaaf/erso
PHP | 338 lines | 278 code | 60 blank | 0 comment | 35 complexity | 232b6e02a7aeaf06c3ac248eaa6b98db MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, LGPL-2.1, BSD-3-Clause, BSD-2-Clause
  1. <?php
  2. class UserController extends BaseController
  3. {
  4. public $layout = '//layouts/content';
  5. const ERROR_PASSWORD_RECOVER_AUTH = 'Вы не можете восстановить пароль будучи авторизованным!';
  6. public function filters()
  7. {
  8. return array('accessControl');
  9. }
  10. public function accessRules()
  11. {
  12. return array(
  13. array(
  14. 'deny',
  15. 'actions' => array(
  16. 'ActivateAccountRequest',
  17. 'ChangePasswordRequest',
  18. 'ActivateAccount',
  19. 'Registration',
  20. 'ChangePassword',
  21. 'Login'
  22. ),
  23. 'users' => array('@')
  24. )
  25. );
  26. }
  27. public static function actionsTitles()
  28. {
  29. return array(
  30. "Login" => "Авторизация",
  31. "Logout" => "Выход",
  32. "Registration" => "Регистрация",
  33. "ActivateAccount" => "Активация аккаунта",
  34. "ActivateAccountRequest" => "Запрос на активацию аккаунта",
  35. "ChangePassword" => "Смена пароля",
  36. "ChangePasswordRequest" => "Запрос на смену пароля",
  37. );
  38. }
  39. public function loadModel($id)
  40. {
  41. $model = User::model()->findByPk((int)$id);
  42. if ($model === null)
  43. {
  44. $this->pageNotFound();
  45. }
  46. return $model;
  47. }
  48. protected function performAjaxValidation($model)
  49. {
  50. if (isset($_POST['ajax']))
  51. {
  52. echo CActiveForm::validate($model);
  53. Yii::app()->end();
  54. }
  55. }
  56. public function actionLogin()
  57. {
  58. $model = new User(User::SCENARIO_LOGIN);
  59. $form = new BaseForm('users.LoginForm', $model);
  60. if (isset($_POST['User']['email']) && isset($_POST['User']["password"]))
  61. {
  62. $model->attributes = $_POST['User'];
  63. if ($model->validate())
  64. {
  65. $identity = new UserIdentity($model->email, $model->password);
  66. if ($identity->authenticate())
  67. {
  68. $this->redirect('/');
  69. }
  70. else
  71. {
  72. $auth_error = $identity->errorCode;
  73. if ($auth_error == UserIdentity::ERROR_NOT_ACTIVE)
  74. {
  75. $auth_error .= "<br/><a href='".$this->url('activateAccountRequest')."'>
  76. Мне не пришло письмо, активировать аккаунт повторно
  77. </a>";
  78. }
  79. else if ($auth_error == UserIdentity::ERROR_UNKNOWN)
  80. {
  81. $auth_error .= "<br/><a href='".$this->url('changePasswordRequest')."'>
  82. Восстановить пароль
  83. </a>";
  84. }
  85. }
  86. }
  87. }
  88. $this->render('login', array(
  89. 'form' => $form,
  90. 'auth_error' => isset($auth_error) ? $auth_error : null
  91. ));
  92. }
  93. public function actionLogout()
  94. {
  95. Yii::app()->user->logout();
  96. $this->redirect(Yii::app()->homeUrl);
  97. }
  98. public function actionRegistration()
  99. {
  100. Setting::model()->checkRequired(array(
  101. User::SETTING_REGISTRATION_MAIL_BODY,
  102. User::SETTING_REGISTRATION_MAIL_SUBJECT,
  103. User::SETTING_REGISTRATION_DONE_MESSAGE
  104. ));
  105. $user = new User(User::SCENARIO_REGISTRATION);
  106. $form = new BaseForm('users.RegistrationForm', $user);
  107. if (isset($_POST['User']))
  108. {
  109. $user->attributes = $_POST['User'];
  110. if ($user->validate())
  111. {
  112. $user->nativePassword = $user->password;
  113. $user->password = md5($user->password);
  114. $user->generateActivateCode();
  115. $user->save(false);
  116. $assignment = new AuthAssignment();
  117. $assignment->itemname = AuthItem::ROLE_DEFAULT;
  118. $assignment->userid = $user->id;
  119. $assignment->save();
  120. $user->sendNoticeEmail(User::EMAIL_EVENT_TYPE_REGISTRATION);
  121. Yii::app()->user->setFlash('done', Setting::model()->getValue(User::SETTING_REGISTRATION_DONE_MESSAGE));
  122. $this->redirect($_SERVER['REQUEST_URI']);
  123. }
  124. }
  125. $this->render('registration', array('form' => $form));
  126. }
  127. public function actionActivateAccount($code, $email)
  128. {
  129. $user = User::model()->findByAttributes(array('activate_code' => $code));
  130. if ($user && md5($user->email) == $email)
  131. {
  132. if (strtotime($user->date_create) + 24 * 3600 > time())
  133. {
  134. $user->activate_date = null;
  135. $user->activate_code = null;
  136. $user->status = User::STATUS_ACTIVE;
  137. $user->save();
  138. Yii::app()->user->setFlash('acrivate_done', 'Активация аккаунта прошла успешно! Вы можете авторизоваться.');
  139. $this->redirect('/login');
  140. }
  141. else
  142. {
  143. $activate_error = 'С момента регистрации прошло больше суток!';
  144. }
  145. }
  146. else
  147. {
  148. $activate_error = 'Неверные данные активации аккаунта!';
  149. }
  150. $this->render('activateAccount', array(
  151. 'activate_error' => isset($activate_error) ? $activate_error : null
  152. ));
  153. }
  154. public function actionActivateAccountRequest()
  155. {
  156. $model = new User(User::SCENARIO_ACTIVATE_REQUEST);
  157. $form = new BaseForm('users.ActivateRequestForm', $model);
  158. if (isset($_POST['User']))
  159. {
  160. $model->attributes = $_POST['User'];
  161. if ($model->validate())
  162. {
  163. $user = $model->findByAttributes(array('email' => $_POST['User']['email']));
  164. if (!$user)
  165. {
  166. $error = UserIdentity::ERROR_UNKNOWN;
  167. }
  168. else
  169. {
  170. switch ($user->status)
  171. {
  172. case User::STATUS_NEW:
  173. $user->generateActivateCode();
  174. $user->save();
  175. $user->sendActivationMail();
  176. Yii::app()->user->setFlash('done', 'На ваш Email отправлено письмо с дальнейшими инструкциями.');
  177. $this->redirect($this->url('activateAccountRequest'));
  178. break;
  179. case User::STATUS_ACTIVE:
  180. $error = UserIdentity::ERROR_ALREADY_ACTIVE;
  181. break;
  182. case User::STATUS_BLOCKED:
  183. $error = UserIdentity::ERROR_BLOCKED;
  184. break;
  185. }
  186. }
  187. }
  188. }
  189. $this->render('activateAccountRequest', array(
  190. 'form' => $form,
  191. 'error' => isset($error) ? $error : null
  192. ));
  193. }
  194. public function actionChangePasswordRequest()
  195. {
  196. Setting::model()->checkRequired(array(
  197. User::SETTING_CHANGE_PASSWORD_REQUEST_MAIL_SUBJECT,
  198. User::SETTING_CHANGE_PASSWORD_REQUEST_MAIL_BODY
  199. ));
  200. $model = new User(User::SCENARIO_CHANGE_PASSWORD_REQUEST);
  201. $form = new BaseForm('users.ChangePasswordRequestForm', $model);
  202. if (isset($_POST['User']))
  203. {
  204. $model->attributes = $_POST['User'];
  205. if ($model->validate())
  206. {
  207. $user = $model->findByAttributes(array('email' => $model->email));
  208. if ($user)
  209. {
  210. if ($user->status == User::STATUS_ACTIVE)
  211. {
  212. $user->nativePassword = User::generateNewPassword();
  213. $user->password = md5($user->nativePassword);
  214. $user->password_recover_date = new CDbExpression('NOW()');
  215. $user->save();
  216. $user->sendNoticeEmail(User::EMAIL_EVENT_TYPE_CHANGE_PASSWORD);
  217. Yii::app()->user->setFlash('done', 'На Ваш адрес электронной почты был выслан пароль.');
  218. $this->redirect($this->url('changePasswordRequest'));
  219. }
  220. else if ($user->status == User::STATUS_NEW)
  221. {
  222. $error = UserIdentity::ERROR_NOT_ACTIVE;
  223. }
  224. else
  225. {
  226. $error = UserIdentity::ERROR_BLOCKED;
  227. }
  228. }
  229. else
  230. {
  231. $error = UserIdentity::ERROR_UNKNOWN;
  232. }
  233. }
  234. }
  235. $this->render("changePasswordRequest", array(
  236. 'form' => $form,
  237. 'error' => isset($error) ? $error : null
  238. ));
  239. }
  240. public function actionChangePassword($code, $email)
  241. {
  242. $model = new User(User::SCENARIO_CHANGE_PASSWORD);
  243. $form = new BaseForm('users.ChangePasswordForm', $model);
  244. $user = User::model()->findByAttributes(array('password_recover_code' => $code));
  245. if (!$user || md5($user->email) != $email)
  246. {
  247. $error = 'Неверная ссылка изменения пароля!';
  248. }
  249. else
  250. {
  251. if (strtotime($user->password_recover_date) + 24 * 3600 > time())
  252. {
  253. if (isset($_POST['User']))
  254. {
  255. $model->attributes = $_POST['User'];
  256. if ($model->validate())
  257. {
  258. $user->password_recover_code = null;
  259. $user->password_recover_date = null;
  260. $user->password = md5($_POST['User']['password']);
  261. $user->save();
  262. Yii::app()->user->setFlash('change_password_done', 'Ваш пароль успешно изменен, вы можете авторизоваться!');
  263. $this->redirect('/login');
  264. }
  265. }
  266. }
  267. else
  268. {
  269. $error = 'С момента запроса на восстановление пароля прошло больше суток!';
  270. }
  271. }
  272. $this->render('changePassword', array(
  273. 'model' => $model,
  274. 'form' => $form,
  275. 'error' => isset($error) ? $error : null
  276. ));
  277. }
  278. }