From 9ad82c3e9d476888e08554e09bdad41384fa9289 Mon Sep 17 00:00:00 2001 From: Artem Konenko <yadummer@gmail.com> Date: Sat, 29 Oct 2016 13:31:23 +0300 Subject: [PATCH] Implement optimictic way of OpenID autentification --- db/migrations/stored/R__functions.sql | 20 +++++++++++ .../structure/V13_8__add_external_1C_key.sql | 6 ++++ .../classes/Controller/Handler/Sign.php | 33 ++++++++++--------- .../application/classes/Model/Account.php | 7 ++++ ~dev_rating/application/classes/User.php | 12 +++++++ .../application/views/sign/inOpenID.twig | 4 +-- 6 files changed, 64 insertions(+), 18 deletions(-) create mode 100644 db/migrations/structure/V13_8__add_external_1C_key.sql diff --git a/db/migrations/stored/R__functions.sql b/db/migrations/stored/R__functions.sql index 812979ff1..095c16cca 100644 --- a/db/migrations/stored/R__functions.sql +++ b/db/migrations/stored/R__functions.sql @@ -2232,6 +2232,26 @@ BEGIN RETURN vAccountID; END // +DROP FUNCTION IF EXISTS SignInByOpenID// +CREATE FUNCTION SignInByOpenID ( + pGlobalKey VARCHAR(255) CHARSET utf8 +) RETURNS int(11) # account id +NO SQL + BEGIN + DECLARE vAccountID INT DEFAULT -1; + + #check account existence + SELECT accounts.ID INTO vAccountID FROM accounts + WHERE accounts.globalKey1C = pGlobalKey + LIMIT 1; + IF vAccountID <= 0 THEN + RETURN -1; + END IF; + + INSERT INTO logs_signin (AccountID) VALUES (vAccountID); + RETURN vAccountID; + END // + -- returns: -- -1 : invalid token -- >0 : accountID diff --git a/db/migrations/structure/V13_8__add_external_1C_key.sql b/db/migrations/structure/V13_8__add_external_1C_key.sql new file mode 100644 index 000000000..7f585ec49 --- /dev/null +++ b/db/migrations/structure/V13_8__add_external_1C_key.sql @@ -0,0 +1,6 @@ +-- +-- Добавление идентификатора физ.лица из 1С в таблицу `accounts` +-- + +ALTER TABLE `accounts` + ADD COLUMN `globalKey1C` varchar(30) CHARACTER SET utf8 AFTER `ID`; \ No newline at end of file diff --git a/~dev_rating/application/classes/Controller/Handler/Sign.php b/~dev_rating/application/classes/Controller/Handler/Sign.php index 9a6e9dd39..29df4f7bb 100644 --- a/~dev_rating/application/classes/Controller/Handler/Sign.php +++ b/~dev_rating/application/classes/Controller/Handler/Sign.php @@ -83,22 +83,23 @@ class Controller_Handler_Sign extends Controller_Handler public function action_openidfinish() { - if ($_GET["openid_sreg_student"] !== '1') { - $this->fail('К сожалению, личный кабинет сотрудника пока что находится в разработке. Следите за новостями!'); - } - if ($_GET['openid_mode'] == 'id_res') { $openid = new OpenID; $openid->SetIdentity($_GET['openid_identity']); $openid_validation_result = $openid->ValidateWithServer(); - if ($openid_validation_result == true) { + if ($openid_validation_result == true) + { $this->openid_signIn(); - } else if ($openid->IsError() == true) { + } + else if ($openid->IsError() == true) + { $error = $openid->GetError(); echo 'Ошибка!'; echo "[" . $error['code'] . "]: " . $error['description']; - } else { + } + else + { echo 'Ошибка!'; echo "При авторизации что-то пошло не так. Попробуете снова?"; } @@ -110,14 +111,14 @@ class Controller_Handler_Sign extends Controller_Handler private function openid_signIn() { - $flags = [ - 'isStudent' => $_GET["openid_sreg_student"], - 'isStaff' => $_GET["openid_sreg_staff"] - ]; - - echo 'Добро пожаловать!'; -// $this->redirect_url = Route::url('evaluation:student'); -// -// Account::signIn($_GET["openid_sig"], $_GET["openid_sreg_r61globalkey"], $flags); + $ok = User::instance()->signInByOpenID($_GET["openid_sreg_r61globalkey"]); + + if (!$ok) $this->fail(); + $this->redirect('/'); + + if ($this->user->isSignedIn()) + { + $this->redirect('/'); + } } } diff --git a/~dev_rating/application/classes/Model/Account.php b/~dev_rating/application/classes/Model/Account.php index 47fdd9873..7739324d5 100644 --- a/~dev_rating/application/classes/Model/Account.php +++ b/~dev_rating/application/classes/Model/Account.php @@ -110,6 +110,13 @@ class Model_Account extends Model ->execute()->get('ID'); } + public static function checkAuthOpenID($globalKey) { + $sql = 'SELECT `SignInByOpenID`(:key) AS `ID`'; + return DB::query(Database::SELECT, $sql) + ->param(':key', $globalKey) + ->execute()->get('ID'); + } + public static function checkAuthToken($token) { $sql = 'SELECT `SignInByToken`(:token) AS `ID`'; return DB::query(Database::SELECT, $sql) diff --git a/~dev_rating/application/classes/User.php b/~dev_rating/application/classes/User.php index 9df38f753..92df3a21b 100644 --- a/~dev_rating/application/classes/User.php +++ b/~dev_rating/application/classes/User.php @@ -159,6 +159,18 @@ class User implements ArrayAccess return $this->initSession($id, $this->hash($password)); } + /** + * Проверяет существования пользователя с заданным globalKey и авторизует его + * + * @param string $globalKey + * @return bool true, если авторизация прошла успешно, + * и false, если данные являются некорректными. + */ + public function signInByOpenID($globalKey) { + $id = (int) Model_Account::checkAuthOpenID($globalKey); + return $this->initSession($id, $this->hash($globalKey)); + } + public function signInByToken($token) { $id = (int) Model_Account::checkAuthToken($token); return $this->initSession($id, $this->hash($token)); diff --git a/~dev_rating/application/views/sign/inOpenID.twig b/~dev_rating/application/views/sign/inOpenID.twig index 36a99bcd7..fb07feada 100644 --- a/~dev_rating/application/views/sign/inOpenID.twig +++ b/~dev_rating/application/views/sign/inOpenID.twig @@ -3,9 +3,9 @@ {% block title %}Авторизация{% endblock %} {% block forms %} <div id='inputs'> - {{ sign.input('loginopenid', 'text', '', 'Логин OpenID', true) }} + {{ sign.input('loginopenid', 'text', '', 'Логин@sfedu.ru', true) }} </div> - {{ sign.input('signopenidin_b', 'button', 'Войти c OpenID') }} + {{ sign.input('signopenidin_b', 'button', 'Войти через OpenID.sfedu.ru') }} <div class='footer'> {{ HTML.anchor('sign/in', 'Вход через локальную учетную запись')|raw }} | {{ HTML.anchor('sign/up', 'Активировать аккаунт')|raw }} | {{ HTML.anchor('remind', 'Забыли пароль?')|raw }} </div> -- GitLab