Ejemplo n.º 1
0
    def index(self, id_system=None):
        u"""Инициализируем параметры системы, в которую вошли.

        """
        #запрет кэширования index
        cherrypy.response.headers["Expires"] = "Mon, 26 Jul 1997 05:00:00 GMT" #Date in the past
        cherrypy.response.headers["Last-Modified"] = "Mon, 26 Jul 1997 05:00:00 GMT" #always modified
        cherrypy.response.headers["Cache-Control"] = "no-cache, must-revalidate" # HTTP/1.1
        cherrypy.response.headers["Pragma"] = "no-cache" # HTTP/1.0

        if id_system is None:
            id_system = getattr(self, 'id_system', None)

            if id_system is None:
                id_system = si.get_id_system()

        if id_system is not None:
            #проверяем на отключенность систему
            dis=db.dbExec(sql="select DISABLED "
                              "from ENGINE_SYSTEMS "
                              "where id_system=? ",
                            params=(id_system,),
                            fetch='one',
                            id_system=-1)
            #print ""
            #print "INDEX: dis=", dis
            #print ""
            #no that system
            if not dis:
                #print ""
                #print "INDEX: gotoIndex. dis=", dis
                #print ""
                #return cpu.goToIndex()
                return cpu.goToError('Подсистема не найдена либо отключена.')
            if dis['DISABLED']:
                #print "dis['DISABLED']=", dis['DISABLED']
                return cpu.goToError('Подсистема временно недоступна.')
                #raise cherrypy.HTTPRedirect("/exception?exception="+
                #    "Система временно недоступна. Попробуйте зайти сюда позже. А пока можно вернуться <a href='javascript:history.back()'>Назад</a>")

            #self.setSesVar("id_system",id_system)
            self.setIfaceVar("id_system", id_system)

            #обновляем сессию, если только система - не список терминальных/мобильных интерфейсов
            if si.get_full_ref_name_by_id_system(id_system) not in (getattr(cfg, 'TERMINAL_link', None),
                                                                    getattr(cfg, 'MOBILE_link', None)):
                error_msg = sessions.session_update(uid=self.getUserVar('uid'), fio=self.getUserVar('userfio'),
                                                    equip_kind=cpu.equipKind(),
                                                    ip_addr=cpu.get_remote_ip(if_proxy='client'),
                                                    user_agent=cpu.getUserAgent(), id_system=id_system)

                # ошибка обновления сессии
                if error_msg:
                    cpu.cherrypylog(error_msg, context='APP.SESSIONS')
                    #return self.drawTemplate(templ=login_index, data=[{'mes': error_msg}, {'langs': cpu.getConfigLangs()}], draw_wo_login=True)
                    if not cpu.isPC():
                        return cpu.goToError(error_msg)
            so.create_sys_options(self.__module__, cfg.options_instances_subdir)

            """d=db.dbExec(sql="select SHOW_NAME,
Ejemplo n.º 2
0
    def __init__(self, location):

        self.Lock = threading.RLock()
        self.location = location
        self.refresh()
        if not self.correct_path:
            from cp_utils import cherrypylog
            cherrypylog("Hot config has uncorrect path %s" % self.location)
        self.tmr = PerpetualTimer(self.refresh_time, self.refresh)
        self.tmr.setName("Hot config reader")
        self.tmr.start()
Ejemplo n.º 3
0
 def default(self, *args, **kwargs):
     logmes = "!!! RNF: " + cherrypy.request.path_info #reduce(lambda x, y: x+'/'+y, args, "")
     cpu.cherrypylog(logmes)
     if len(args) == 0:
         print "default: unknown resource not found, len(args)==0, path=%s" % cherrypy.request.path_info
         return cpu.goToError('Неизвестный ресурс %s не найден. Проверьте правильность ссылки.'
                              % cherrypy.request.path_info, from_root=True)
         #return cpu.goToIndex()
     if not secure.is_static_resource(args[len(args)-1]):
         print "default: not static resource not found %s:" % cherrypy.request.path_info
         return cpu.goToError('Ресурс %s не найден. Проверьте правильность ссылки.' % cherrypy.request.path_info,
                              from_root=True)
Ejemplo n.º 4
0
 def close_pc_session_by_data(user_data, reason, closed_by=None):
     "Закрытие PC-сессии, если она привязана к пользователю"
     #print "%s: close_pc_session_by_data" % (time.strftime('%H:%M:%S',time.localtime()))
     uid = get_uid(user_data)
     if uid is None:
         return
     if is_terminal(user_data):
         return
     fio = get_fio(user_data)
     error_msg, web_session_id = session_close(uid=uid, fio=fio, equip_kind='P', reason=reason, closed_by=closed_by)
     if error_msg:
         cpu.cherrypylog(error_msg, context='APP.SESSIONS')
Ejemplo n.º 5
0
    def getint(self, section, option, default):
        self.Lock.acquire()
        try:
            if self.hot_conf.has_option(section, option):
                try:
                    res = self.hot_conf.getint(section, option)
                except ValueError:
                    from cp_utils import cherrypylog
                    cherrypylog(
                        "Hot config has uncorrect integer option %s at section %s"
                        % (option, section))
                    res = default
            else:
                res = default
        finally:
            self.Lock.release()

        return res
Ejemplo n.º 6
0
            fields.append({
                'name': 'passwd',
                'errmes': str(exc)
            })  #Недостаточна сложность пароля!
            return (0, fields)
        except adm.EUserVerifyAndChangePassword, exc:
            fields.append(
                {
                    'name': 'login',
                    'errmes': str(exc)
                }
            )  #Другая ошибка на уровне БД (например, Пользователь не заведён в системе)
            return (0, fields)
        except Exception, exc:
            cpu.cherrypylog("UserProfile.user_change_passwd:\n" +
                            tb.format_exc(),
                            context='APP.PROFILE')
            fields.append({
                'name':
                'login',
                'errmes':
                _('Сервис временно недоступен. Повторите попытку позже.'
                  )
            })  # Скрываем причину от пользователя
            return (0, fields)
        else:
            return (1, fields)


class Profile(BasePage):
    "Профиль пользователя"
Ejemplo n.º 7
0
def upload(file=None, ext=[], sysname='DEFAULT', uid='', test=False):
    """
        Загрузка файла на сервер
        параметры:
            file - файл для загрузки
            ext - список расширений для ограничения загрузок. Например: ['rar', 'zip'] - будут допускаться только такие типы файлов
            sysname - имя системы. Будет создана подпапка с этим именем (если указано), туда и будут падать загрузки
            uid - ид. пользователя, будет добавлен префикс к папке
            test - флаг тестирования файла на предмет удовлетворения требований для загрузок, может быть полезен для предварительной валидации
         возвращает:
            res - [0 - плохо/1 - хорошо]
            mes - сообщение об ошибке, если res = 0
            path - полный путь загруженного файла
    """
    if not file.filename:
        return 0, error_code[0], ''
    # путь загрузки (папка)
    upload_path = os.path.join(cfg.UPLOAD_PATH, sysname, uniq_path(uid))
    try:
        # проверим расширение из списка доступных
        fname, fext = os.path.splitext(file.filename)
        if (fext[1:]
                not in cfg.UPLOAD_FILE_TYPES) or (ext and fext[1:] not in ext):
            return 0, error_code[1], ''
        # проверка на размер и одновременная запись на диск (чтобы не делать двойной проход по размеру)
        # если размер превышен, файл удаляется
        size = 0
        if not os.path.isdir(upload_path):
            os.makedirs(upload_path)
        import py_utils as pu
        res_filename = os.path.join(upload_path,
                                    pu.decodeXStr(repr(file.filename)[2:-1]))
        file.file.seek(0)
        f = open(res_filename, 'wb')
        closed = 0
        while True:
            # читаем по 8кб, так быстрее читать размер больших файлов
            #data = file.file.read(8192)
            data = file.file.read(16384)
            if not data:
                break
            if size > cfg.UPLOAD_MAX_SIZE:
                f.close()
                os.remove(res_filename)
                os.removedirs(upload_path)
                closed = 1
                break
            if not test:
                f.write(data)
            size += len(data)
        if closed == 0:
            f.close()
            if test:
                os.remove(res_filename)
                os.removedirs(upload_path)
        else:
            return 0, error_code[2], ''
        return 1, '', res_filename
    except:
        import traceback as tb
        import cp_utils as cpu
        cpu.cherrypylog("upload exception:\n" + tb.format_exc(),
                        context='APP.UPLOAD')
        return 0, error_code[3], ''
Ejemplo n.º 8
0
        def wrapped(*args, **kwargs):
            res = db.dbExec(sql='select id_system from ENGINE_FIND_SYSTEM_BY_FULL_REF(?)', params=['/LOG'], fetch='one', id_system=-1)
            if not res:
                cpu.cherrypylog('system LOG not found')
                return f(*args, **kwargs)
            log_system = res['id_system']
            if not f.__doc__:
                raise LogException('Doc string of method %s.%s not found' % (args[0].__class__, f.__name__))
            id_system = int(args[0].id_system) #int(args[0].getIfaceVar('id_system'))
            #print "------------------"
            #print log_system
            #print "------------------"

            sargs = ''
            skwargs = ''
            args_1251 = format(obj=args, add_utf_str=True, add_unicode_str=True, consider_ajax=1)
            kwargs_1251 = format(obj=kwargs, add_utf_str=True, add_unicode_str=True, consider_ajax=1)

            #args
            for arg in args_1251[1:]:
                sargs += '%s, ' % iif(arg is None, 'null', iif(type(arg)==str, decodeXStr('"%s"'%(str(arg).replace('"', '\\"'))),
                                                               decodeXStr('%s'%(str(arg).replace('"', '\\"'))))) #str() need, else error "AttributeError: 'int' object has no attribute 'replace'"
            if sargs:
                sargs = '"args": [%s]' % sargs[:-2]

            #kwargs
            for name, val in kwargs_1251.items():
                skwargs += '%s: %s, ' % (iif(type(name)==str, decodeXStr('"%s"'%(str(name).replace('"', '\\"'))),
                                                                decodeXStr('%s'%(str(name).replace('"', '\\"')))),
                                         iif(val is None, 'null', iif(type(val)==str, decodeXStr('"%s"'%(str(val).replace('"', '\\"'))),
                                                                      decodeXStr('%s'%(str(val).replace('"', '\\"')))))) #str() need, else error "AttributeError: 'int' object has no attribute 'replace'"
            if skwargs:
                skwargs = '"kwargs": {%s}' % skwargs[:-2]

            #sallargs = '; '.join((sargs, skwargs)) #ne katit
            #sallargs = str(sargs + skwargs).strip()
            sallargs = sargs
            if sallargs:
                if skwargs:
                    sallargs += ', ' + skwargs
            else:
                sallargs = skwargs
            sallargs = '{%s}' % sallargs

            table_name = logGetTableName(args[0].__class__)

            conv_f_doc = convDocString(f.__doc__)

            db.dbExec(sql='execute procedure prepare_metadata(?)', params=[table_name], fetch='none', id_system=log_system)
            db.dbExec(sql='execute procedure log_insert(?,?,?,?,?,?,?,?,?,?)',
                params=(
                    table_name,
                    id_system,
                    si.systems_params[id_system]['system_name'],
                    str(args[0].__class__), #.split('.')[-1],
                    f.__name__,
                    code[:20],
                    conv_f_doc,
                    args[0].getUserVar('uid'), #int(args[0].getUserVar('uid')),
                    args[0].getUserVar('userfio'),
                    sallargs
                ), fetch='none', id_system=log_system)

            result = f(*args, **kwargs)
            return result
Ejemplo n.º 9
0
def logWrite(code, ext_params=None, level=0):
    "direct write into log (code required max 20 chars)"

    def get_params_for_log():
        type_caller, self, f, f_cum_name = find_base_caller(level = level + 2)

        if type_caller == 'b':
            cls = self.__class__
            str_cls = str(cls)
            id_system = int(self.id_system) #int(self.getIfaceVar('id_system')) #or nested function not in class (self is none), or class is borned not from BasePage
            system_name = si.systems_params[id_system]['system_name']
            f_doc = f.__doc__

        elif type_caller in ['f', 'n']:
            #try:
            cls = f.__module__
            str_cls = "m " + str(f.__module__)
            id_system = -1
            system_name = 'SYSTEM'
            f_doc = f.__doc__
            #except:

        elif type_caller == 't':
            cls = None
            str_cls = None
            id_system = None
            system_name = None
            f_doc = None
            #print 'Top level'
            #raise Exception('Класс не порождён от BasePage')

        else:# type_caller == 'o':
            cls = None
            str_cls = None
            id_system = None
            system_name = None
            f_doc = None
            #print 'Class not borned from BasePage'
            #raise Exception('Класс не порождён от BasePage')

        return type_caller == 'b', f_cum_name, cls, str_cls, id_system, system_name, f_doc

    is_class, f_name, cls, str_cls, id_system, system_name, f_doc = get_params_for_log()

    res = db.dbExec(sql='select id_system from ENGINE_FIND_SYSTEM_BY_FULL_REF(?)', params=['/LOG'], fetch='one', id_system=-1)
    if not res:
        cpu.cherrypylog('system LOG not found')
        return
    log_system = res['id_system']

    #print is_class
    #print f_name
    #try:
    #    print f.__name__
    #except:
    #    pass

    if not f_doc:
        raise LogException('Doc string of %s %s.%s not found' % (iif(is_class, 'method', 'function'), cls, f_name))

    tb_frame = sys._getframe(level+1)

    #simple args and arg-argument
    args_new = []
    #simple argument
    for local in tb_frame.f_locals.keys():
        vl = tb_frame.f_locals[local]
        if is_simple_argument(local, tb_frame):
            args_new.append(format(obj=vl, add_utf_str=True, add_unicode_str=True))

    #arg-argument
    for local in tb_frame.f_locals.keys():
        vl = tb_frame.f_locals[local]
        if is_args(local, tb_frame):
            args_new.extend(format(obj=vl, add_utf_str=True, add_unicode_str=True))

    #kwargs and ext_params
    kwargs_new = {}
    for local in tb_frame.f_locals.keys():
        vl = tb_frame.f_locals[local]
        #kwarg-argument or is arg
        if is_kwargs(local, tb_frame):
            if ext_params:
                vlcopy = vl.copy()
                vlcopy.update(ext_params)
            kwargs_new = format(obj=vlcopy, add_utf_str=True, add_unicode_str=True)
            break #only once
    if kwargs_new == {}:
        kwargs_new = format(obj=ext_params, add_utf_str=True, add_unicode_str=True)

    sargs = ''
    skwargs = ''
    #args_1251 = format(obj=args_new, add_utf_str=True, add_unicode_str=True) #already in this coding
    #kwargs_1251 = format(obj=kwargs_new, add_utf_str=True, add_unicode_str=True)

    #args
    #del self-links
    #if is_class or is_nested:
    if len(args_new):
        for i in xrange(len(args_new)):
            if isinstance(args_new[i], BasePage):
                del args_new[i]
                break

    #args
    for arg in args_new:
        sargs += '%s, ' % iif(arg is None, 'null', iif(type(arg)==str, decodeXStr('"%s"'%(str(arg).replace('"', '\\"'))),
                                                       decodeXStr('%s'%(str(arg).replace('"', '\\"'))))) #str() need, else error "AttributeError: 'int' object has no attribute 'replace'"
    if sargs:
        sargs = '"args": [%s]' % sargs[:-2]

    #kwargs
    for name, val in kwargs_new.items():
        skwargs += '%s: %s, ' % (iif(type(name)==str, decodeXStr('"%s"'%(str(name).replace('"', '\\"'))),
                                                        decodeXStr('%s'%(str(name).replace('"', '\\"')))),
                                 iif(val is None, 'null', iif(type(val)==str, decodeXStr('"%s"'%(str(val).replace('"', '\\"'))),
                                                              decodeXStr('%s'%(str(val).replace('"', '\\"')))))) #str() need, else error "AttributeError: 'int' object has no attribute 'replace'"
    if skwargs:
        skwargs = '"kwargs": {%s}' % skwargs[:-2]

    #sallargs = '; '.join((sargs, skwargs)) #ne katit
    #sallargs = str(sargs + skwargs).strip()
    sallargs = sargs
    if sallargs:
        if skwargs:
            sallargs += ', ' + skwargs
    else:
        sallargs = skwargs
    sallargs = '{%s}' % sallargs

    table_name = logGetTableName(cls)

    conv_f_doc = convDocString(f_doc)

    db.dbExec(sql='execute procedure prepare_metadata(?)', params=[table_name], fetch='none', id_system=log_system)
    db.dbExec(sql='execute procedure log_insert(?,?,?,?,?,?,?,?,?,?)',
        params=(
            table_name,
            id_system,
            system_name,
            str_cls, #str(cls), #str(args[0].__class__), #.split('.')[-1],
            f_name, #f.__name__ для wrapped-функций возвращает имя wrapped-функции
            code[:20],
            conv_f_doc,
            iif(cpu.getUserVar('uid'), cpu.getUserVar('uid'), '-1'),
            iif(cpu.getUserVar('userfio'), cpu.getUserVar('userfio'), 'SYSTEM'), #cpu.getUserVar('userfio')
            sallargs
        ), fetch='none', id_system=log_system)
Ejemplo n.º 10
0
    def user_layer_add(self, RegAddon, **kwargs):
        """Создаёт слой, базы данных слоя, владельца слоя, назначает ему права на систему по умолчанию.
            Возвращает кортеж (succ, errfields),
            где succ - признак успешности заведения
            errfield - словарь {'name': имя поля с ошибкой, 'errmes': сообщение об ошибке}
        """
        try:
            (layer_id, layer_code, owner_id) = layers.layerCreateAll(
                organization=kwargs['company'],
                fio=kwargs['fio'],
                password=kwargs['passwd'],
                login=kwargs['login'],
                email=kwargs['email'],
                phonenumber=kwargs['phonenumber'],
                tarif=kwargs['tarif'])

            #t.commit()
        except adm.EUserAddBadLogin as e:
            errfield = {'name': 'login', 'errmes': str(e)}
            return (0, [errfield])
        except adm.EUserAddExistsLogin as e:
            errfield = {'name': 'login', 'errmes': str(e)}
            return (0, [errfield])
        except adm.EUserAddExistsEmail as e:
            errfield = {'name': 'email', 'errmes': str(e)}
            return (0, [errfield])
        except layers.ETarLayerSetTarifIdTarNotFound as e:
            errfield = {'name': 'tarif', 'errmes': str(e)}
            return (0, [errfield])
        except Exception as e:
            #t.rollback()
            #import sys
            #errfield = sys.exc_info()[1]
            #errfield = {'name': 'fio', 'errmes': 'Сервис временно недоступен. Повторите попытку позже.'}
            cpu.cherrypylog("UserReg.user_layer_add 1st branch:\n" +
                            tb.format_exc(),
                            context='APP.REG')

            errfield = {
                'name':
                'fio',
                'errmes':
                _('Сервис временно недоступен. Повторите попытку позже.'
                  )
            }  #str(e)} Скрываем причину от пользователя
            return (0, [errfield])
        else:
            #adm.rightAddDefaults(is_registration=True, id_user=res['OUT_ID_USER'], fio=kwargs['fio'], handle_manually=False, params_utf8=False)
            try:
                if RegAddon is not None:
                    # доп. параметры регистрации
                    # передаем только юзера, т.к. поля-аргументы уже сидят в классе
                    kwargs['layer_id'] = layer_id
                    RegAddon.createaccount(user_id=owner_id, **kwargs)
                adm.rightAddDefaults(is_registration=True,
                                     id_user=owner_id,
                                     handle_manually=False,
                                     layer_id=layer_id)
            except ERegAddonCustom as e:
                cpu.cherrypylog(
                    "UserReg.user_layer_add 4 branch ERegAddonCustom:\n" +
                    tb.format_exc(),
                    context='APP.REG')
                if RegAddon is not None and hasattr(
                        RegAddon, 'onException') and callable(
                            getattr(RegAddon, 'onException')):
                    kwargs['exception'] = e
                    errfield = RegAddon.onException(user_id=owner_id, **kwargs)
                if errfield is None:
                    errfield = {
                        'name':
                        'fio',
                        'errmes':
                        _('Сервис временно недоступен. Повторите попытку позже.'
                          )
                    }  #str(e)} Скрываем причину от пользователя
                try:
                    if layer_id:
                        layers.layerDel(layer_id)
                    if owner_id:
                        adm.userDel(
                            owner_id,
                            handle_manually=False,
                            delFromBases=
                            False,  #не удаляем из созданной БД, т.к. далее удаляем саму БД
                            layer_id=layer_id)
                    if layer_code:
                        layers.dbsDel(layer_code)
                except:
                    cpu.cherrypylog(
                        "UserReg.user_layer_add 5 branch ERegAddonCustom:\n" +
                        tb.format_exc(),
                        context='APP.REG')
                    pass
                return (0, [errfield])
            except Exception as e:
                #import cp_utils as cpu
                cpu.cherrypylog("UserReg.user_layer_add 2nd branch:\n" +
                                tb.format_exc(),
                                context='APP.REG')
                #при ошибках назначения прав удаляем инфу о слое и его владельце из БД Engine и созданную БД
                try:
                    if layer_id:
                        layers.layerDel(layer_id)
                    if owner_id:
                        adm.userDel(
                            owner_id,
                            handle_manually=False,
                            delFromBases=
                            False,  #не удаляем из созданной БД, т.к. далее удаляем саму БД
                            layer_id=layer_id)
                    if layer_code:
                        layers.dbsDel(layer_code)
                except:
                    cpu.cherrypylog("UserReg.user_layer_add 3rd branch:\n" +
                                    tb.format_exc(),
                                    context='APP.REG')
                    pass

                errfield = {
                    'name':
                    'fio',
                    'errmes':
                    _('Сервис временно недоступен. Повторите попытку позже.'
                      )
                }  #str(e)} Скрываем причину от пользователя
                return (0, [errfield])
            else:
                return (1, [])
Ejemplo n.º 11
0
    def user_add(self, RegAddon, **kwargs):
        """Непосредственное добавление пользователя в БД
            и добавление прав на предопределённые системы
            Возвращает кортеж (succ, errfields),
            где succ - признак успешности заведения
            errfield - словарь {'name': имя поля с ошибкой, 'errmes': сообщение об ошибке}
        """
        # сначала юзера в движке
        #t = db.Trans(id_system=-1)
        try:
            uid = adm.userAdd(is_registration=True,
                              fio=kwargs['fio'],
                              password=kwargs['passwd'],
                              login=kwargs['login'],
                              email=kwargs['email'],
                              phonenumber=kwargs['phonenumber'],
                              id_user=None,
                              layer_id=None,
                              conEngine=None,
                              handle_manually=False,
                              params_utf8=False)
            """res = adm.userAdd(is_registration=True, fio=kwargs['fio'], password=kwargs['passwd'], login=kwargs['login'],
                    email=kwargs['email'], phonenumber=kwargs['phonenumber'], id_user=None, layer_id=None,
                    conEngine=None, handle_manually=False, params_utf8=False)"""
            """res = t.dbExec(sql='select * from ENGINE_USER_ADD(?,?,?,?,?,?,?)',
                        params=(None,
                                None,
                                kwargs['login'],
                                kwargs['fio'],
                                kwargs['email'],
                                kwargs['phonenumber'],
                                kwargs['passwd']
                                ),
                        fetch='one',
                        id_system=-1
                       )
            """
            # если по каким-то причинам на уровне базы произошла ошибка - возбудим эксепшн
            """if res['ERROR_CODE'] != 0:
                fields = {'name': 'fio', 'errmes': _('Сервис временно недоступен. Повторите попытку позже.')}
                if res['ERROR_CODE'] == 3:
                    fields = {'name': 'email', 'errmes': 'Пользователь с таким email уже зарегистрирован.'}
                if res['ERROR_CODE'] == 2:
                    fields = {'name': 'login', 'errmes': 'Логин уже занят.'}
                raise Exception(fields)
            """
            #t.commit()
        except adm.EUserAddBadLogin as e:
            errfield = {'name': 'login', 'errmes': str(e)}
            return (0, [errfield])
        except adm.EUserAddExistsLogin as e:
            errfield = {'name': 'login', 'errmes': str(e)}
            return (0, [errfield])
        except adm.EUserAddExistsEmail as e:
            errfield = {'name': 'email', 'errmes': str(e)}
            return (0, [errfield])
        except Exception as e:
            #t.rollback()
            #import sys
            #errfield = sys.exc_info()[1]
            #return (0, errfield)
            cpu.cherrypylog("UserReg.user_add 1st branch:\n" + tb.format_exc(),
                            context='APP.REG')

            errfield = {
                'name':
                'fio',
                'errmes':
                _('Сервис временно недоступен. Повторите попытку позже.'
                  )
            }  #str(e)} Скрываем причину от пользователя
            return (0, [errfield])
        else:
            #adm.rightAddDefaults(is_registration=True, id_user=res['OUT_ID_USER'], fio=kwargs['fio'], handle_manually=False, params_utf8=False)
            try:
                if RegAddon is not None:
                    # доп. параметры регистрации
                    # передаем только юзера, т.к. поля-аргументы уже сидят в классе
                    kwargs['layer_id'] = None
                    RegAddon.createaccount(user_id=uid, **kwargs)
                #добавить право на системы по умолчанию
                """if hasattr(scfg, 'autoGrantRefs'):
                    if scfg.autoGrantRefs != []:
                        from systems.ENGINE.ADMINPANEL.admin import AdminPanel
                        import simplejson as json
                        adminPanel = AdminPanel()
                        for href in scfg.autoGrantRefs:
                            id_system = si.find_id_system_by_full_ref_name(href)
                            dumped_d = adminPanel.ajaxAddRight(res['OUT_ID_USER'], pu.convToUTF8(kwargs['fio']), id_system)
                            d = json.loads(dumped_d)
                            if d['data']['ERROR_CODE']:
                                #return self.dump(d)
                                raise Exception('Ошибка при добавлении прав пользователю на систему с id='+str(id_system))
                """

                adm.rightAddDefaults(is_registration=True,
                                     id_user=uid,
                                     handle_manually=False,
                                     layer_id=None)
            except ERegAddonCustom as e:
                cpu.cherrypylog(
                    "UserReg.user_add 4 branch ERegAddonCustom:\n" +
                    tb.format_exc(),
                    context='APP.REG')
                if RegAddon is not None and hasattr(
                        RegAddon, 'onException') and callable(
                            getattr(RegAddon, 'onException')):
                    kwargs['exception'] = e
                    errfield = RegAddon.onException(user_id=uid, **kwargs)
                if errfield is None:
                    errfield = {
                        'name':
                        'fio',
                        'errmes':
                        _('Сервис временно недоступен. Повторите попытку позже.'
                          )
                    }  #str(e)} Скрываем причину от пользователя
                try:
                    if uid:
                        adm.userDel(uid,
                                    handle_manually=False,
                                    delFromBases=True,
                                    layer_id=None)
                except:
                    cpu.cherrypylog(
                        "UserReg.user_add 5 branch ERegAddonCustom:\n" +
                        tb.format_exc(),
                        context='APP.REG')
                    pass
                return (0, [errfield])
            except Exception as e:
                #import cp_utils as cpu
                cpu.cherrypylog("UserReg.user_add 2nd branch:\n" +
                                tb.format_exc(),
                                context='APP.REG')
                #при ошибках назначения прав удаляем инфу о слое и его владельце из БД Engine и созданную БД
                try:
                    if uid:
                        adm.userDel(uid,
                                    handle_manually=False,
                                    delFromBases=True,
                                    layer_id=None)
                except:
                    cpu.cherrypylog("UserReg.user_add 3rd branch:\n" +
                                    tb.format_exc(),
                                    context='APP.REG')
                    pass

                errfield = {
                    'name':
                    'fio',
                    'errmes':
                    _('Сервис временно недоступен. Повторите попытку позже.'
                      )
                }  #str(e)} Скрываем причину от пользователя
                return (0, [errfield])
            else:
                return (1, [])
Ejemplo n.º 12
0
class Updater(BasePage):  #, TCommon):
    def index(self, id_system=None):
        BasePage.index(self, id_system)
        #raise cherrypy.HTTPRedirect('users')
        #return self.users() - если так, то при F5 чистится сессия, т.к. вызывается self.index
        bases = db.dbExec(
            sql=
            'select B.ID_BASE, B.DBALIAS, B.SHOW_NAME, S.IP from UPD_BASES B '
            '  left join SERVERS S on S.ID_SERVER=B.ID_SERVER '
            'order by B.ORDERBY ',
            params=(),
            fetch='all',
            id_system=-1)
        bases['datalist_bases'] = bases['datalist']
        del bases['datalist']

        modules = db.dbExec(
            sql=
            'select M.ID_MODULES, M.MALIAS, M.SHOW_NAME, S.IP from UPD_MODULES M '
            '  left join SERVERS S on S.ID_SERVER=M.ID_SERVER '
            'order by M.ORDERBY ',
            params=(),
            fetch='all',
            id_system=-1)
        modules['datalist_modules'] = modules['datalist']
        del modules['datalist']

        bond = db.dbExec(
            sql='select BO.ID_BASE, BO.ID_MODULES from UPD_BOND BO ',
            params=(),
            fetch='all',
            id_system=-1)
        bond['datalist_bond'] = bond['datalist']
        del bond['datalist']
        userfio = self.getUserVar('userfio')
        userid = self.getUserVar('uid')
        curtime = str(time.time())
        return self.drawTemplate(templ=updater_tmpl,
                                 data=[
                                     bases, modules, bond, userfio, {
                                         "userid": userid
                                     }, {
                                         "curtime": curtime
                                     }
                                 ])

    index.exposed = True

    def dump(self, data, ext_data=None, formats={}):
        #print "========dump==============="
        return self.pyDumps(data=data, ext_data=ext_data, formats=formats)
        #return json.dumps(data, encoding='cp1251')

    def upload_stats(self):
        try:
            #print "INVOKING upload_stats"
            import threading
            #print threading.currentThread()
            if not hasattr(cherrypy, 'file_transfers'):
                #print "======"
                #print "not hasattr(cherrypy, 'file_transfers')"
                #print "======"
                return self.pyDumps(data={'status': 'starting'})

            #print "*****"
            #print "HASATTR!!!"
            #print "*****"

            #global file_transfers
            #print "======"
            #print file_transfers
            #print "======"
            if not cherrypy.file_transfers.has_key(cherrypy.request.remote.ip):
                #print "no key ", cherrypy.request.remote.ip
                return self.pyDumps(data={'status': 'starting'})

            stat = cherrypy.file_transfers[cherrypy.request.remote.ip]
            #print "======"
            #print stat
            #print "======"
            # Convert everything to KBs and return
            for key, val in stat.iteritems():
                speed = '%9.2f' % (val.speed / 1024.0)
                total = '%9.2f' % (val.pre_sized / 1024.0)
                transfered = '%9.2f' % (val.transfered / 1024.0)
                eta = str(int(val.eta))

                done = val.transfered / val.pre_sized
                done = str(300 * done)
                #Logger.info("Upload Stats: fn: %s speed: %s total: %s transferred: %s" % (key, speed, total, transfered))
                #print "transfered = ", transfered
                return self.pyDumps(
                    data={
                        'status': 'uploading',
                        'filename': key,
                        'speed': speed,
                        'total': total,
                        'transfered': transfered,
                        'eta': eta,
                        'done': done
                    })
        except KeyError:
            #Logger.info("Upload Stats: returning done")
            # If there are no entries by our IP, then we have nothing.
            #raise
            #del_file_transfers()
            #raise
            #print "status=done"
            return self.pyDumps(data={'status': 'done'})

    upload_stats.exposed = True

    @cherrypy.tools.noBodyProcess()
    def upload(self):
        #print "upload: ", self.getIfaceVar("id_system")
        """upload action

        We use our variation of FieldStorage to parse the MIME
        encoded HTML form data containing the file."""

        #print "x"*5252
        #print "UPLOAD STARTS"
        #print "x"*5252

        #ignore no authorized scripts
        LOGIN = self.getUserVar('login')
        if not LOGIN:
            return 'Нельзя заливать скрипты с утерянной авторизацией!'
        #print "LOGIN="******"0"
        whatsnew = []

        formFields = FieldStorage(fp=cherrypy.request.rfile,
                                  headers=lcHDRS,
                                  environ={'REQUEST_METHOD': 'POST'},
                                  keep_blank_values=True)

        whatsnew = pu.format(
            json.loads((formFields['whatsnewdic'].value
                        ).decode("windows-1251").encode("utf-8")))
        try:
            t = self.trans()
        except Exception, exc:
            return str(exc)

        try:
            #print "BEFORE CREATING FieldStorage"
            # formFields = FieldStorage(fp=cherrypy.request.rfile,
            # headers=lcHDRS,
            # environ={'REQUEST_METHOD':'POST'},
            # keep_blank_values=True)

            dicparams['ID_BASE'] = formFields['upd_base_cmb'].value
            dicparams['ID_MODULES'] = formFields['upd_module_cmb'].value
            dicparams['FILENAME'] = ""

            #print "AFTER CREATING FieldStorage"
            theFile = formFields['upd_file']
            #print "AFTER 2 CREATING theFile"
            # theFile has 2 attributes:
            #    - filename contains the name of the uploaded file
            #    - file is an input stream opened for reading

            #print formFields

            base = formFields['upd_base_cmb'].value
            module = formFields['upd_module_cmb'].value
            #print "====="
            #Получаем имя каталога
            if hasattr(cfg, 'upd_conf_location'):
                upd_conf = pu.importer(cfg.upd_conf_location)
                if hasattr(upd_conf, 'upload_path'):
                    cat = upd_conf.upload_path
                else:
                    return cpu.goToError(
                        'В конфигурационном файле ' +
                        cfg.upd_conf_location +
                        ' отстутсвует параметр upload_path')
            else:
                return cpu.goToError(
                    'Отстутсвует параметр конфигурации upd_conf_location'
                )
            #cat='c:/tmp'
            pu.mk_dir(cat)
            ld = os.listdir(cat)
            #print "ld: ", ld
            ld_7z = filter(
                lambda fn: os.path.splitext(fn)[1] == '.7z' and len(
                    fn.split('=')) > 1 and fn.split('=')[1].isdigit(), ld)
            ld_7z.sort()
            #ld_7z.reverse()
            #print "ld_7z: ", ld_7z

            #last_7z=os.path.join(cat, ld[0])
            if ld_7z == []:
                NN = '01'
                #print "if ld_7z==[]: NN='01'"
            else:
                last_7z = ld_7z[len(ld_7z) - 1]
                #print "last_7z=", last_7z
                last_NN = last_7z.split('=')[1]
                #print "civil last_NN:", last_NN
                NN = "%02d" % (int(last_NN) + 1)
            tt = time.localtime(time.time())
            YYYY = time.strftime('%Y', tt)
            MM = time.strftime('%m', tt)
            DD = time.strftime('%d', tt)
            #import pPrinter
            #print "*"*52
            #import pprint
            #pPrinter = pprint.PrettyPrinter(indent=8)
            #pPrinter.pprint(formFields)
            #print "===\n",kwargs
            #print "===\n", base, module
            #print "*"*52
            MALIAS = self.dbExec(
                sql="select MALIAS from UPD_MODULES where ID_MODULES=?",
                fetch="one",
                params=(module, ))['MALIAS']
            DBALIAS = self.dbExec(
                sql="select DBALIAS from UPD_BASES where ID_BASE=?",
                fetch="one",
                params=(base, ))['DBALIAS']
            FILENAME = theFile.filename
            FILENAME = os.path.basename(FILENAME)
            FILENAME = FILENAME[FILENAME.rfind('\\') +
                                1:]  #IE fix full file names
            shortname = "%(YYYY)s-%(MM)s-%(DD)s=%(NN)s=%(MALIAS)s=%(DBALIAS)s=%(LOGIN)s=%(FILENAME)s" % vars(
            )
            fullname = os.path.join(cat, shortname)

            #print fullname
            #print NN
            #print "====="
            #for item in ld:
            #    fn = pathesJoin([cat,item])
            #    if os.path.isfile(fn) and os.path.splitext(fn)[1]=='.sql':

            # Read the tempfile and store it in the final file
            f = open(fullname, 'wb')
            while 1:
                data = theFile.file.read(1024 *
                                         8)  # Read blocks of 8KB at a time
                if not data: break
                f.write(data)
            f.close()

            #print "====================="
            #print "src = theFile.file.name=",theFile.file.name
            #print "dst = '/tmp/'+theFile.filename",'/tmp/'+theFile.filename
            #print "====================="
            #os.link(theFile.file.name, '/tmp/'+theFile.filename)
            dicparams['FILENAME'] = fullname
            dicparams['STATUS'] = '1'

            dbRes = t.dbExec(sql='select * from UPD_INSERTUPDATE(?,?,?,?,?)', params=[dicparams['DEVEL_ID'],\
                                    dicparams['ID_BASE'], dicparams['ID_MODULES'], dicparams['FILENAME'],\
                                    dicparams['STATUS']], fetch='one', id_system=-1)
            for item in whatsnew:
                wnRes = t.dbExec(sql='select * from UPD_WHATSNEWINSERT(?,?,?,?,?)', params=[dbRes['IDUPDATE'],\
                                        str(item['id_system']), str(item['id_type']), str(item['redmine']),\
                                        str(item['description'])],\
                                        fetch="one", id_system=-1)

            self.analyseUpdateFile(fullname, dbRes['IDUPDATE'])

            t.commit()
            return
            #return ("ok, получили файл '%s'. Файл был сохранён как "+fullname) % theFile.filename

        except Exception, exc1:
            import traceback as tb
            tb_str = tb.format_exc()
            cpu.cherrypylog('upload: branch 1\n%s' % tb_str, context='UPDATER')

            e_str1 = str(exc1)
            e_str2 = ''
            e_str3 = ''

            t.rollback()
            dicparams['FILENAME'] = None
            dicparams['STATUS'] = '0'
            t = self.trans()
            try:
                dbRes = t.dbExec(sql='select * from UPD_INSERTUPDATE(?,?,?,?,?)', params=[dicparams['DEVEL_ID'],\
                                        dicparams['ID_BASE'], dicparams['ID_MODULES'], dicparams['FILENAME'],\
                                        dicparams['STATUS']], fetch='one', id_system=-1)
                for item in whatsnew:
                    wnRes = t.dbExec(sql='select * from UPD_WHATSNEWINSERT(?,?,?,?,?)', params=[dbRes['IDUPDATE'],\
                                            str(item['id_system']), str(item['id_type']), str(item['redmine']),\
                                            str(item['description'])],\
                                            fetch="one", id_system=-1)
                t.commit()
            except Exception, exc2:
                tb_str2 = tb.format_exc()
                cpu.cherrypylog('upload: branch 2\n%s' % tb_str2,
                                context='UPDATER')
                e_str2 = str(exc2)
                t.rollback()
                try:
                    del_file_transfers()
                except Exception, exc3:
                    tb_str3 = tb.format_exc()
                    cpu.cherrypylog('upload: branch 3\n%s' % tb_str3,
                                    context='UPDATER')
                    e_str3 = str(exc3)
Ejemplo n.º 13
0
    def draw_system_list_term(self, code, termnum):
        # код завершения смены
        if code == cfg.TERMINAL_LOGOFF_BARCODE:
            # запрос на закрытие сессии в RBS
            mes = sessions.rbs_close_check(self.getSesVar('termiduser'))

            # не разрешено закрывать сессию
            if mes:
                return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                    data=[{'termname': self.getSesVar('termname'), 'termusername': self.getSesVar('termusername'), 'mes': mes}], draw_wo_login=True)

            # получено разрешение из RBS на закрытие сессии
            # попытка закрыть сессию
            error_msg, web_session_id = sessions.session_close(uid=self.getSesVar('termiduser'),
                                               fio=self.getSesVar('termusername'),
                                               equip_kind=pu.iif(cpu.isMobile(), 'M', 'T'),
                                               reason=sessions.SES_CLOSE_REASON_EXIT,
                                               closed_by=None)
            # ошибка закрытия сессии
            if error_msg:
                cpu.cherrypylog(error_msg, context='APP.SESSIONS')
                return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                    data=[{'termname': self.getSesVar('termname'), 'termusername': self.getSesVar('termusername'), 'mes': error_msg}], draw_wo_login=True)
            # сессия закрыта успешно
            termusername = self.getSesVar('termusername')
            self.exit(redirect=False)
            return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                data=[{'termname': self.getSesVar('termname'), 'termusername': '', 'mes': 'Сессия пользователя '+termusername+' закрыта'}], draw_wo_login=True)

        # валидация длины введённого ШК и его целостности
        if not term_verify_barcode(code):
            return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                data=[{'termname': self.getSesVar('termname'), 'termusername': self.getSesVar('termusername'), 'mes': 'Отсканирован не ШК пользователя'}], draw_wo_login=True)

        # структура ШК верна - верифицируем его и определяем пользователя

        usr = db.dbExec(sql='select * from ENGINE_USER_VERIFY_TERM(?)',
                        params=[code], fetch='one', id_system=-1)
        if usr['ERROR_CODE']!=0:
            if usr['ERROR_CODE']==5:
                # пользователь найден, а ШК - нет

                # сверяем дату генерации ШК в БД и отсканированного ШК
                msg_check_barcode_date = check_barcode_date(code, usr['BARCODE_OUT'])
                if msg_check_barcode_date:
                    return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                        data=[{'termusername': usr['FIO'], #'termusername': self.getSesVar('termusername'),
                               'termname': self.getSesVar('termname'),
                               'mes': msg_check_barcode_date
                            }], draw_wo_login=True)


                # валидация длины ШК в БД и его целостности
                if not term_verify_barcode(usr['BARCODE_OUT']):
                    return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                        data=[{'termusername':usr['FIO'], #'termusername': self.getSesVar('termusername'),
                               'termname': self.getSesVar('termname'),
                               'mes': 'Испорчен ШК в базе данных. Обратитесь в службу поддержки!'}], draw_wo_login=True)

                # неизвестная ошибка в ШК
                return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                    data=[{'termusername':usr['FIO'], #'termusername': self.getSesVar('termusername'),
                           'termname': self.getSesVar('termname'),
                           'mes': 'Неизвестная ошибка в ШК. Обратитесь в службу поддержки!'}], draw_wo_login=True)

            else:
                #2 - 'Пользователь не заведён в системе!' или другая будущая ошибка
                return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                    data=[{'termname': self.getSesVar('termname'),
                           'termusername': self.getSesVar('termusername'),
                           'mes': usr['ERROR_MSG']}], draw_wo_login=True)

        if getattr(cfg, 'SKUD_INTEGRATION', False) and \
                (getattr(cfg, 'SKUD_CHECK_MOBILE', False) and cpu.isMobile() or
                getattr(cfg, 'SKUD_CHECK_TSD', False) and cpu.isTSD()):
            allow = db.dbExecDirect(sql='select ALLOW from %s(?)' % cfg.SKUD_MAJOR_DB_ACCESS_PROC,
                                    params=[usr['ID_USER']],
                                    fetch='one', id_base=db.getIdMajorDb())['ALLOW']
            if not allow:
                if cpu.isTSD():
                    return cpu.goToError(_('Доступ запрещён по данным СКУД!'))
                else:
                    return self.exception_inner(tmpl_name='exception_skud_access_mob', data={'userfio': usr['FIO']})

        # заказан ли проброс для этого вида оборудования в конфиге
        probros = pu.iif(cpu.isMobile(),
                         getattr(cfg, 'sessions_forward_to_last_iface_mob', None),
                         getattr(cfg, 'sessions_forward_to_last_iface_term', None))
        if probros:
            # читаем данные последней сессии
            error_msg, go_url, ses_info = sessions.session_last_session_info(uid=usr['ID_USER'], fio=usr['FIO'],
                                                                             equip_kind=pu.iif(cpu.isMobile(), 'M', 'T')
            )
            # ошибка получения информации о последней сессии
            if error_msg:
                cpu.cherrypylog(error_msg, context='APP.SESSIONS')
                probros = False

        # открываем сессию
        old_web_session_id, error_msg = sessions.session_open(uid=usr['ID_USER'], fio=usr['FIO'],
                                                              equip_kind=pu.iif(cpu.isMobile(), 'M', 'T'),
                                                              termnum=termnum)

        # ошибка открытия сессии
        if error_msg:
            cpu.cherrypylog(error_msg, context='APP.SESSIONS')
            return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),
                data=[{'termname': self.getSesVar('termname'), 'termusername': usr['FIO'], 'mes': error_msg}],
                draw_wo_login=True)

        # удаляем старую web-сессию, если она есть
        if old_web_session_id:
            sessions.session_delete_old_web_session(old_web_session_id)

        # залогинились

        #print "draw_system_list_term: id_user=%s, fio=%s, barcode=%s" %( usr['ID_USER'], self.df(usr['FIO']), usr['BARCODE_OUT'])

        # заполняем переменные сессии юзера
        create_user_session_class(login=usr['LOGIN'], uid=usr['ID_USER'], userfio=usr['FIO'], email=usr['EMAIL'],
                                  phonenumber=usr['PHONENUMBER'], layer_id=usr['LAYER_ID'],
                                  locale=usr['LANG_CODE'] or self.getSesVar('locale'),
                                  is_superadmin=usr['IS_SUPERADMIN'])
        self.setSesVar('termiduser', usr['ID_USER'])
        self.setSesVar('termusername', usr['FIO'])

        # далее реализуем проброс

        # проброс в зависимости от настроек конфиругации и наличия последней сохранённой сессии
        if probros and go_url:
            # если error_msg пусто, то go_url заполнено - переходим в него
            raise cherrypy.HTTPRedirect(go_url)
        else:
            # иначе - анализируем
            # получаем доступные системы нулевого уровня, сортируя по cfg.systems_order
            systems = get_user_systems(uid=self.getUserVar("uid"), higher=None, recurse=0, use_layers=None)
            # если юзер не имеет прав ни на одну из систем нулевого уровня
            if len(systems['datalist'])==0:
                return self.drawTemplate(templ=pu.iif(cpu.isMobile(), login_index_mob, login_index_term),data=[{'mes':'Пользователь не имеет прав ни на одну систему'}], draw_wo_login=True)

            # если у юзера есть право на KURSTERM или WMSMOBILE и список систем в нём непуст, то перебрасываем в KURSTERM или WMSMOBILE
            if cpu.isMobile():
                # если у юзера есть право на WMSMOBILE
                if getattr(cfg, 'MOBILE_link', None) in self.getUserVar('granted_system_refs'):

                    # получить id_system для системы WMSMOBILE
                    MOBILE_id_system = si.find_id_system_by_full_ref_name(cfg.MOBILE_link)
                    #TERMINAL_id_system=db.dbExec(sql='select ID_SYSTEM from ENGINE_FIND_SYSTEM_BY_FULL_REF(?)',
                    #    params=[cfg.TERMINAL_link], fetch='one', id_system=-1)['ID_SYSTEM']

                    # получить список доступных юзеру подсистем в системе WMSMOBILE
                    mobile_subsystems = get_user_systems(uid=self.getUserVar("uid"), higher=MOBILE_id_system, recurse=0, use_layers=None)
                    # если список доступных юзеру подсистем в системе WMSMOBILE содержит одну запись(возможно, OLDTERM), то перебрасываем в неё
                    if len(mobile_subsystems['datalist']) == 1:
                        #raise cherrypy.HTTPRedirect(terminal_subsystems['datalist'][0]['FULL_REF_NAME']+'/?id_system='+ str(terminal_subsystems['datalist'][0]['ID_SYSTEM']))
                        raise cherrypy.HTTPRedirect(mobile_subsystems['datalist'][0]['FULL_REF_NAME'])
                    # иначе перебрасываем в WMSMOBILE
                    else:
                        #raise cherrypy.HTTPRedirect(cfg.TERMINAL_link+'/?id_system='+ str(TERMINAL_id_system))
                        raise cherrypy.HTTPRedirect(cfg.MOBILE_link)
            else:
                # если у юзера есть право на KURSTERM
                if getattr(cfg, 'TERMINAL_link', None) in self.getUserVar('granted_system_refs'):

                    # получить id_system для системы KURSTERM
                    TERMINAL_id_system = si.find_id_system_by_full_ref_name(cfg.TERMINAL_link)
                    #TERMINAL_id_system=db.dbExec(sql='select ID_SYSTEM from ENGINE_FIND_SYSTEM_BY_FULL_REF(?)',
                    #    params=[cfg.TERMINAL_link], fetch='one', id_system=-1)['ID_SYSTEM']

                    # получить список доступных юзеру подсистем в системе KURSTERM
                    terminal_subsystems = get_user_systems(uid=self.getUserVar("uid"), higher=TERMINAL_id_system, recurse=0, use_layers=None)
                    # если список доступных юзеру подсистем в системе KURSTERM содержит одну запись(возможно, OLDTERM), то перебрасываем в неё
                    if len(terminal_subsystems['datalist']) == 1:
                        #raise cherrypy.HTTPRedirect(terminal_subsystems['datalist'][0]['FULL_REF_NAME']+'/?id_system='+ str(terminal_subsystems['datalist'][0]['ID_SYSTEM']))
                        raise cherrypy.HTTPRedirect(terminal_subsystems['datalist'][0]['FULL_REF_NAME'])
                    # иначе перебрасываем в KURSTERM
                    else:
                        #raise cherrypy.HTTPRedirect(cfg.TERMINAL_link+'/?id_system='+ str(TERMINAL_id_system))
                        raise cherrypy.HTTPRedirect(cfg.TERMINAL_link)

            # если у юзера есть права более, чем на 1 систему - рисуем список систем на выбор
            if len(systems['datalist'])>1:
                #return self.drawTemplate(templ=choose_your_destiny,data=[systems])
                return self.drawTemplate(templ=pu.iif(cpu.isMobile(), subsystem_list_mob, subsystem_list_term),
                                         data=[systems, {'system_name': _('Выберите систему')}])

            # если у юзера есть право только на одну систему, то перебрасываем в неё
            if len(systems['datalist'])==1:
                #self.setSesVar("id_system",systems['datalist'][0]['ID_SYSTEM'])
                #raise cherrypy.HTTPRedirect(systems['datalist'][0]['FULL_REF_NAME']+'/?id_system='+ str(self.getSesVar("id_system")))
                #print "if len(systems['datalist'])==1:"
                #raise cherrypy.HTTPRedirect(systems['datalist'][0]['FULL_REF_NAME']+'/?id_system='+ str(systems['datalist'][0]['ID_SYSTEM']))
                raise cherrypy.HTTPRedirect(systems['datalist'][0]['FULL_REF_NAME'])
Ejemplo n.º 14
0
    def draw_system_list(self, username, password, first_time=0, pwd_is_hash='0'):
        u"""Валидация логина и пароля и проброс вглубь дерева подсистем.
            Возвращает словарь {'ERROR_CODE': ERROR_CODE, 'ERROR_MSG': ERROR_MSG, 'REDIRECT_CODE': REDIRECT_CODE,
              'REDIRECT_DATA': REDIRECT_DATA}, где
            ERROR_CODE - ERROR_MSG:
            '0' - null (удачно)
            '1' - "Не указан логин"
            '2' - "Пользователь не заведён в системе!"
            '3' - "Администратор не установил Ваш пароль!"
            '4' - "Неверный пароль!"
            '5' - "Не указан пароль!"
            '6' - "Пароль не переустановлен пользователем!"
            '100' - "Организация временно отключена" (слой отключён)
            '110' - "Доступ запрещён по данным СКУД"
            '120' - "Ошибка открытия сессии..."
            REDIRECT_CODE: 0 - REDIRECT_DATA содержит url для проброса (перейти в него изнутри движка так: cp_utils.HTTPRedirect(REDIRECT_DATA))
                           1 - REDIRECT_DATA содержит отрисованную html-страницу авторизации со списком систем, если ERROR_CODE==0 или с ошибкой, если ERROR_CODE!=0
                           2 - REDIRECT_DATA содержит текст ошибки, для отображения на отдельной странице ошибки (перейти в него изнутри движка так: cp_utils.goToError(REDIRECT_DATA))

            Если ERROR_CODE==0, то REDIRECT_CODE in [0, 1].
            Если ERROR_CODE!=0, то REDIRECT_CODE in [1, 2].

        """

        # обрабатываем параметры
        if pwd_is_hash in ['0', '', None]:
            pwd_is_hash = False
        else:
            pwd_is_hash = True

        # инициализируем результат
        result = {'ERROR_CODE': 0, 'ERROR_MSG': None, 'REDIRECT_CODE': 0, 'REDIRECT_DATA': ''}

        #снова выставляем переменные, если пользователь попал на login минуя index
        #например, нажал в браузере "Обновить" на форме списка систем
        self.setSesVar('termiduser', None)
        self.setSesVar('termusername', None)
        self.setSesVar('termnum', None)
        self.setSesVar('termname', None)

        usr = verify_user(username, password, pwd_is_hash=pwd_is_hash)
        if usr['ERROR_CODE']:
            result['ERROR_CODE'] = usr['ERROR_CODE']
            result['ERROR_MSG'] = usr['ERROR_MSG']
            result['REDIRECT_CODE'] = 1
            if usr['ERROR_CODE'] == 6:
                self.setSesVar('tmp_uid', usr['ID_USER'])
                self.setSesVar('tmp_login', username)
                result['REDIRECT_DATA'] = self.drawTemplate(templ=login_change_passwd,
                                                            data=[{'username': username, 'mes': '', 'uid': self.getSesVar('tmp_uid')},
                                                                  {'langs': cpu.getConfigLangs()}],
                                                            draw_wo_login=True)
            else:
                result['REDIRECT_DATA'] = self.drawTemplate(templ=login_index,
                                                            data=[{'username': username, 'mes': usr['ERROR_MSG']},
                                                                  {'langs': cpu.getConfigLangs()}],
                                                            draw_wo_login=True)
            return result

        #if password == '':
        #    return self.drawTemplate(templ=login_index,data=[{'username':username, 'mes':'Введите пароль пож-та'}], draw_wo_login=True)

        # залогинились
        # проверяем здесь, а не в cpu.sec для ускорения ответа сервера
        # и не чистим SesVar('ip_addr') при выходе из Курса (exit), чтоб запомнить и вычислить пересечения сессий
        # за всё время хранения сессий
        # если бы сессии хренились в файле, то можно было бы не перевходить и продолжалось бы пересечения
        # и пришлось бы обрабатывать в sec
        # но т.к. в RAM и часто перегружается
        # cherrypy.session.id - есть гарантировано здесь, проверено, даже когда чистят куки, id уже сформирован к этому времени
        #print self.getSesVar('ip_addr'), cpu.get_remote_ip(), sessions.session_id()
        #if self.getSesVar('ip_addr') is None:
        #    self.setSesVar('ip_addr', cpu.get_remote_ip())
        #elif self.getSesVar('ip_addr') != cpu.get_remote_ip():
        #    raise CrossSessionsException(
        #        'Пересечение сессий! Очистите куки браузера! Ваш ip=%s пересекается с ip=%s по session_id=%s'
        #        % (cpu.get_remote_ip(), self.getSesVar('ip_addr'), sessions.session_id()))

        """ Бывшая проверка пересечения сессий в УР
        session_ip = self.getSesVar('ip_addr')
        real_ip = cpu.get_remote_ip(if_proxy='client') # if_proxy='client' - чтоб если входим 2-й раз, не нажимая Выход, не выдавало пересечение сессий (если не рвался инет)
        if session_ip is None:
            self.setSesVar('ip_addr', real_ip)
        elif session_ip != real_ip and usr['ID_USER'] != self.getUserVar('uid') and self.getKursZoneId(usr['ID_USER']) != self.getKursZoneId(self.getUserVar('uid')):
            cpu.cherrypylog('---------------------CROSS SESSIONS---------------------')
            cpu.cherrypylog('Entering user: login=%s, uid=%d, userfio=%s' % (username, usr['ID_USER'], usr['FIO']))
            cpu.cherrypylog('Request headers:\n'+self.df(cherrypy.request.headers))
            cpu.cherrypylog('Existing session info:')
            raise CrossSessionsException(
                'Пересечение сессий! Возможно, у Вас изменился ip-адрес. Очистите куки браузера, нажмите на ссылку <a href="/exit">Выход</a> и перезайдите в КУРС! Ваш ip=%s пересекается с ip=%s по session_id=%s.'
                % (real_ip, session_ip, sessions.session_id()))
        """

        # активируем переменные сессии
        #self.setSesVar("login",username)
        #self.setSesVar("uid",usr['ID_USER'])
        #self.setSesVar("userfio",usr['FIO'])

        #print "draw_system_list: self.getUserVar('uid'): ", self.getUserVar("uid")

        #self.setSesVar("is_admin",usr['IS_ADMIN'])
        # рисуем админпанель
        #if usr['IS_ADMIN']:
        #  self.setSesVar("granted_system_refs", ['admin'])
        #  raise cherrypy.HTTPRedirect('/admin')

        if layers.layersIsUse() and not adm.userIsSuperAdmin(uid=usr['ID_USER']):
            li = layers.layerInfo(layer_id=usr['LAYER_ID'])
            layer_disabed = li['DISABLED']
            if layer_disabed is not None and layer_disabed != 0: #or layers.tar_layer_expired_days_remains(layer_id=usr['LAYER_ID']) <= 0:
                result['ERROR_CODE'] = 100
                result['ERROR_MSG'] = _('Ваша организация временно отключена. Обратитесь в службу поддержки, если считаете это необоснованным.')
                result['REDIRECT_CODE'] = 2
                result['REDIRECT_DATA'] = result['ERROR_MSG']
                return result

        if getattr(cfg, 'SKUD_INTEGRATION', False) and cpu.isPC() and getattr(cfg, 'SKUD_CHECK_PC', False):
            allow = db.dbExecDirect(sql='select ALLOW from %s(?)' % cfg.SKUD_MAJOR_DB_ACCESS_PROC,
                                    params=[usr['ID_USER']],
                                    fetch='one', id_base=db.getIdMajorDb())['ALLOW']
            if not allow:
                result['ERROR_CODE'] = 110
                result['ERROR_MSG'] = _('Доступ запрещён по данным СКУД!')
                result['REDIRECT_CODE'] = 2
                result['REDIRECT_DATA'] = result['ERROR_MSG']
                return result

        probros = False
        go_url = ''
        if not first_time:
            # заказан ли проброс для этого вида оборудования в конфиге
            probros = cfg.sessions_forward_to_last_iface_pc
            if probros:
                # читаем данные последней сессии
                error_msg, go_url, ses_info = sessions.session_last_session_info(uid=usr['ID_USER'], fio=usr['FIO'],
                                                                                 equip_kind='P')
                # ошибка получения информации о последней сессии
                if error_msg:
                    cpu.cherrypylog(error_msg, context='APP.SESSIONS')
                    probros = False

        #открываем сессию
        old_web_session_id, error_msg = sessions.session_open(uid=usr['ID_USER'], fio=usr['FIO'], equip_kind='P')

        # ошибка открытия сессии
        if error_msg:
            cpu.cherrypylog(error_msg, context='APP.SESSIONS')
            result['ERROR_CODE'] = 120
            result['ERROR_MSG'] = error_msg
            result['REDIRECT_CODE'] = 1
            result['REDIRECT_DATA'] = self.drawTemplate(templ=login_index,
                                                        data=[{'mes': error_msg}, {'langs': cpu.getConfigLangs()}],
                                                        draw_wo_login=True)
            return result

        # удаляем старую web-сессию
        if old_web_session_id:
            sessions.session_delete_old_web_session(old_web_session_id)

        # заполняем переменные сессии юзера
        create_user_session_class(login=username, uid=usr['ID_USER'], userfio=usr['FIO'], email=usr['EMAIL'],
                                  phonenumber=usr['PHONENUMBER'], layer_id=usr['LAYER_ID'],
                                  locale=usr['LANG_CODE'] or self.getSesVar('locale'),
                                  is_superadmin=usr['IS_SUPERADMIN'])

        # далее реализуем проброс

        # проброс в зависимости от настроек конфигурации и наличия последней сохранённой сессии
        # после регистрации (1-й вход) не делаем проброс в последнюю систему
        if not first_time and probros and go_url:
            # если error_msg пусто, то go_url заполнено - переходим в него
            cpu.cherrypylog(error_msg, context='APP.SESSIONS')
            result['ERROR_CODE'] = 0
            result['ERROR_MSG'] = None
            result['REDIRECT_CODE'] = 0
            result['REDIRECT_DATA'] = go_url
            return result
        else:
            # иначе - анализируем
            # получаем рекурсивно доступные системы, сортируя по cfg.systems_order
            systems = get_user_systems(uid=self.getUserVar("uid"), higher=None, recurse=1, use_layers=None)
            # если юзер не имеет прав ни на одну из систем
            if len(systems['datalist']) == 0:
                result['ERROR_CODE'] = 0
                result['ERROR_MSG'] = None
                result['REDIRECT_CODE'] = 1
                result['REDIRECT_DATA'] = self.drawTemplate(templ=login_index,
                                                            data=[{'mes': _('Пользователь не имеет прав ни на одну систему')},
                                                                  {'langs': cpu.getConfigLangs()}],
                                                            draw_wo_login=True)
                return result

            # если у юзера есть право на КУРС, то перебрасываем в него
            """KURS_link = '/KURS'
            KURS_found = False
            for dic in systems['datalist']:
                if KURS_link == dic['FULL_REF_NAME']:
                    KURS_found = True
                    KURS_id_system = dic['ID_SYSTEM']
                    break
            if KURS_found:
                raise cherrypy.HTTPRedirect(KURS_link+'/?id_system='+ str(KURS_id_system))
            """

            link_found = False
            FULL_REF_NAMES = map(lambda system: system['FULL_REF_NAME'], systems['datalist'])

            if first_time:
                # если у юзера есть право на одну из систем cfg.REDIRECT_LINKS_AFTER_REG, то пробрасываем в неё
                for link in cfg.REDIRECT_LINKS_AFTER_REG:
                    if link in FULL_REF_NAMES:
                        link_found = True
                        break
            else:
                # если у юзера есть право на одну из систем cfg.REDIRECT_LINKS, то пробрасываем в неё
                for link in cfg.REDIRECT_LINKS:
                    if link in FULL_REF_NAMES:
                        link_found = True
                        break

            if link_found:
                #raise cherrypy.HTTPRedirect(link+'/?id_system='+ str(link_id_system))
                result['ERROR_CODE'] = 0
                result['ERROR_MSG'] = None
                result['REDIRECT_CODE'] = 0
                result['REDIRECT_DATA'] = link
                return result

            # получаем доступные системы нулевого уровня, сортируя по cfg.systems_order
            systems0 = get_user_systems(uid=self.getUserVar("uid"), higher=None, recurse=0, use_layers=None)

            # если у юзера есть права более, чем на 1 систему - рисуем список систем на выбор
            if len(systems0['datalist']) > 1:
                #return self.drawTemplate(templ=choose_your_destiny,data=[systems0])
                result['ERROR_CODE'] = 0
                result['ERROR_MSG'] = None
                result['REDIRECT_CODE'] = 1
                result['REDIRECT_DATA'] = self.drawTemplate(templ=subsystem_list,
                                                            data=[systems0, {'system_name': _('Выберите систему'),
                                                                             'first_time': first_time}])
                return result

            # если у юзера есть право только на одну систему, то перебрасываем в неё
            if len(systems0['datalist']) == 1:
                #self.setSesVar("id_system",systems0['datalist'][0]['ID_SYSTEM'])
                #raise cherrypy.HTTPRedirect(systems0['datalist'][0]['FULL_REF_NAME']+'/?id_system='+ str(self.getSesVar("id_system")))
                #print "if len(systems0['datalist'])==1:"
                #raise cherrypy.HTTPRedirect(systems0['datalist'][0]['FULL_REF_NAME']+'/?id_system='+ str(systems0['datalist'][0]['ID_SYSTEM']))
                result['ERROR_CODE'] = 0
                result['ERROR_MSG'] = None
                result['REDIRECT_CODE'] = 0
                result['REDIRECT_DATA'] = systems0['datalist'][0]['FULL_REF_NAME']
                return result