Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //
- //
- class auth {
- private $db;
- private $sessionId="";
- public $timeout=60;
- public $message;
- public $data;
- public $db_bill;
- public $bill_dbs;
- //
- //
- public function __construct ($db=null) {
- $this->db=$db;
- $this->db_bill=null;
- $this->bill_dbs=array();
- $this->data=array();
- if (isset($this->db->dblink)) {
- $query="select * from billing_db where `show`=1 order by description";
- if ($result_db=$this->db->query($query)) {
- while ($row=$this->db->fetch_assoc($result_db)) {
- $this->bill_dbs[]=$row;
- }
- }
- }
- }
- //
- //
- public function __destruct() {
- if ($this->db_bill) $this->db_bill->close();
- }
- private function check_cookie() {
- $sessid=null;
- if (isset($_COOKIE["session"])) {$sessid=quote_string($_COOKIE["session"]); }
- if (empty($sessid)) {
- return false;
- }
- if (!$result_session=$this->db->query("SELECT * FROM speedyline_sessions WHERE session='" . $sessid . "'")) {
- echo $this->db->error;
- return false;
- }
- if (!($session=$this->db->fetch_assoc($result_session))) {
- //$this->message="Previous Session time out.";
- return false;
- }
- if (time() > $session['ttl']) {
- //$this->message= "Предыдущая сессия завершена из-за неактивности.";
- return false;
- }
- if (!($_SERVER['REMOTE_ADDR'] == $session['ip'])) {
- //$this->message= "Wrong ip.";
- return false;
- }
- $this->sessionId=$sessid;
- $this->data['region']=$session['region'];
- $this->data['id']=$session['id'];
- $this->data['login']=$session['login'];
- if (!$this->connect_billing()) {
- $this->message='Сервис временно недоступен..';
- return false;
- }
- $this->data['is_juridical'] = $this->is_juridical();
- $this->get_user_ips($this->data['id']);
- $query="UPDATE speedyline_sessions SET ttl=" . (time()+60*$this->timeout) . " WHERE session='" . $sessid . "'";
- if (!$this->db->query($query)) {
- //$this->message="Error in DataBase. ";
- //return false;
- }
- return true;
- }
- //
- //
- private function check_password () {
- if (!isset($_POST['submit'])) return false;
- $login='';
- $pass='';
- $region='';
- if (isset($_POST['login'])) { $login=trim(quote_string($_POST['login'])); }
- if (isset($_POST['password'])) {$pass=trim(quote_string($_POST['password'])); }
- if (isset($_POST['region'])) {$region=trim(quote_string($_POST['region'])); }
- $ip=quote_string($_SERVER['REMOTE_ADDR']);
- $net=$this->get_network_by_ip($ip);
- if (empty ($login)) {
- $this->message='Не введен логин.';
- return false;
- }
- if (empty ($pass)) {
- $this->message='Не введен пароль.';
- return false;
- }
- // Биллинг пользователя определяется по его логину,
- // поэтому регион может быть пустым.
- // Возможность выбора региона на странице логина предоставляется только
- // пользователям, подключающимся из офисов компании.
- if (empty ($region)) {
- // сначала подбираем регион по логину пользователя
- $region = $this->getRegionByLogin($login);
- if (!$region) {
- // если по системному логину пользователь не нашёлся, ищем по альтернативному
- $alt_login = $this->getUserByAltLogin($login);
- if ($alt_login) {
- $region = $alt_login['region'];
- }
- else {
- // если и по альтернативному логину не получилось, то пытаемся использовать IP пользователя
- if ($net) {
- $region = $net['billing_name'];
- }
- else {
- // если и по IP не получилось, то тогда все - без вариантов
- // либо логин не существует, либо speedyline_users не обновилась,
- // либо, в дополнение ко всему прочему, пользователь пытается войти
- // с IP, который не принадлежит сети.
- $this->message='Пользователь не найден. Повторите попытку позднее.';
- return false;
- }
- }
- }
- }
- $this->data['region']=$region;
- if (!$this->connect_billing()) {
- $this->message='Сервис временно недоступен..';
- return false;
- }
- $login_ok=false;
- if ($alt_login) {
- $query='SELECT id, login, password from users where id="'.$alt_login['user_id'].'" and is_deleted=0 limit 1';
- }
- else {
- $query='SELECT id, login, password from users where login="'.$login.'" and is_deleted=0 limit 1';
- }
- if ($result_user=$this->db_bill->query($query)) {
- if ($user=$this->db_bill->fetch_assoc($result_user)) {
- if ($user['password']==$pass) {
- $this->data['id']=$user['id'];
- $this->data['login']=$user['login'];
- $this->data['is_juridical'] = $this->is_juridical();
- $login_ok=true;
- }
- }
- }
- if (!$login_ok) {
- $this->message='Логин или пароль указаны неверно.';
- write_log($login.' Error login or pass ('.$pass.') from ip '.$ip);
- return false;
- }
- $this->get_user_ips($this->data['id']);
- if (!$this->is_allow_other_ips()) {
- if (!$this->is_my_ip($ip)) {
- if (!$net || $net['type']!=2) {
- $this->message='Доступ разрешен только с ip адресов, принадлежащих пользователю \''.$login.'\' . Ваш ip: '.$ip;
- write_log($login.' Wrong ip for login '.$login.' from ip '.$ip);
- return false;
- }
- }
- }
- $sessid=md5((time()*$this->data['id']).'speedyline_l_k') . $this->data['id'];
- $query='INSERT INTO speedyline_sessions (session, id, ip, region, login, ttl)VALUES ("' . $sessid . '", "' . $this->data['id'] . '", "' . $ip . '", "'.$region.'", "'.$login.'", ' . (time()+60*$this->timeout) . ')';
- if (!$this->db->query($query)) {
- $this->message="Сервис временно недоступен!";
- return false;
- }
- setcookie("session",$sessid,time()+60*60*24);
- $this->sessionId=$sessid;
- write_log($login.' Successfull login from ip '.$ip);
- return true;
- }
- //
- public function findUser($login) {
- $query = "SELECT u.user_id, b.name
- FROM speedyline_users u
- LEFT OUTER JOIN speedyline_users_alt_logins a
- ON u.user_id = a.user_id
- INNER JOIN billing_db b
- ON u.user_id BETWEEN b.user_min_id AND b.user_max_id
- WHERE u.login = '$login' or a.alt_login = '$login'";
- $result = $this->db->query($query);
- if ($result) {
- $user = $this->db->fetch_assoc($result);
- if ($user) {
- return $user;
- }
- }
- return NULL;
- }
- //
- private function getUser ($region, $user_id) {
- $this->data['region']=$region;
- if (!$this->connect_billing()) {
- $this->message='Сервис временно недоступен..';
- return false;
- }
- $query="SELECT * from users where id = '$user_id'";
- if ($result_user=$this->db_bill->query($query)) {
- if ($user=$this->db_bill->fetch_assoc($result_user)) {
- return $user;
- }
- else {
- $this->message='Данные пользователя недоступны. Обратитесь в техническую поддержку';
- return false;
- }
- }
- }
- //
- public function changeUserPassword($region, $user_id, $password) {
- $this->data['region']=$region;
- if (!$this->connect_billing()) {
- $this->message='Сервис временно недоступен..';
- return false;
- }
- $query = "UPDATE users SET password = '$password' where id = $user_id";
- if (!$this->db_bill->query($query)) {
- $this->message='Ошибка при изменение пароля. Обратитесь в службу технической поддержки.';
- return FALSE;
- }
- return true;
- }
- //
- public function login () {
- //return true;
- if (count($this->bill_dbs)<1) {
- $this->message="Сервис временно недоступен.";
- return false;
- }
- if ($this->check_cookie() || $this->check_password()) {
- return true;
- }
- return false;
- }
- //
- //
- public function logout() {
- if (!empty($this->sessionId)) {
- $query="DELETE FROM speedyline_sessions WHERE session='" . $this->sessionId . "'";
- if (!$this->db->query($query)) {
- return false;
- }
- $query="DELETE FROM speedyline_sessions WHERE ttl < ".time();
- $this->db->query($query);
- }
- return true;
- }
- //
- //
- private function connect_billing() {
- foreach ($this->bill_dbs as $bill_db) {
- if ($bill_db['name']==$this->data['region']) {
- $this->db_bill=new db($bill_db['ip'],$bill_db['login'],$bill_db['pass'],$bill_db['db']);
- $this->data['uniteller_shop_id']=$bill_db['uniteller_shop_id'];
- return $this->db_bill->connect_t();
- }
- }
- return null;
- }
- //
- //
- private function get_user_ips() {
- if (!$this->db_bill || !isset($this->data['id']) || $this->data['id']<1) return false;
- $id=$this->data['id'];
- $query='select account_id, ip, mask
- from service_links
- left join iptraffic_service_links on service_links.id=iptraffic_service_links.id and iptraffic_service_links.is_deleted=0
- left join ip_groups on iptraffic_service_links.ip_group_id=ip_groups.ip_group_id and ip_groups.is_deleted=0
- where service_links.user_id='.$id.' and service_links.is_deleted=0
- order by ip
- ';
- if ($this->db_bill->query($query)) {
- while($ips=$this->db_bill->fetch_assoc()) {
- $ip=long2ip($ips['ip']);
- $mask=long2ip($ips['mask']);
- if ($ip>0) {
- $ip_ar=array('ip' => $ip, 'mask' => $mask);
- $this->data['accounts'][$ips['account_id']]['ips'][]=$ip_ar;
- }
- }
- }
- }
- //
- //
- public function is_my_ip($ip_str) {
- $ip=ip2long($ip_str);
- if (empty($ip)) return false;
- if (!isset($this->data['accounts'])) return false;
- foreach ($this->data['accounts'] as $account) {
- if (!isset($account['ips'])) continue;
- foreach ($account['ips'] as $ip_ar) {
- if ((ip2long($ip_ar['ip']) & ip2long($ip_ar['mask'])) == ($ip & ip2long($ip_ar['mask']))) {
- return true;
- }
- }
- }
- return false;
- }
- public function get_network_by_ip($ip_str) {
- $ip=ip2long($ip_str);
- if (empty($ip)) return false;
- $query='select * from billing_db_ips
- where '.$ip.' & billing_db_ips.mask = billing_db_ips.ip ';
- if ($result_net=$this->db->query($query)) {
- if ($row=$this->db->fetch_assoc($result_net)) {
- return $row;
- }
- }
- return null;
- }
- public function is_allow_other_ips() {
- $query='select web_allow_other_ips as allow from speedyline_users where user_id='.$this->data['id'].'';
- if ($result_opt=$this->db->query($query)) {
- if ($row=$this->db->fetch_assoc($result_opt)) {
- return $row['allow'];
- }
- }
- return 0;
- }
- //
- private function getRegionByLogin($login) {
- $query = "SELECT b.name AS region
- FROM speedyline_users u
- INNER JOIN billing_db b
- ON u.user_id BETWEEN b.user_min_id AND b.user_max_id
- WHERE u.login = '$login'";
- $result_region = $this->db->query($query);
- if ($result_region) {
- $region_array = $this->db->fetch_assoc($result_region);
- if ($region_array) {
- return $region_array['region'];
- }
- }
- return NULL;
- }
- //
- private function getUserByAltLogin($login) {
- $query = "SELECT u.user_id, u.alt_login, b.name AS region
- FROM speedyline_users_alt_logins u
- INNER JOIN billing_db b
- ON u.user_id BETWEEN b.user_min_id AND b.user_max_id
- WHERE u.alt_login = '$login'";
- $result = $this->db->query($query);
- if ($result) {
- $user = $this->db->fetch_assoc($result);
- if ($user) {
- return $user;
- }
- }
- return NULL;
- }
- //
- public function getUserAltLogin() {
- $query = "SELECT alt_login
- FROM speedyline_users_alt_logins
- WHERE user_id = {$this->data['id']}";
- $result = $this->db->query($query);
- if ($result) {
- $user = $this->db->fetch_assoc($result);
- if ($user) {
- return $user['alt_login'];
- }
- }
- return NULL;
- }
- //
- public function setUserAltLogin($alt_login) {
- if (empty($this->data['id'])) {
- return FALSE;
- }
- // проверяем уникальность логина среди системных
- if ($this->getRegionByLogin($alt_login)) {
- return FALSE;
- }
- //
- if ($alt_login) {
- $query = "REPLACE INTO speedyline_users_alt_logins (user_id, alt_login)
- VALUES({$this->data['id']}, '$alt_login')";
- }
- else {
- $query = "DELETE FROM speedyline_users_alt_logins
- WHERE user_id = {$this->data['id']}";
- }
- return $this->db->query($query);
- }
- private function is_juridical() {
- if (!$this->db_bill || !isset($this->data['id']) || $this->data['id']<1) return false;
- $id=$this->data['id'];
- $query="SELECT is_juridical from users where id=$id";
- if ($this->db_bill->query($query)) {
- while($user=$this->db_bill->fetch_assoc()) {
- return $user['is_juridical'];
- }
- }
- return FALSE;
- }
- }
- global $db;
- $auth=new auth($db);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement