From b4f1db1ee780bce7d9a784b499cdc9f64fb0441e Mon Sep 17 00:00:00 2001
From: xamgore <xamgore@ya.ru>
Date: Sat, 11 Jun 2016 15:08:28 +0300
Subject: [PATCH] Refactor sign-in js, remove unused code

---
 media/js/sign.js                              | 126 ++++--------------
 .../classes/Controller/Handler/Sign.php       |  79 ++---------
 ~dev_rating/application/classes/User.php      |  15 ++-
 ~dev_rating/application/i18n/ru/ru.php        |   8 +-
 4 files changed, 56 insertions(+), 172 deletions(-)

diff --git a/media/js/sign.js b/media/js/sign.js
index 46ca8f1c5..3d04e8a46 100644
--- a/media/js/sign.js
+++ b/media/js/sign.js
@@ -1,5 +1,5 @@
-$(function()
-{
+$(function () {
+
     var $login = $('#login');
     var $pass = $('#password');
     var $signInButton = $('#signin_b');
@@ -16,114 +16,42 @@ $(function()
             })
     });
 
-    Auth.onAllow = function() {
-        $signInButton.removeAttr('disabled');
-    };
-
     // todo: animation
-    Auth.onDeprecate = function() {
-        $signInButton.attr('disabled', 'disabled');
-    };
-
+    Auth.onAllow = () => $signInButton.removeAttr('disabled');
+    Auth.onDeprecate = () => $signInButton.attr('disabled', 'disabled');
 
-    $('#remind').click(function()
-    {
 
-        $.post(URLdir + 'handler/sign/remindPassword', {'email': $('#email').val()},
-        function(data)
-        {
-            data = $.parseJSON(data);
-            if(data.success === true)
-            {
+    $('#remind').click(function () {
+        $.postJSON(URLdir + 'handler/sign/remindPassword', { 'email': $('#email').val() })
+            .fail(err => EventInspector.error(err.responseText))
+            .done(_ => {
                 $('#remind').val('Проверьте почту!');
                 window.location.replace(URLdir);
-            }
-            else
-            {
-                EventInspector.error(data.error);
-            }
-        });
-
-    });
-
-    $('#changepass_b').click(function()
-    {
-
-        $.post(URLdir + 'handler/sign/changePassword', {
-            'password': $('#password').val(),
-            'confirm_password': $('#confirm_password').val(),
-            'token': $('#token').val()
-        },
-        function(data)
-        {
-            data = $.parseJSON(data);
-            if(data.success === true)
-            {
-                $('#changepass_b').val('Пароль успешно изменен!');
-                window.location.replace(URLdir);
-            }
-            else
-            {
-                $('input').each(function(){
-                    $(this).removeClass('wrong');
-                });
-                $('#errors').html('<ul>');
-                $.each(data.errors, function(i){
-                    EventInspector.error(data.errors[i]);
-                    $('#' + i).addClass('wrong');
-                });
-            }
-        });
-
+            })
     });
 
-    $('#signup_b').click(function()
-    {
-
-        $.post(URLdir + 'handler/sign/up',
-            {'activation_code': $('#activation_code').val(),
-            'login': $('#login').val(),
-            'password': $('#password').val(),
+    $('#signup_b').click(function () {
+        $.postJSON(URLdir + 'handler/sign/up', {
+            'activation_code':  $('#activation_code').val(),
+            'login':            $('#login').val(),
+            'password':         $('#password').val(),
             'confirm_password': $('#confirm_password').val(),
-            'email': $('#email').val(),
-            'confirm_email': $('#confirm_email').val()},
-        function(data)
-        {
-            data = $.parseJSON(data);
-            if(data.success === true)
-            {
-                $('#signup_b').val('Всё отлично!');
-                window.location.replace(URLdir);
-            }
-            else
-            {
-                $('input').each(function(){
-                    $(this).removeClass('wrong');
-                });
-                $('#errors').html('<ul>');
-                $.each(data.errors, function(i){
-                    EventInspector.error(data.errors[i]);
-                    $('#' + i).addClass('wrong');
-                });
-            }
-        });
+            'email':            $('#email').val(),
+            'confirm_email':    $('#confirm_email').val()
+        }).done(_ => {
+            $('#signup_b').val('Всё отлично!');
+            window.location.replace(URLdir);
+        }).fail(err => Popup.error(err.responseText));
     });
 
-    $(document).keypress(function(event){
-    if(event.keyCode==13)
-    {
-            if($('#login').is(':focus'))
-            {
-                $('#password').focus();
-            }
-            else if($('#password').is(':focus'))
-            {
-                $('#signin_b').trigger('click');
-            }
-            else if($('#email').is(':focus'))
-            {
-                $('#email').siblings('input[type=button]').trigger('click');
+    $(document).keypress(function (event) {
+        if (event.keyCode == 13) {
+            if ($login.is(':focus')) {
+                $pass.focus();
+            } else if ($pass.is(':focus')) {
+                $signInButton.trigger('click');
             }
         }
     });
+    
 });
diff --git a/~dev_rating/application/classes/Controller/Handler/Sign.php b/~dev_rating/application/classes/Controller/Handler/Sign.php
index f507ffcea..b8daa3abc 100644
--- a/~dev_rating/application/classes/Controller/Handler/Sign.php
+++ b/~dev_rating/application/classes/Controller/Handler/Sign.php
@@ -12,83 +12,32 @@ class Controller_Handler_Sign extends Controller_Handler
     }
 
     public function action_up() {
-        $res['success'] = false;
-
         $config = Kohana::$config->load('security.securityPolicy');
 
-        $this->post->rule('activation_code', 'alpha_numeric')
+        $this->post
             ->rule('login', 'not_empty')
+            ->rule('activation_code', 'alpha_numeric')
             ->rule('password', 'min_length', [':value', $config['password']['length']])
             ->rule('confirm_password', 'matches', [':validation', 'confirm_password', 'password'])
             ->rule('email', 'not_empty')
             ->rule('email', 'email');
 
-        if ($this->post->check()) {
-            list($res['success'], $attempt) = User::instance()->signUp(
-                $_POST['activation_code'], $_POST['email'], $_POST['login'], $_POST['password']);
-
-            if (!$res['success']) {
-                switch ($attempt) {
-                    case 'login_exists':
-                        $this->post->error('login', 'already_exists');
-                        break;
-                    case 'mail_exists':
-                        $this->post->error('email', 'already_exists');
-                        break;
-                    case 'invalid_code':
-                        $this->post->error('activation_code', 'invalid_code');
-                        break;
-                }
-            }
-        }
+        if (!$this->post->check())
+            $this->fail($this->post->errors('signin'));
 
-        if (!$res['success']) {
-            $res['errors'] = $this->post->errors('signin');
-        }
-
-        $this->response->body(json_encode($res));
+        if ($err = User::instance()->signUp($_POST['activation_code'], $_POST['email'], $_POST['login'], $_POST['password']))
+            $this->fail(I18n::get($err));
     }
 
     public function action_remindPassword() {
-        $res['success'] = false;
-
         $this->post->rule('email', 'not_empty')->rule('email', 'email');
-
-        if ($this->post->check()) {
-            if (Account::doesEmailExist($_POST['email'])) {
-                Account::createRecoveryRequest($_POST['email']);
-                $res['success'] = true;
-            } else {
-                $res['error'] = 'Пользователь с таким e-mail адресом не зарегистрирован в системе!';
-            }
-        } else {
-            $res['error'] = 'Введенная строка не является e-mail адресом!';
-        }
-
-        $this->response->body(json_encode($res));
-    }
-
-    public function action_changePassword() {
-        $res['success'] = false;
-
-        $config = Kohana::$config->load('security.securityPolicy');
-
-        $this->post->rule('token', 'alpha_numeric')
-            ->rule('password', 'min_length', [':value', $config['password']['length']])
-            ->rule('confirm_password', 'matches', [':validation', 'confirm_password', 'password']);
-
-        if ($this->post->check()) {
-            $token = $_POST['token'];
-            if (Account::checkToken($token)) {
-                Account::changePasswordByToken($token, $_POST['password']);
-                $res['success'] = true;
-            }
-        }
-
-        if (!$res['success']) {
-            $res['errors'] = $this->post->errors('signin');
-        }
-
-        $this->response->body(json_encode($res));
+        
+        if (!$this->post->check())
+             $this->fail('Введенная строка не является <span>e‑mail</span> адресом!');
+        
+        if (!Account::doesEmailExist($_POST['email']))
+            $this->fail('Пользователь с таким <span>e-mail</span> адресом не зарегистрирован в системе!');
+        
+        Account::createRecoveryRequest($_POST['email']);
     }
 }
diff --git a/~dev_rating/application/classes/User.php b/~dev_rating/application/classes/User.php
index 8527d3028..458d9efc7 100644
--- a/~dev_rating/application/classes/User.php
+++ b/~dev_rating/application/classes/User.php
@@ -131,23 +131,24 @@ class User implements ArrayAccess
      * @param string $email  E-Mail адрес
      * @param string $login
      * @param string $password
-     * @return array  Пару вида <tt>(is_ok, err_msg)</tt>
+     * @return string|bool текст ошибки, иначе false
      */
     public function signUp($code, $email, $login, $password) {
         $id = Model_Account::activateAccount($login, $password, $email, $code);
+
         switch ($id) {
             case -1:
-                return [false, 'something wrong!'];
+                return 'something went wrong';
             case -2:
-                return [false, 'invalid_code'];
+                return 'invalid activation code';
             case -3:
-                return [false, 'mail_exists'];
+                return 'mail already exists';
             case -4:
-                return [false, 'login_exists'];
+                return 'login already exists';
         }
-
+        
         $this->initSession($id, $this->hash($password));
-        return [true, 'ok'];
+        return false;
     }
 
     /**
diff --git a/~dev_rating/application/i18n/ru/ru.php b/~dev_rating/application/i18n/ru/ru.php
index 937fc1c2a..03ee4bf6b 100644
--- a/~dev_rating/application/i18n/ru/ru.php
+++ b/~dev_rating/application/i18n/ru/ru.php
@@ -18,4 +18,10 @@ return array(
     'password'                                             => 'Пароль',
     'confirm password'                                     => 'подтверждение пароля',
     'activation code'                                      => 'Код активации',
-);
\ No newline at end of file
+    
+    # register account messages
+    'login already exists'    => 'Логин уже существует',
+    'mail already exists'     => 'E-mail уже существует!',
+    'something went wrong'    => 'Что-то пошло не так ¯\_(ツ)_/¯',
+    'invalid activation code' => 'Введенный код активации недействителен',
+);
-- 
GitLab