Skip to content
Snippets Groups Projects
Commit 6ec1c3ab authored by xamgore's avatar xamgore
Browse files

Code formatting

parent 3c2dc7c9
Branches
Tags
No related merge requests found
<?php
class Kohana_User implements ArrayAccess {
class Kohana_User implements ArrayAccess
{
protected static $_instance;
protected $_session;
protected $_config;
......@@ -10,21 +10,19 @@ class Kohana_User implements ArrayAccess {
protected static $_flag;
/**
* Вовзращает экземпляр класса (singleton-паттерн)
*
* @return self
*/
* @deprecated Singleton is an anti-pattern!
* @return self class instance (singleton-pattern)
*/
public static function instance($state = false) {
self::$_flag = $state;
if(!isset(self::$_instance))
{
if (!isset(self::$_instance)) {
$config = Kohana::$config->load('account');
self::$_instance = new self($config);
}
return self::$_instance;
}
private function __construct($config = array()) {
$this->_config = $config;
$this->_session = Session::instance();
......@@ -34,20 +32,19 @@ class Kohana_User implements ArrayAccess {
$this->_config['hash_method'] = 'sha256';
$isSignedIn = $this->isSignedIn();
$this->_PrepareSemester();
if($isSignedIn) {
if ($isSignedIn) {
$id = $this->_session->get('ID');
$this->_userInfo = $this->_getInfoFromDB($id);
if (self::$_flag != true) {
$this->_session->regenerate();
$this->_session->set('start_time', time());
}
}
}
protected function _PrepareSemester() {
$semesterID = $this->_session->get("SemesterID");
if (!$semesterID) {
......@@ -55,29 +52,30 @@ class Kohana_User implements ArrayAccess {
}
$this->SetSemester($semesterID);
}
public function SetSemester($semesterID) {
$res = $this->_model->SetSemesterID($semesterID);
if ($res >= 0)
if ($res >= 0) {
$this->_session->set("SemesterID", "$semesterID");
}
}
/**
* Регистрирует нового пользователя и осуществляет вход.
* Проверяет корректность кода активации и существование аккаунтов с такими же авторизационными данными.
* Проверяет корректность кода активации и существование
* аккаунтов с такими же авторизационными данными.
*
* @param string $code Код активации
* @param string $email E-Mail адресс
* @param string $login
* @param string $password
* @return array
*/
public function signUp($code, $email, $login, $password)
{
* @param string $code Код активации
* @param string $email E-Mail адресс
* @param string $login
* @param string $password
* @return array Пару вида <tt>(is_ok, err_msg)</tt>
*/
public function signUp($code, $email, $login, $password) {
$model = &$this->_model;
$account = Account::instance();
$isValid = $model->isActivationCodeValid($code);
if (!$isValid) {
return array(false, 'invalid_code');
......@@ -85,25 +83,28 @@ class Kohana_User implements ArrayAccess {
$isLogin = $account->isLoginExists($login);
$isMail = $account->isMailExists($email);
if ($isLogin) {
return array(false, 'login_exists');
} else if ($isMail) {
return array(false, 'mail_exists');
} else {
if ($isMail) {
return array(false, 'mail_exists');
}
}
$id = $model->activateAccount($login, $password, $email, $code);
$this->completeSignIn($id, $this->hash($password));
return array(true, 'ok');
}
/**
* Проверяет корректность авторизационных данных и возвращает true, если авторизация прошла успешно, и false, если данные являются некорректными.
* Проверяет корректность авторизационных данных.
*
* @param string $login
* @param string $password
* @return bool
*/
* @param string $login
* @param string $password
* @return bool true, если авторизация прошла успешно,
* и false, если данные являются некорректными.
*/
public function signIn($login, $password) {
$id = (int)$this->_model->checkAuth($login, $password);
if ($id === -1) {
......@@ -112,10 +113,11 @@ class Kohana_User implements ArrayAccess {
return $this->completeSignIn($id, $this->hash($password));
}
}
protected function completeSignIn($id, $passhash) {
$userHash = $this->hash($id.Request::$user_agent.Request::$client_ip).$this->_config['hash_key'];
$passwordHash = $this->hash($passhash.$this->_config['hash_key']);
$source = $id . Request::$user_agent . Request::$client_ip;
$userHash = $this->hash($source) . $this->_config['hash_key'];
$passwordHash = $this->hash($passhash . $this->_config['hash_key']);
Cookie::set('userhash', $passwordHash);
$this->_userInfo = $this->_getInfoFromDB($id);
$this->_session->regenerate();
......@@ -124,190 +126,176 @@ class Kohana_User implements ArrayAccess {
$this->_session->set('UserHash', $this->hash($userHash));
$this->_session->set('PasswordHash', $passwordHash);
$this->_session->set('start_time', time());
return TRUE;
}
return true;
}
/**
* Проверяет авторизационный статус пользователя и, если пользователь имеет useragent и IP, отличные от хранимых в сессии, осуществляет выход из текущего сеанса.
* Проверяет авторизационный статус пользователя и, если
* пользователь имеет UserAgent и IP, отличные от хранимых
* в сессии, осуществляет выход из текущего сеанса.
*
* @return bool
*/
public function isSignedIn()
{
* @return bool true, если пользователь авторизован
*/
public function isSignedIn() {
$session = &$this->_session;
if($session->get('LoggedIn') && !$this->checkHash()) {
if ($session->get('LoggedIn') && !$this->checkHash()) {
$this->completeSignOut();
}
return $this->_session->get('LoggedIn');
}
protected function checkHash()
{
protected function checkHash() {
$id = $this->_session->get('ID');
$userHash = $this->hash($id.Request::$user_agent.Request::$client_ip).$this->_config['hash_key'];
$source = $id . Request::$user_agent . Request::$client_ip;
$userHash = $this->hash($source) . $this->_config['hash_key'];
$userCheck = $this->_session->get('UserHash') == $this->hash($userHash);
$passCheck = Cookie::get('userhash') == $this->_session->get('PasswordHash');
return $userCheck AND $passCheck;
}
}
/**
* Завершает текущий сеанс пользователя.
*
* @return array
*/
public function signOut()
{
if($this->isSignedIn()) {
* @return bool
*/
public function signOut() {
if ($this->isSignedIn()) {
return $this->completeSignOut();
}
return FALSE;
return false;
}
protected function completeSignOut()
{
$this->_session ->set('ID', FALSE)
->set('LoggedIn', FALSE)
->set('UserHash', FALSE);
protected function completeSignOut() {
$this->_session
->set('ID', false)
->set('LoggedIn', false)
->set('UserHash', false);
Cookie::delete('userhash');
unset($this->_userInfo);
$this->_session->restart();
return TRUE;
return true;
}
/**
* Проверяет корректность данного пароля для текущего пользователя.
*
* @param string $password Пароль
* @return bool
*/
* @param string $password
* @return bool
*/
public function checkPassword($password) {
if(!$this->isSignedIn())
return FALSE;
$passhash = $this->hash($password);
return $this->hash($passhash.$this->_config['hash_key']) === $this->_session->get('PasswordHash');
if (!$this->isSignedIn())
return false;
$passHash = $this->hash($password);
$computed = $this->hash($passHash . $this->_config['hash_key']);
return $computed === $this->_session->get('PasswordHash');
}
public function changePassword($old, $new)
{
if(!$this->checkPassword($old))
return FALSE;
public function changePassword($old, $new) {
if (!$this->checkPassword($old))
return false;
$this->_model->changePassword($this->offsetGet('ID'), $new);
$passhash = $this->hash($this->hash($new).$this->_config['hash_key']);
Cookie::set('userhash', $passhash);
$passhash = $this->hash($this->hash($new) . $this->_config['hash_key']);
$this->_session->set('PasswordHash', $passhash);
return TRUE;
Cookie::set('userhash', $passhash);
return true;
}
public function changeLogin($login)
{
if(!$this->isSignedIn() || Account::instance()->isLoginExists($login))
return FALSE;
public function changeLogin($login) {
if (!$this->isSignedIn() || Account::instance()->isLoginExists($login))
return false;
$this->_model->changeLogin($this->offsetGet('ID'), $login);
return TRUE;
}
public function changeMail($email)
{
if(!$this->isSignedIn() || Account::instance()->isMailExists($email))
return FALSE;
$token = md5(time().$this->offsetGet('EMail').$email);
return true;
}
public function changeMail($email) {
if (!$this->isSignedIn() || Account::instance()->isMailExists($email))
return false;
$token = md5(time() . $this->offsetGet('EMail') . $email);
$this->_session->set('NewMail_Token', $token);
$this->_session->set('NewMail_Adress', $email);
return $token;
}
public function completeChangeMail($token)
{
}
public function completeChangeMail($token) {
$email = $this->_session->get('NewMail_Adress');
if($token == $this->_session->get('NewMail_Token') AND !Account::instance()->isMailExists($email))
{
if ($token == $this->_session->get('NewMail_Token') AND !Account::instance()->isMailExists($email)) {
$this->_model->changeMail($this->offsetGet('ID'), $email);
return true;
}
else {
} else {
return false;
}
}
public function changeProfile($data)
{
if($this->offsetGet('Type') == 'teacher')
{
$this->_model->ChangeTeacherInfo(
$this->offsetGet('TeacherID'),
$data['lastName'],
$data['firstName'],
$data['secondName'],
$data['jobPositionID'],
$data['departmentID']);
}
}
// ---------------------------- [INFO] -------------------------------------
public function changeProfile($data) {
if ($this->offsetGet('Type') == 'teacher') {
$this->_model->ChangeTeacherInfo($this->offsetGet('TeacherID'), $data['lastName'], $data['firstName'], $data['secondName'], $data['jobPositionID'], $data['departmentID']);
}
}
/* Info */
/**
* Возвращает массив, содержащий пользовательские данные.
*
* @return array
*/
public function getInfoAsArray()
{
if($this->isSignedIn())
public function getInfoAsArray() {
if ($this->isSignedIn()) {
return $this->_userInfo + $this->_session->as_array();
else
} else {
return array();
}
}
protected function _getInfoFromDB($id)
{
protected function _getInfoFromDB($id) {
$info = $this->_model->getPersonalInfo($id)->offsetGet(0);
$info += $this->_model->getAccountInfo($id)->offsetGet(0);
return $info;
}
// ---------------------------- [ARRAY] ------------------------------------
/* Array access */
public function offsetSet($offset, $value) {
if(isset($this->_userInfo[$offset])) {
if (isset($this->_userInfo[$offset])) {
return $this->_userInfo[$offset];
} else {
throw new Kohana_Exception('Invalid key: '.$offset);
throw new Kohana_Exception('Invalid key: ' . $offset);
}
}
public function offsetGet($offset) {
if(isset($this->_userInfo[$offset]))
{
if (isset($this->_userInfo[$offset])) {
return $this->_userInfo[$offset];
} else {
return false;
}
else
return FALSE;
}
public function offsetUnset($offset) {
if(isset($this->_userInfo[$offset]))
{
if (isset($this->_userInfo[$offset])) {
unset($this->_userInfo[$offset]);
}
}
public function offsetExists($offset) {
return isset($this->_userInfo[$offset]);
}
/**
* Perform a hmac hash, using the configured method.
*
* @param string $str string to hash
* @param string $str string to hash
* @return string
*/
protected function hash($str)
{
if ( ! $this->_config['hash_key'])
{
$this->_config['hash_key'] = $key = md5(time().Request::$client_ip);
protected function hash($str) {
if (!$this->_config['hash_key']) {
$this->_config['hash_key'] = $key = md5(time() . Request::$client_ip);
$this->_model->setHashKey($key);
}
return hash_hmac($this->_config['hash_method'], $str, $this->_config['hash_key']);
}
}
}
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment