Exemple #1
0
def checkLicense(module_name, replace=False):
    check = False
    version_type = License().getVersionType()
    if version_type == 'U':
        check = True
    elif module_name == 'user':
        license_user_num = int(License().getUsers())
        now_users_num = OmUser.objects.filter(
            delete=False, is_active=True).exclude(username='******').count()
        if now_users_num < license_user_num:
            check = True
        else:
            check = False
    elif module_name == 'app':
        license_app_num = int(License().getApps())
        now_app_num = ActiveApplication.objects.filter(
            app_attr__in=['user', 'cloud'], undeploy_flag=False).count()
        if replace:
            now_app_num = now_app_num - 1
        if now_app_num < license_app_num:
            check = True
        else:
            check = False
    elif module_name == 'collector':
        if check_app('ommonitor'):
            from ommonitor.models import Collector
            license_devices_num = int(License().getDevices())
            now_devices_num = Collector.objects.all().count()
            if now_devices_num < license_devices_num:
                check = True
            else:
                check = False
        else:
            check = False
    return check
Exemple #2
0
def ldapManualSyncAjax(request):
    '''
    LDAP manual Sync
    input: execute LDAP functions
    return: messages
    author: Pei Lin
    '''
    if check_app('omldap'):
        from omldap.views import ldapManualSync
        result = ldapManualSync(request)
        if result["status"] == "success":
            info('%s ldap Check Connect success.' % request.user.username,
                 request)
            return ResponseAjax(statusEnum.success,
                                result['message']).returnJSON()
        elif result["status"] == "fail":
            info('%s ldap Check Connect error.' % request.user.username,
                 request)
            return ResponseAjax(statusEnum.not_found,
                                result['message']).returnJSON()
        else:
            info('%s ldap Check Connect error.' % request.user.username,
                 request)
            return ResponseAjax(statusEnum.no_permission,
                                result['message']).returnJSON()
    else:
        info('%s ldap Check Connect error.' % request.user.username, request)
        return ResponseAjax(statusEnum.not_found,
                            _('您尚未安裝omldap APP,請聯絡原廠。')).returnJSON()
Exemple #3
0
def systemPage(request):
    '''
    system config page
    input:request
    return: system.html
    author:Jia Liu
    '''
    if request.user.is_superuser:
        is_ldap = check_app('omldap')
        return render(request, "system_config.html", locals())
    else:
        return render(request, "403.html")
Exemple #4
0
def ldapCheckConnectAjax(request):
    '''
    use ldap3 check connection
    input: use bind_user to connect LDAP 
    return: connection status
    author: Jia Liu
    '''
    if check_app('omldap'):
        from omldap.views import ldapCheckConnect
        result = ldapCheckConnect(request)
        if result["status"] == "success":
            info('%s ldap Check Connect success.' % request.user.username,
                 request)
            return ResponseAjax(statusEnum.success,
                                result['message']).returnJSON()
        else:
            info('%s ldap Check Connect error.' % request.user.username,
                 request)
            return ResponseAjax(statusEnum.not_found,
                                result['message']).returnJSON()
    else:
        info('%s ldap Check Connect error.' % request.user.username, request)
        return ResponseAjax(statusEnum.not_found,
                            _('您尚未安裝omldap APP,請聯絡原廠。')).returnJSON()
Exemple #5
0
from omuser.models import OmGroup,OmUser
from django.db.models import Count
from omflow.syscom.default_logger import info,error,debug
from django.utils.translation import gettext as _
from omflow.global_obj import GlobalObject
from omflow.models import SystemSetting
import json,ast,time
from omflow.syscom.license import getUsers
ldpadata_json = {}
from omflow.syscom.common import check_app
if check_app('omldap'):
    try:
        from ldap3 import Server, Connection, ALL
    except Exception as e:
        error("LDAP error:" + str(e))

def create_LDAP_user(ldap_client_server,ldap_client_server_port,ldap_base_dn,ldap_bind_user,ldap_bind_user_password):
    '''
    use ldap3 create user
    input: connect LDAP objectClass=user
    return: create user time
    author: Jia Liu
    ''' 
    start = time.time()
    server = Server(host=ldap_client_server,port=int(ldap_client_server_port),get_info=ALL,connect_timeout=2)
    conn = Connection(server, ldap_bind_user, ldap_bind_user_password, auto_bind=True,receive_timeout=2)
    conn.search(ldap_base_dn, '(&(objectCategory=person)(objectClass=user))', attributes=['distinguishedName','sAMAccountName','cn','userPrincipalName','userAccountControl','objectSID'])
    result = conn.entries
    AD_List = list(filter(lambda x: not "CN=Users"  in str(x['distinguishedName']).split(','), result))
    DN_User_List = []
    AD_User_List= []
Exemple #6
0
    def ready(self):
        import sys
        if (not 'makemigrations' in sys.argv) and (not 'migrate' in sys.argv):
            #set sidebar design to global object
            from omflow.global_obj import GlobalObject, FlowActiveGlobalObject
            from omflow.syscom.q_monitor import FormFlowMonitor, LoadBalanceMonitor
            from omflow.models import SystemSetting, QueueData
            from omflow.syscom.schedule_monitor import scheduleThread
            import threading

            starttime = str(datetime.now())
            GlobalObject.__statusObj__['server_start_time'] = datetime.now()
            #開發環境runserver的主線程功能只會監控子線程運作,以子線程為主要運行,子線程環境變數為True。
            if (os.environ.get('RUN_MAIN') == 'true'
                ) or "mod_wsgi" in sys.argv or "--noreload" in sys.argv:
                t1 = threading.Thread(target=FormFlowMonitor.setRunning)
                t1.start()
                t2 = threading.Thread(target=scheduleThread)
                t2.start()

            #確認是否為第一次啟動server
            systemsetting = SystemSetting.objects.all()
            if systemsetting:
                FlowActiveGlobalObject.ServerStart()
                if (os.environ.get('RUN_MAIN') == 'true'
                    ) or "mod_wsgi" in sys.argv or "--noreload" in sys.argv:
                    #將未完成的單放入form flow monitor
                    q_l = list(QueueData.objects.all().values(
                        'module_name', 'method_name', 'input_param'))
                    for q in q_l:
                        FormFlowMonitor.putQueue(q['module_name'],
                                                 q['method_name'],
                                                 json.loads(q['input_param']))
                    from omflow.syscom.common import check_app
                    if settings.OMFLOW_TYPE == 'collector' and check_app(
                            'ommonitor'):
                        from ommonitor.models import LoadBalanceQueueData
                        #將未完成的python放入load balance monitor
                        q_l = list(LoadBalanceQueueData.objects.all().values(
                            'module_name', 'method_name', 'input_param'))
                        for q in q_l:
                            LoadBalanceMonitor.putQueue(
                                q['module_name'], q['method_name'],
                                json.loads(q['input_param']))
                sidebar_design_str = SystemSetting.objects.get(
                    name='sidebar_design').value
                sidebar_design = json.loads(sidebar_design_str)
                GlobalObject.__sidebarDesignObj__[
                    'sidebar_design'] = sidebar_design
                GlobalObject.__sidebarDesignObj__[
                    'design_updatetime'] = starttime
                GlobalObject.__sidebarDesignObj__[
                    'permission_updatetime'] = starttime
                #ThreadPoolExecutor max workers
                POOL_MAX_WORKER = int(
                    SystemSetting.objects.get(name='pool_max_worker').value)
                ldap_str = SystemSetting.objects.get(name='ldap_config').value
                ldap_json = json.loads(ldap_str)
            else:
                #create system user when first time run server
                from omuser.models import OmUser
                import uuid
                sysuser = OmUser.objects.create_user(username='******',
                                                     nick_name='system',
                                                     password=uuid.uuid4().hex,
                                                     email='*****@*****.**',
                                                     is_superuser=True)
                #create sidebar design when first time run server
                app_list = settings.INSTALLED_APPS
                sidebar_design = []
                #check which app has been installed
                if 'omformflow' in app_list:
                    mymission = {
                        "id": "mymission",
                        "name": "我的任務",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "commenting"
                    }
                    service = {
                        "id": "service",
                        "name": "服務請求",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "shopping-cart"
                    }
                    customflow = {
                        "id": "custom_1",
                        "name": "Apps",
                        "p_id": "",
                        "flow_uuid": "custom",
                        "icon": "folder"
                    }
                    servermanage = {
                        "id": "servermanage",
                        "name": "資料收集",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "server"
                    }
                    flowmgmt = {
                        "id": "flowmgmt",
                        "name": "應用管理",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "cubes"
                    }
                    sidebar_design.append(mymission)
                    sidebar_design.append(service)
                    sidebar_design.append(servermanage)
                    sidebar_design.append(flowmgmt)
                    sidebar_design.append(customflow)
                staffmgmt = {
                    "id": "staffmgmt",
                    "name": "人員管理",
                    "p_id": "",
                    "flow_uuid": "default",
                    "icon": "user"
                }
                syssetting = {
                    "id": "syssetting",
                    "name": "系統設定",
                    "p_id": "",
                    "flow_uuid": "default",
                    "icon": "gear"
                }
                sidebar_design.append(staffmgmt)
                sidebar_design.append(syssetting)
                sidebar_design_str = json.dumps(sidebar_design)
                SystemSetting.objects.create(
                    name='sidebar_design',
                    description='side bar design json',
                    value=sidebar_design_str)
                GlobalObject.__sidebarDesignObj__[
                    'sidebar_design'] = sidebar_design
                GlobalObject.__sidebarDesignObj__[
                    'design_updatetime'] = starttime
                GlobalObject.__sidebarDesignObj__[
                    'permission_updatetime'] = starttime
                #ThreadPoolExecutor max workers
                POOL_MAX_WORKER = 10
                SystemSetting.objects.create(
                    name='pool_max_worker',
                    description='formflow thread pool max worker',
                    value=POOL_MAX_WORKER)
                #ldap config
                ldpadata_json = {
                    'ldap_client_server': '',
                    'ldap_client_server_port': '',
                    'ldap_base_dn': '',
                    'ldap_bind_user': '',
                    'ldap_bind_user_password': '',
                    'ldap_client_domain': ''
                }
                ldpadata_str = json.dumps(ldpadata_json)
                SystemSetting.objects.create(
                    name='ldap_config',
                    description='ldap connect setting',
                    value=ldpadata_str)
                #使用條款
                SystemSetting.objects.create(
                    name='PI_agree',
                    description='personal_information_agree',
                    value=personal_information_agree)
                SystemSetting.objects.create(name='SU_agree',
                                             description='software_use_agree',
                                             value=software_use_agree)
                #node default group
                from ommonitor.models import CollectorGroup
                CollectorGroup.objects.create(name='未分類')
                CollectorGroup.objects.create(name='分散處理')
                #首次啟動匯入default流程
                firstrunImport(sysuser)
            #server, node啟動的事前準備
            if (os.environ.get('RUN_MAIN') == 'true'
                ) or "mod_wsgi" in sys.argv or "--noreload" in sys.argv:
                doPreProcessing()
            #設定global
            from omformflow.models import OmParameter
            op = list(
                OmParameter.objects.filter(group_id=None).values(
                    'name', 'value'))
            for i in op:
                GlobalObject.__OmParameter__[i['name']] = i['value']
            ldap_json = {}
            GlobalObject.__ldapObj__['ldap_client_server'] = ldap_json.get(
                'ldap_client_server', '')
            GlobalObject.__ldapObj__[
                'ldap_client_server_port'] = ldap_json.get(
                    'ldap_client_server_port', '')
            GlobalObject.__ldapObj__['ldap_client_domain'] = ldap_json.get(
                'ldap_client_domain', '')
Exemple #7
0
def get_org_bool():
    boolstr = check_app('omorganization')
    return boolstr
Exemple #8
0
def get_ldap_bool():
    boolstr = check_app('omldap')
    return boolstr
Exemple #9
0
def updateSystemConfigAjax(request):
    '''
    change system log level
    input: request
    return: log level
    author: Jia Liu
    '''
    if GlobalObject.__statusObj__["ldapRunning"] == False:
        GlobalObject.__statusObj__["ldapRunning"] = True
        #function variable
        ldapdata = {}
        #get postdata
        postdata = getPostdata(request)
        POOL_MAX_WORKER = postdata.get('POOL_MAX_WORKER', '')
        PI_agree = postdata.get('PI_agree', '')
        SU_agree = postdata.get('SU_agree', '')
        ldap_client_server = postdata.get('ldap_client_server', '')
        ldap_client_server_port = postdata.get('ldap_client_server_port', '')
        ldap_base_dn = postdata.get('ldap_base_dn', '')
        ldap_bind_user = postdata.get('ldap_bind_user', '')
        ldap_bind_user_password = postdata.get('ldap_bind_user_password', '')
        ldap_client_domain = postdata.get('ldap_client_domain', '')
        loglevel = postdata.get('LOG_LEVEL', '')
        #set log level
        loglevel_ex = logging.getLevelName(
            logging.getLogger('django').getEffectiveLevel())
        if loglevel and loglevel != loglevel_ex:
            #設定django log level
            logging.getLogger('django').setLevel(loglevel)
            #設定omflow log level
            logging.getLogger('omflowlog').setLevel(loglevel)
            critical('LOG等級已經改為 %s' % loglevel, request)
            #write settings.py
            file_data = ""
            file_path = os.path.join(settings.BASE_DIR, 'omflow/',
                                     'settings.py')
            with open(file_path, "r", encoding="utf-8") as f:
                for line in f:
                    if "LOG_LEVEL = " in line:
                        line = "LOG_LEVEL = '" + loglevel + "'\n"
                    file_data += line
                f.close()
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(file_data)
                f.close()
        #set pool max worker


#         SystemSetting.objects.filter(name='pool_max_worker').update(value=POOL_MAX_WORKER)
        SystemSetting.objects.filter(name='PI_agree').update(value=PI_agree)
        SystemSetting.objects.filter(name='SU_agree').update(value=SU_agree)
        #set ldap
        ldapdata['ldap_client_server'] = ldap_client_server
        ldapdata['ldap_client_server_port'] = ldap_client_server_port
        ldapdata['ldap_base_dn'] = ldap_base_dn
        ldapdata['ldap_bind_user'] = ldap_bind_user
        ldapdata['ldap_bind_user_password'] = ldap_bind_user_password
        ldapdata['ldap_client_domain'] = ldap_client_domain
        GlobalObject.__ldapObj__['ldap_client_server'] = ldap_client_server
        GlobalObject.__ldapObj__[
            'ldap_client_server_port'] = ldap_client_server_port
        GlobalObject.__ldapObj__['ldap_client_domain'] = ldap_client_domain
        ldapdata_str = json.dumps(ldapdata)
        ldap_config = SystemSetting.objects.filter(name="ldap_config")
        if ldap_config[0].value != ldapdata_str:
            ldap_config.update(value=ldapdata_str)
            #sync ldap
            if check_app('omldap'):
                from omldap.ldap_config import syncLDAP
                t = threading.Thread(target=syncLDAP)
                t.start()
        else:
            GlobalObject.__statusObj__["ldapRunning"] = False
        info('%s update SystemConfig success.' % request.user.username,
             request)
        return ResponseAjax(statusEnum.success, _('更新成功。')).returnJSON()
    else:
        info('%s update SystemConfig error.' % request.user.username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('LDAP更新正在執行。')).returnJSON()