Permalink
Browse files

registration + email confirm

  • Loading branch information...
1 parent 562df53 commit a9c4ecc9a5928322dd0ac32a31809535e56445dc @studentIvan committed May 10, 2012
View
@@ -119,5 +119,6 @@
),
'sessions' => true,
'users' => true,
+ 'email_confirm' => true,
),
);
View
@@ -6,16 +6,22 @@
* sendmail
* native
*/
- 'used_transport' => 'native',
+ 'used_transport' => 'smtp',
/**
* Configuration for smtp
*/
- 'smtp' => array(
+ /*'smtp' => array(
'host' => 'example.com:25', // server:port
'username' => 'admin@example.com',
'password' => 'example',
'encryption' => null, // 'encryption' => 'ssl'
+ ),*/
+ 'smtp' => array(
+ 'host' => 'smtp.yandex.ru:25', // server:port
+ 'username' => 'php.batman@yandex.ru',
+ 'password' => 'batman.php',
+ 'encryption' => null,
),
/**
@@ -36,9 +42,14 @@
* VCard for Mailer::createMessage function
* $mailer->setFrom($email => "$firstName $lastName");
*/
- 'v_card' => array(
+ /*'v_card' => array(
'email' => 'admin@example.com',
'first_name' => 'Admin',
'last_name' => 'Example',
+ ),*/
+ 'v_card' => array(
+ 'email' => 'php.batman@yandex.ru',
+ 'first_name' => 'Batman',
+ 'last_name' => 'Php',
),
);
View
@@ -9,7 +9,7 @@ class GDCaptcha
public static function checkCorrect($input)
{
$token = Session::getToken();
- if ($input == Database::getSingleResult("SELECT phrase FROM captcha WHERE token='$token'")) {
+ if (strtoupper($input) == Database::getSingleResult("SELECT phrase FROM captcha WHERE token='$token'")) {
Database::getInstance()
->query("DELETE FROM captcha WHERE token='$token'");
return true;
@@ -185,14 +185,10 @@ public static function show(
imagesetstyle($image, $style);
foreach(range(1, $lines) as $i) {
- $what = rand(1, 100);
- if ($what > 50) {
- imageline($image, rand(2, $width - 2), rand(2, $height - 2),
- rand(2, $width - 2), rand(2, $height - 2), IMG_COLOR_STYLED);
- } else {
- imageline($image, rand(2, $width - 2), rand(2, $height - 2),
- rand(2, $width - 2), rand(2, $height - 2), $textThemes[rand(0, $textThemesCount)]);
- }
+ imageline($image, rand(2, $width - 2), rand(2, $height - 2),
+ rand(2, $width - 2), rand(2, $height - 2),
+ ((rand(1, 100) > 50) ? IMG_COLOR_STYLED :
+ $textThemes[rand(0, $textThemesCount)]));
}
header('Content-Type: image/png');
@@ -36,7 +36,6 @@ CREATE TABLE `captcha` (
LOCK TABLES `captcha` WRITE;
/*!40000 ALTER TABLE `captcha` DISABLE KEYS */;
-INSERT INTO `captcha` VALUES ('d30f9338c1a4822d5c0b6e076b2a255a','U8TNG');
/*!40000 ALTER TABLE `captcha` ENABLE KEYS */;
UNLOCK TABLES;
@@ -208,7 +207,7 @@ CREATE TABLE `users_data` (
LOCK TABLES `users_data` WRITE;
/*!40000 ALTER TABLE `users_data` DISABLE KEYS */;
-INSERT INTO `users_data` VALUES (1,'studentIvan','Иван Маслов','cryptox3@gmail.com',NULL,'m','1992-03-12','{\"test\":null}');
+INSERT INTO `users_data` VALUES (1,'studentIvan','Иван Маслов',NULL,NULL,'m','1992-03-12','{\"test\":null}');
/*!40000 ALTER TABLE `users_data` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
@@ -221,4 +220,4 @@ UNLOCK TABLES;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
--- Dump completed on 2012-05-09 2:49:00
+-- Dump completed on 2012-05-10 20:24:40
@@ -30,6 +30,37 @@ public static function viewProfile($matches)
}
}
+ public static function activate($matches)
+ {
+ if (!(isset(Process::$context['cms']['email_confirm']) and
+ Process::$context['cms']['email_confirm'])) {
+ throw new NotFoundException();
+ }
+
+ $key = $matches[1];
+ $login = $matches[2];
+
+ try {
+ $user = UserProfile::loadFromLogin($login);
+ } catch (Exception $e) {
+ throw new ForbiddenException();
+ }
+
+ if (
+ $data = $user->getNonIndexedData() and
+ isset($data['email_confirm']) and !$data['email_confirm'] and
+ isset($data['email_confirm_key']) and $data['email_confirm_key'] and
+ $data['email_confirm_key'] === $key
+ ) {
+ unset($data['email_confirm_key']);
+ $data['email_confirm'] = true;
+ $user->setNonIndexedData($data)->save();
+ Process::redirect('/');
+ } else {
+ throw new ForbiddenException();
+ }
+ }
+
public static function register()
{
Process::$context['page_title'] = 'Регистрация';
@@ -41,8 +72,53 @@ public static function register()
"e7a9fg0h790awf$formCode", "cydas89gfy8431sas$formCode"
);
- if ($login and $password and $passwordRepeat and $email and $captcha) {
+ if ($login and $password and $passwordRepeat and $email and $captcha)
+ {
+ try
+ {
+ Process::load('GDCaptcha');
+
+ if (!GDCaptcha::checkCorrect($captcha)) {
+ throw new InvalidArgumentException("Неверно введён код с картинки");
+ }
+ $user = new UserProfile();
+ $user->setLogin($login);
+ $user->setPassword($password, $passwordRepeat);
+ $user->setEmail($email);
+ $user->setRole(3);
+
+ if (isset(Process::$context['cms']['email_confirm']) and
+ Process::$context['cms']['email_confirm'])
+ {
+ $user->setNonIndexedData(array(
+ 'email_confirm' => false,
+ 'email_confirm_key' => Registration::getActivationKey($user),
+ ));
+ }
+
+ if ($user->save())
+ {
+ Process::$context['complete'] = true;
+ if (isset(Process::$context['cms']['email_confirm']) and
+ Process::$context['cms']['email_confirm']) {
+ if (!Registration::sendConfirmationEmail($user)) {
+ $user->remove();
+ throw new InvalidArgumentException("Не удалось отправить письмо подтверждения");
+ }
+ }
+ }
+ else
+ {
+ throw new InvalidArgumentException("Ошибка сервера, попробуйте позднее");
+ }
+ }
+ catch (InvalidArgumentException $e) {
+ Process::$context['flash_error'] = $e->getMessage();
+ Process::$context['x_login'] = $login;
+ Process::$context['x_email'] = $email;
+ Process::$context['rrr'] = rand(111,999);
+ }
}
}
@@ -26,19 +26,36 @@ public static function sendConfirmationEmail(UserProfile $user)
);
}
- /**
- * TODO: FUCKING MESSAGE EMAIL
- */
+ $subject = $_SERVER['HTTP_HOST'] . ' - подтверждение email';
+ $text = '<h3>Подтверждение адреса электронной почты</h3>
+ <p>С вашего адреса электронной почты была зафиксирована попытка
+ регистрации аккаунта на сайте $site</p>
+ <p>Если это были действительно Вы, то пройдите пожалуйста по ссылке активации:</p>
+ <p><a href="$activate">$activate</a></p>';
- $subject = '';
- $text = '';
- $message = Mailer::createMessage($subject, $to, $text);
+ $message = Mailer::createMessage(
+ $subject, $to, str_replace(array('$site', '$activate'),
+ array($_SERVER['HTTP_HOST'], 'http://' . $_SERVER['HTTP_HOST'] . '/activate/' .
+ Registration::getActivationKey($user) . '/' . $user->getLogin() . '.html'), $text
+ ));
- return true;
+ return Mailer::send($message, true);
}
catch (LogicException $e)
{
return false;
}
}
+
+ /**
+ * @static
+ * @param UserProfile $user
+ * @return string
+ */
+ public static function getActivationKey(UserProfile $user)
+ {
+ return Security::getDigest(array(
+ Session::getToken(), $user->getLogin()
+ ));
+ }
}
@@ -16,6 +16,7 @@ class UserProfile
'login_exists' => 'Такой логин уже зарегистрирован',
'password' => 'Пароль не должен равняться логину',
'password_length' => 'Пароль должен быть не менее четырёх символов в длину',
+ 'password_repeat' => 'Введённые пароли не совпадают',
'user_not_exists' => 'Такого пользователя не существует',
'role' => 'Неверно указана роль',
'nickname' => 'Ник может состоять только из символа "подчеркивание", букв a-z, а-я и цифр,
@@ -144,11 +145,17 @@ public function setLogin($login, $loginIsEmail = false)
/**
* @param string $password
- * @return UserProfile
+ * @param bool|string $passwordRepeat
* @throws InvalidArgumentException
+ * @return UserProfile
*/
- public function setPassword($password)
+ public function setPassword($password, $passwordRepeat = false)
{
+ if ($passwordRepeat and ($password != $passwordRepeat)) {
+ throw new InvalidArgumentException(
+ UserProfile::$exceptions['password_repeat']
+ );
+ }
$length = mb_strlen($password, 'UTF-8');
if ($length > 3) {
if ($password != $this->login) {
@@ -493,4 +500,27 @@ public function save()
return false;
}
}
+
+ /**
+ * @return bool
+ */
+ public function remove()
+ {
+ $userId = $this->id;
+
+ return (!is_null($userId)) ?
+ Users::remove($userId) : false;
+ }
+
+ /**
+ * @param int $minutesInterval
+ * @return bool
+ */
+ public function isOnline($minutesInterval)
+ {
+ $userId = $this->id;
+
+ return (!is_null($userId)) ?
+ Users::checkOnlineState($userId, $minutesInterval) : false;
+ }
}
@@ -6,6 +6,9 @@
'/registration\.html' => array(
'!common:session', '!profiles:profilesController:register', 'profiles/registration'
),
+ '/activate/([^/]+)/([a-zA-Z0-9_]+)\.html' => array(
+ '!common:session', '!profiles:profilesController:activate'
+ ),
'/captcha/(\S+)\.png' => array(
'!common:session', '!profiles:profilesController:getCaptcha'
),
@@ -1,13 +1,16 @@
{% extends mobile ? 'skeleton.mobile.html.twig' : 'skeleton.html.twig' %}
-{% block body %}
+{% block body %}{% if not complete %}
+{% if flash_error %}<div class="alert alert-error ui-overlay-e">
+ {{ flash_error }}
+</div>{% endif %}
<form action="/registration.html" method="POST" class="well">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="logininput">
Логин:
</label>
<input id="logininput" name="xcya94n8cdjscam{{ form_code }}"
- value="" type="text" required="required" />
+ value="{{ x_login }}" type="text" required="required" />
</fieldset>
</div>
<div data-role="fieldcontain">
@@ -16,7 +19,7 @@
Email:
</label>
<input id="emailinput" name="e7a9fg0h790awf{{ form_code }}"
- value="" type="email" required="required" />
+ value="{{ x_email }}" type="email" required="required" />
</fieldset>
</div>
<div data-role="fieldcontain">
@@ -40,7 +43,7 @@
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="captcha">
- <div><img src="/captcha/{{ csrf_token }}.png"></div>
+ <div><img src="/captcha/{{ csrf_token }}.png?access={% if rrr %}{{ rrr }}{% else %}first{% endif %}"></div>
<div>Текст с картинки:</div>
</label>
<input id="captcha" name="cydas89gfy8431sas{{ form_code }}"
@@ -49,4 +52,8 @@
</div>
<input type="submit" class="btn" value="Зарегистрироваться" />
</form>
-{% endblock %}
+{% else %}
+<p>Регистрация завершена успешно</p>
+{% if cms.email_confirm %}<p>Для завершения регистрации откройте ваш email и пройдите по ссылке подтверждения</p>{% endif %}
+<p><a href="/">Вернуться на главную</a></p>
+{% endif %}{% endblock %}
Oops, something went wrong.

0 comments on commit a9c4ecc

Please sign in to comment.