<?php
class auth {

	var $is_login = false;
	var $user_id = 0;
	var $user_obj;
    var $sess_obj;
	var $groups = array();

	function __construct() {
		global $core_db;

        session_set_cookie_params(32140800,'/',_COOKIE_DOMAIN_); // Сессия на год
        session_start();
        $sess_id = session_id();

        $this->sess_obj = new cobject( '_sys_user_sessions' );
		$this->user_obj = new cobject( '_sys_users' );

        
	    $db2 = $this->sess_obj->getDB()->q( $this->sess_obj->getSelect(' AND `session_id` = "'. db_escape_string($sess_id) . '" ' ) );
	    if ( $db2->nr() ) {
			$this->_intAuth( $db2->f('user_id') );
	    } else {
            $this->is_login = false;
        }
	}
    
    function _intAuth( $user_id ) {
		global $core_db;
        $this->user_obj->byId($user_id);
        if ($this->user_obj->id && !$this->user_obj->get('_sys_disabled') ) {
            $this->is_login = true;
            $this->user_id = $user_id;
            if ( $this->user_obj->get('group') ) {
            	$this->groups = explode( ',', $this->user_obj->get('group') );
            }
        } else {
            $this->do_logout();
        }
    }

	
	function do_login( $user_id ) {
        $this->do_logout();
        $this->sess_obj->set('session_id', session_id() );
        $this->sess_obj->set('user_id', $user_id );
        $this->sess_obj->save();
        $this->_intAuth($user_id);
	}

	
	function do_logout() {
        $this->sess_obj->getDB()->q( 'DELETE FROM `_sys_user_sessions` WHERE `session_id` = "' . db_escape_string(session_id()) . '" ' );
        $this->is_login  = false;
		$this->user_obj->byId( 0 );
        $this->user_id = 0;
	}
	
	
	function is_login() {
		return $this->is_login;
	}
	
	function get( $attr ) {
		return $this->user_obj->get( $attr );
	}
	
	function sessGet($key) {
		return $this->sessionData[$key];
	}

	function sessSet($key, $val) {
		$this->sessionData[$key] = $val;
	}

	function saveSession() {
		if ( $this->is_login ) {
			$data = serialize($this->sessionData);
			$this->user_obj->byId( $this->user_id );
            if ( $data !=  $this->user_obj->get('session_data')  ) {
    			$this->user_obj->set('session_data',$data);
    			$this->user_obj->save(false);
            }
		}
	}		
}	
?>