Example #1
0
def userSession(request):
    '''
        返回用户信息
    '''
    username, role, clientip = User(request).get_default_values()

    data = request.POST

    # 判断是否登入
    if not request.user.is_authenticated:
        ret_data = {"code": 1001, "msg": "请重新登陆"}
        return HttpResponse(json.dumps(ret_data))

    # 返回新的token
    logger.info('%s login' % username)
    return HttpResponse(
        json.dumps({
            "code": 0,
            "msg": "获取用户信息成功",
            "data": {
                'username': username,
                'is_superuser': request.user.is_superuser,
                'is_staff': request.user.is_staff
            }
        }))
Example #2
0
def Login(request, authentication_form=AuthenticationForm):
    '''
        控制登陆
    '''
    username, role, clientip = User(request).get_default_values()

    data = request.POST

    # # 判断是否登入
    # if request.user.is_authenticated:
    #     return HttpResponseRedirect('/')

    # 校验登陆
    form = authentication_form(request, data=data)
    if form.is_valid():
        auth_login(request, form.get_user())

        # 返回新的token
        logger.info('%s login' % username)
        return HttpResponse(
            json.dumps({
                "code": 0,
                "msg": "登陆成功了",
                "data": {
                    "csrftoken":
                    "c262e61cd13ad99fc650e6908c7e5e65b63d2f32185ecfed6b801ee3fbdd5c0a"
                }
            }))
    else:
        return HttpResponse(json.dumps({
            "code": 1001,
            "msg": "账号密码错误",
        }))
Example #3
0
def delete_domain_records(request):
    '''
        删除域名记录
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '删除域名记录成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)

            logger.info(data)
            # return HttpResponse(json.dumps(ret_data))
            for record in data['records']:
                domain = DomainTb.objects.get(id=record['id'])  # 获取域名

                domain.delete()

    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '删除域名记录失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #4
0
def add_records(request):
    '''
        新增DNSPOD 域名解析
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '新增域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            zone = data['zone']
            logger.info(data)
            for sub_domain in data['sub_domain']:
                dnspod_acc = DnspodAccountTb.objects.get(
                    name=zone['dnspod_acc'])
                record_name = zone[
                    'zone'] if sub_domain == '@' else sub_domain + "." + zone[
                        'zone']
                try:
                    dpapi = DpApi(DNSPOD_URL, dnspod_acc.key)
                except Exception as e:
                    logger.error(str(e))
                    ret_data['code'] = 500
                    ret_data['msg'] = '%s 新增域名解析失败:%s' % (record_name, str(e))
                    return HttpResponse(json.dumps(ret_data))

                else:
                    result, status = dpapi.create_zone_record(
                        domain=zone['zone'],
                        sub_domain=sub_domain,
                        record_type=data['type'],
                        value=data['content'],
                        record_line=data['record_line'],
                        #status         = 'enable' if data['enabled'] == '1' else 'disable',
                    )
                if not status:
                    ret_data['code'] = 500
                    ret_data['msg'] = '%s 新增域名解析失败:%s' % (record_name,
                                                          str(result))
                    return HttpResponse(json.dumps(ret_data))
                insert_ah(
                    clientip, username,
                    "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                    ('null', 'null', 'null', 'null'),
                    "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                    (data['type'], record_name, data['content'], '1'), status,
                    'add')
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '新增域名解析失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #5
0
def get_domain_args(request):
    '''
        获取域名 列表
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0 # 请求正常,返回 0
    ret_data['msg']  = '获取DNSPOD账号列表'
    ret_data['data'] = {}
    
    # 获取 cdn 账号列表
    cdn_acc_list = Domainns(request).get_cdn_account()

    # 获取 cf 账号列表
    cf_acc_list = Domainns(request).get_cf_account()

    group_list   = DomainDetectGroupTb.objects.all()
    ret_data['data'] = {
            'customer': choices_customer,
            'product' : choices_product,
            'group'   : [],
            'cdn'     : [],
            'cf'      : [],
        }

    for cdn in cdn_acc_list:
        tmp_dict = {
            'id':      cdn.id,
            'name':    cdn.get_name_display(),
            'account': cdn.account,
        }

        ret_data['data']['cdn'].append(tmp_dict)

    for cf in cf_acc_list:
        tmp_dict = {
            'id':      cf.id,
            'name':    "cloudflare",
            'account': cf.name,
        }
        ret_data['data']['cf'].append(tmp_dict)

    for item in group_list:
        tmp_dict = {}
        tmp_dict['id']     = item.id
        tmp_dict['group']  = item.group
        tmp_dict['client'] = item.client
        tmp_dict['method'] = item.method
        tmp_dict['ssl']    = item.ssl
        tmp_dict['retry']  = item.retry

        ret_data['data']['group'].append(tmp_dict)

    return HttpResponse(json.dumps(ret_data))
Example #6
0
def index(request):
    '''
        主页入口
    '''
    username, role, clientip = User(request).get_default_values()

    return render(
        request,
        'home.html',
    )
Example #7
0
def update_records(request):
    '''
        更新DNSPOD 域名解析
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '修改域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            for record in data['records']:
                dnspod_acc = DnspodAccountTb.objects.get(
                    name=record['dnspod_acc'])
                dpapi = DpApi(DNSPOD_URL, dnspod_acc.key)

                result, status = dpapi.update_zone_record(
                    domain=record['zone'],
                    record_id=record['record_id'],
                    sub_domain=record['sub_domain'],
                    record_type=data['type'],
                    value=data['value'],
                    record_line_id=record['record_line_id'],
                    status='enable' if data['enabled'] == '1' else 'disable')
                if not status:
                    logger.error(str(result))
                    ret_data['code'] = 500
                    ret_data['msg'] = "修改 %s 域名解析失败!%s" % (zone['name'],
                                                           str(result))
                    logger.error(ret_data['msg'])
                    return HttpResponse(json.dumps(ret_data))
                logger.info(
                    "req_ip: %s | user: %s | updaterecord: { 'type':%s, 'name': %s, 'content': %s, 'proxied':%s } ---> { 'type':%s, 'name': %s, 'content': %s, 'proxied':%s }"
                    % (clientip, username, record['type'], record['name'],
                       record['value'], record['enabled'], data['type'],
                       record['name'], data['value'], data['enabled']))

                insert_ah(
                    clientip, username,
                    "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                    (record['type'], record['name'], record['value'],
                     record['enabled']),
                    "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                    (data['type'], record['name'], data['value'],
                     data['enabled']), status)
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '修改域名信息失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #8
0
def update_records(request):
    '''
        更新CF 域名解析
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '修改域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            logger.info(data)
            for record in data['records']:
                cf_acc = CfAccountTb.objects.get(name=record['cf_acc'])
                cfapi = CfApi(CF_URL, cf_acc.email, cf_acc.key)
                if data['proxied'] == 'true':
                    proxied = True
                else:
                    proxied = False

                result = cfapi.update_zone_record(
                    record['zone_id'],
                    data['type'],
                    record['name'],
                    data['content'],
                    proxied=proxied,
                    record_id=record['record_id'])
                logger.info(
                    "req_ip: %s | user: %s | updaterecord: { 'type':%s, 'name': %s, 'content': %s, 'proxied':%s } ---> { 'type':%s, 'name': %s, 'content': %s, 'proxied':%s }"
                    % (clientip, username, record['type'], record['name'],
                       record['content'], record['proxied'], data['type'],
                       record['name'], data['content'], proxied))

                insert_h = AlterHistoryTb(
                    time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    req_ip=clientip,
                    user=username,
                    pre_rec="'type':%s, 'name': %s, 'content': %s, 'proxied':%s"
                    % (record['type'], record['name'], record['content'],
                       record['proxied']),
                    now_rec="'type':%s, 'name': %s, 'content': %s, 'proxied':%s"
                    % (data['type'], record['name'], data['content'], proxied))

                insert_h.save()
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '修改域名解析失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #9
0
def edit_domain_records(request):
    '''
        域名修改
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '域名修改成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)

            logger.info(data)
            # return HttpResponse(json.dumps(ret_data))

            index = 0
            for record in data['records']:
                domain = DomainTb.objects.get(id=record['id'])  # 获取域名

                if len(data['records']) == 1 or data['content']:
                    domain.content = data['content']

                domain.name = data['name'][index]
                domain.product = data['product']
                domain.customer = data['customer']
                domain.status = data['status']
                domain.group = DomainDetectGroupTb.objects.get(
                    id=data['group'])

                domain.save()
                if data['cdn_status']:
                    for cdn in domain.cdn.all():
                        domain.cdn.remove(cdn)
                    for cdn in data['cdn']:
                        domain.cdn.add(CdnAccountTb.objects.get(id=cdn))
                        domain.save()
                if data['cf_status']:
                    if data['cf']:
                        domain.cf = CfAccountTb.objects.get(id=data['cf'])
                        domain.save()

                index += 1

    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '域名修改失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #10
0
def add_records(request):
    '''
        新增CF 域名解析
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '新增域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            zone = data['zone']
            for sub_domain in data['sub_domain']:
                cf_acc = CfAccountTb.objects.get(name=zone['cf_acc'])
                try:
                    cfapi = CfApi(CF_URL, cf_acc.email, cf_acc.key)
                except Exception as e:
                    logger.error(str(e))
                    ret_data['code'] = 500
                    ret_data['msg'] = '新增域名解析失败:%s' % str(e)
                    return HttpResponse(json.dumps(ret_data))

                else:
                    result = cfapi.create_zone_record(
                        zone_id=zone['zone_id'],
                        record_name=sub_domain + '.' +
                        zone['zone'] if sub_domain != "@" else zone['zone'],
                        record_type=data['type'],
                        record_content=data['content'],
                        proxied=True
                        if data['proxied'].lower() == 'true' else False,
                    )
                if not result['success']:
                    ret_data['code'] = 500
                    ret_data[
                        'msg'] = '新增域名解析失败:%s' % result['errors'][0]['message']
                    return HttpResponse(json.dumps(ret_data))
                insert_ah(
                    clientip, username, "null",
                    "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                    (data['type'], sub_domain + '.' + zone['zone'],
                     data['content'], '1'), result['success'], 'add')
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '新增域名解析失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #11
0
def Logout(request):
    '''
        控制登出
    '''
    username, role, clientip = User(request).get_default_values()

    data = request.POST

    # 登出
    logger.info('%s logout' % username)
    ret_data = {"code": 1001, "msg": "您已登出"}
    auth_logout(request)
    return HttpResponse(json.dumps(ret_data))
Example #12
0
def get_cf_accounts(request):
    '''
        获取CF账号列表
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0 # 请求正常,返回 0
    ret_data['msg']  = '获取CF账号列表'
    ret_data['data'] = []

    # 获取CF 账号
    cf_acc_list = Domainns(request).get_cf_account()

    for cf_acc in cf_acc_list:
        cfapi  = CfApi(CF_URL, cf_acc.email, cf_acc.key)
        page   = 1
        result = cfapi.get_dns_lists(page=page)
        
        # 请求异常处理
        if 'result_info' not in result: 
            ret_data['msg'] = "获取CF DNS失败:%s" %str(result)
            return HttpResponse(json.dumps(ret_data))

        # 格式化账号信息
        total_pages = result['result_info']['total_pages']
        tmp_dict = {
            'name':      cf_acc.name,
            'email':     cf_acc.email,
            'cf_acc_py': lazy_pinyin(cf_acc.name), # 将账号按照中文拼音进行排序
            'domain':    [],
            }
        if len(result['result']) == 0:
            continue
        while page <= total_pages: # 如果拿到的数据有多页,循环获取,直到拿到所有域名
            for record in result['result']:
                tmp_dict['domain'].append({
                        'name': record['name'],
                        'id':   record['id'],
                        'status': 'enable',
                    })
            page += 1
            result = cfapi.get_dns_lists(page=page)
        ret_data['data'].append(tmp_dict)

    #logger.info(ret_data['data'])
    ret_data['data'].sort(key=lambda acc: acc['cf_acc_py']) # cf_acc 拼音排序

    return HttpResponse(json.dumps(ret_data))
Example #13
0
def get_dnspod_accounts(request):
    '''
        获取DNSPOD账号列表
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0 # 请求正常,返回 0
    ret_data['msg']  = '获取DNSPOD账号列表'
    ret_data['data'] = []

    # 获取DNSPOD 账号
    dnspod_acc_list = Domainns(request).get_dnspod_account()

    for dnspod_acc in dnspod_acc_list:

        # 做一步异常处理
        try:
            dpapi = DpApi(DNSPOD_URL, dnspod_acc.key)
        except Exception as e:
            ret_data['code'] = 500
            ret_data['msg']  = "查询 %s 账号失败:%s" %(dnspod_acc.name, str(e))
            logger.error(ret_data['msg'] )
            return HttpResponse(json.dumps(ret_data))
        else:
            result, status = dpapi.get_dns_lists(type='all')
            if not status:
                ret_data['code'] = 500
                ret_data['msg']  = '获取DNSPOD账号列表 失败:%s' %str(result)
                logger.error(ret_data['msg'])
                return HttpResponse(json.dumps(ret_data))
            else:
                ret_data['data'].append({
                    'name':   dnspod_acc.name,
                    'email':  dnspod_acc.email,
                    'domain': result['domains'],
                    'dnspod_acc_py': lazy_pinyin(dnspod_acc.name),
                })

    #logger.info(ret_data['data'])
    ret_data['data'].sort(key=lambda acc: acc['dnspod_acc_py']) # dnspod_acc_py 拼音排序

    return HttpResponse(json.dumps(ret_data))
Example #14
0
def get_zone_records(request):
    '''
        获取CF 域名信息
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '获取域名信息成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            logger.info(data)
            for zone in data['zones']:
                cf_acc = CfAccountTb.objects.get(name=zone['cf_acc'])
                cfapi = CfApi(CF_URL, cf_acc.email, cf_acc.key)
                result = cfapi.get_zone_records(zone['zone_id'])
                if len(result['result']) == 0:
                    continue
                logger.info(result['result'])
                for record in result['result']:
                    tmp_dict = {}
                    tmp_dict['cf_acc'] = zone['cf_acc']
                    tmp_dict['zone'] = record['zone_name']
                    tmp_dict['name'] = record['name']
                    tmp_dict['type'] = record['type']
                    tmp_dict['content'] = record['content']
                    tmp_dict['proxied'] = record['proxied']
                    tmp_dict['record_id'] = record['id']
                    tmp_dict['zone_id'] = record['zone_id']
                    ret_data['data'].append(tmp_dict)

    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '获取域名信息失败: %s' % str(e)

    ret_data['count'] = len(ret_data['data'])

    return HttpResponse(json.dumps(ret_data))
Example #15
0
def delete_records(request):
    '''
        删除DNSPOD 域名解析
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '删除域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            for zone in data:
                dnspod_acc = DnspodAccountTb.objects.get(
                    name=zone['dnspod_acc'])
                dpapi = DpApi(DNSPOD_URL, dnspod_acc.key)

                result, status = dpapi.delete_zone_record(
                    zone['zone'], zone['record_id'], zone['name'])
                if not status:
                    logger.error(str(result))
                    ret_data['code'] = 500
                    ret_data['msg'] = "删除 %s 域名失败!%s" % (zone['name'],
                                                         str(result))
                    logger.error(ret_data['msg'])
                    return HttpResponse(json.dumps(ret_data))
                else:
                    logger.info("删除 %s 域名成功!%s" % (zone['name'], str(result)))
                    insert_ah(
                        clientip, username,
                        "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                        (zone['type'], zone['name'], zone['value'],
                         zone['enabled']), "null", status, 'delete')
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '删除域名解析失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #16
0
def add_domain_records(request):
    '''
        域名新增
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '域名新增成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)

            logger.info(data)
            # return HttpResponse(json.dumps(ret_data))

            for domain_name in data['name']:
                domain = DomainTb(
                    name=domain_name,
                    product=data['product'],
                    customer=data['customer'],
                    group=DomainDetectGroupTb.objects.get(id=data['group']),
                    content=data['content'],
                    status=data['status'])

                domain.save()
                for cdn in data['cdn']:
                    domain.cdn.add(CdnAccountTb.objects.get(id=cdn))
                    domain.save()
                if data['cf']:
                    domain.cf = CfAccountTb.objects.get(id=data['cf'])
                    domain.save()

    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '域名新增失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #17
0
def delete_records(request):
    '''
        删除CF 域名解析
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '删除域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            for zone in data:
                cf_acc = CfAccountTb.objects.get(name=zone['cf_acc'])
                cfapi = CfApi(CF_URL, cf_acc.email, cf_acc.key)

                result = cfapi.delete_zone_record(zone['zone_id'],
                                                  zone['record_id'])
                if not result['success']:
                    logger.error(str(e))
                    ret_data['code'] = 500
                    ret_data['msg'] = "删除 %s 域名失败!%s" % (zone['name'],
                                                         str(result))
                    logger.error(ret_data['msg'])
                    return HttpResponse(json.dumps(ret_data))
                else:
                    logger.info("删除 %s 域名成功!%s" % (zone['name'], str(result)))
                    insert_ah(
                        clientip, username,
                        "'type':%s, 'name': %s, 'content': %s, 'enabled':%s" %
                        (zone['type'], zone['name'], zone['content'],
                         zone['proxied']), "null", result['success'], 'delete')
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '删除域名解析失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #18
0
def reflesh_execute_cdn(request):
    '''
        刷新指定账号上域名的缓存
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0 # 请求正常,返回 0
    ret_data['msg']  = '域名缓存刷新成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            ret_data['data'] = data
    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg']  = '域名缓存刷新失败: %s' %str(e)

    return HttpResponse(json.dumps(ret_data))
Example #19
0
def telegram_group(request):
    '''
        获取telegram 群组,以及 各部门的人员
    '''
    username, role, clientip = User(request).get_default_values()

    # 判断是否登陆
    if not request.user.is_authenticated:
        return HttpResponse(json.dumps(ret_data))

    # 获取需要@的群组人员
    atUsers = {}
    if request.user.is_superuser:
        atUsersSelects = DepartmentUserTb.objects.filter(status=1).all()
    else:
        atUsersSelects = DepartmentUserTb.objects.filter(status=1).all()

    # 获取需要发送信息的群组
    groups = {}
    if request.user.is_superuser or username == 'test':
        groupSelects = TelegramChatGroupTb.objects.filter(status=1).all()
    elif role == "sa":
        groupSelects = TelegramChatGroupTb.objects.filter(
            status=1,
            group__in=['kindergarten', 'zhuanyepan', 'yunwei',
                       'sport2']).all()
    else:
        groupSelects = TelegramChatGroupTb.objects.filter(
            status=1, group__in=['kindergarten', 'zhuanyepan',
                                 'sport2']).all()

    for department in atUsersSelects:
        atUsers[department.name] = {
            'id':
            department.id,
            'department':
            department.department,
            'users': [{
                'name': user.name,
                'user': user.user,
                'user_id': user.user_id,
            } for user in department.user.filter(status=1).all()],
            'atUsers':
            department.AtUsers(),
            'display':
            department.display().replace(' ', ''),
        }

    for group in groupSelects:
        groups[group.group] = {
            'id': group.id,
            'group': group.group,
            'name': group.name,
            'group_id': group.group_id,
        }

    return HttpResponse(
        json.dumps({
            "code": 0,
            "msg": "",
            'data': {
                'atUsers': atUsers,
                'groups': groups,
            },
        }))
Example #20
0
def get_domain_records(request):
    '''
        域名列表获取
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '域名列表获取成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            domains = DomainTb.objects.filter(name__icontains=data['name'],
                                              status__in=data['status'],
                                              group__id__in=data['group'],
                                              product__in=data['product'],
                                              customer__in=data['customer'])
            logger.info(data)
            if len(data['cdn']) != 0:
                domains = domains.filter(cdn__in=data['cdn'])
            if len(data['cf']) != 0:
                domains = domains.filter(cf__in=data['cf'])

            domains = domains.all().order_by('-id')

            for domain in domains:
                tmp_dict = {}
                tmp_dict['id'] = domain.id
                tmp_dict['name'] = domain.name
                tmp_dict['product'] = (domain.product,
                                       domain.get_product_display())
                tmp_dict['customer'] = (domain.customer,
                                        domain.get_customer_display())
                tmp_dict['content'] = domain.content
                tmp_dict['status'] = domain.status

                tmp_dict['group'] = {
                    'id': domain.group.id,
                    'group': domain.group.group,
                }

                tmp_dict['cdn'] = [{
                    'id': cdn.id,
                    'name': cdn.get_name_display(),
                    'account': cdn.account,
                } for cdn in domain.cdn.all()]
                if domain.cf:
                    tmp_dict['cf'] = [{
                        'id': domain.cf.id,
                        'name': "cloudflare",
                        'account': domain.cf.name,
                    }]
                else:
                    tmp_dict['cf'] = []

                ret_data['data'].append(tmp_dict)

    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '域名列表获取失败: %s' % str(e)

    return HttpResponse(json.dumps(ret_data))
Example #21
0
def get_zone_records(request):
    '''
        获取DNSPOD 域名信息
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '获取域名解析成功'
    ret_data['data'] = []

    try:
        if request.method == 'POST':
            data = json.loads(request.body)
            logger.info(data)
            for zone in data['zones']:
                dnspod_acc = DnspodAccountTb.objects.get(
                    name=zone['dnspod_acc'])
                dpapi = DpApi(DNSPOD_URL, dnspod_acc.key)
                result, status = dpapi.get_zone_records(zone['domain'])
                if not status:
                    logger.error("查询 %s 域名失败!%s" %
                                 (zone['domain'], str(result)))
                    return HttpResponseServerError('error!')
                else:
                    #logger.info(result)
                    for record in result['records']:
                        if record['type'] in ['A', 'CNAME']:
                            ret_data['data'].append({
                                'dnspod_acc':
                                zone['dnspod_acc'],
                                'zone':
                                zone['domain'],
                                'zone_id':
                                zone['zone_id'],
                                'sub_domain':
                                record['name'],
                                'name':
                                record['name'] + '.' + zone['domain']
                                if record['name'] != '@' else zone['domain'],
                                'type':
                                record['type'],
                                'value':
                                record['value'],
                                'record_id':
                                record['id'],
                                'record_line':
                                record['line'],
                                'record_line_id':
                                record['line_id'],
                                #'record_line_id': record['line_id'].replace('=', '%3D'),
                                'enabled':
                                record['enabled'],
                            })

    except Exception as e:
        logger.error(str(e))
        ret_data['code'] = 500
        ret_data['msg'] = '获取域名信息失败: %s' % str(e)

    ret_data['count'] = len(ret_data['data'])

    return HttpResponse(json.dumps(ret_data))
Example #22
0
def telegram_sendgroupmessage(request):
    '''
        往对应群组发送信息
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '未发送任何消息'

    # 初始化 telegram 信息
    message = MESSAGE_TEST.copy()

    # time.sleep(5)

    if request.method == 'POST':

        data = request.POST

        # 检查群组是否为空
        if 'group' not in data or not data['group']:
            ret_data['msg'] = 'TG群组为空,请检查!'
            return HttpResponse(json.dumps(ret_data))
        else:
            message['group'] = data['group']

        # 检查是否有图片
        if 'files[]' in request.FILES and request.FILES.getlist('files[]'):
            # request.FILES 是一个 MultiValueDict,如果传入的参数是一个数组,需要通过 getlist 方法来获取列表数据
            for img in request.FILES.getlist('files[]'):
                logger.info(img)
                # 判断文件是不是 gif
                s = SendTelegram(message)
                if str(img)[-3:] == "gif":
                    r = s.send_document(img)
                else:
                    r = s.send_document(img)
                    # r = s.send_photo(img)

                logger.info(message)

                if r:
                    ret_data['msg'] = '图片发送成功'
                else:
                    ret_data['code'] = 500
                    ret_data['msg'] = '图片发送失败'
                    return HttpResponse(json.dumps(ret_data))

        # 检查信息是否为空
        if 'text' not in data or not data['text']:
            # ret_data['msg'] = '信息为空,请检查!'
            return HttpResponse(json.dumps(ret_data))

        # 获取需要@的部门或组
        atUsers = []
        if 'atUsers' in data and data['atUsers']:
            atUsersDepList = [
                int(id) for id in data['atUsers'].replace(' ', '').split(',')
                if IsSomeType(id).is_int()
            ]
            atUsersSelects = DepartmentUserTb.objects.filter(
                status=1, id__in=atUsersDepList).all()
            for department in atUsersSelects:
                atUsers.append(department.department + ': ' + ', '.join([
                    '@' + user.user
                    for user in department.user.filter(status=1).all()
                ]))

        message['text'] = data['text'] + '\r\n\r\n' + '\r\n'.join(atUsers)
        s = SendTelegram(message)
        if s.send():
            ret_data['msg'] = '发送成功!'
        else:
            ret_data['msg'] = 'telegram 接口错误,发送失败!'
        return HttpResponse(json.dumps(ret_data))

    else:
        ret_data['msg'] = '403'
        return HttpResponse(json.dumps(ret_data))
Example #23
0
def menu(request):
    '''
        获取 前端导航栏
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0  # 请求正常,返回 0
    ret_data['msg'] = '获取导航栏路由'
    ret_data['data'] = []

    # 获取用户对路由的权限
    try:
        if request.user.is_superuser:  # 超级用户拥有所有权限
            first_level_list = WebUriFirstLevelTb.objects.filter(
                status=1).all()
            second_level_list = WebUriSecondLevelTb.objects.filter(
                status=1).all()
            third_level_list = WebUriThirdLevelTb.objects.filter(
                status=1).all()
        else:
            user_web_uri_p = UserPermissionsTb.objects.get(user=request.user)
            first_level_list = [
                per
                for per in user_web_uri_p.weburifirst_l.filter(status=1).all()
            ]
            second_level_list = [
                per for per in user_web_uri_p.weburisecond_l.filter(
                    status=1).all()
            ]
            third_level_list = [
                per
                for per in user_web_uri_p.weburithird_l.filter(status=1).all()
            ]
            for group in user_web_uri_p.usergroup_p.filter(
                    status=1).all():  # 循环将组权限 分配给用户
                for first_level in group.weburifirst_l.filter(status=1).all():
                    if first_level not in first_level_list:
                        first_level_list.append(first_level)
                for second_level in group.weburisecond_l.filter(
                        status=1).all():
                    if second_level not in second_level_list:
                        second_level_list.append(second_level)
                for third_level in group.weburithird_l.filter(status=1).all():
                    if third_level not in third_level_list:
                        third_level_list.append(third_level)

    except Exception as e:
        logger.error(str(e))
        return HttpResponse(json.dumps(ret_data))

    # 将权限 格式化成合法的数据
    for first_level in first_level_list:
        first_level_dict = {  # 获取第一层导航路由
            'title': first_level.title,
            'name': first_level.name,
            'jump': first_level.jump,
            'icon': first_level.icon,
            'list': []
        }
        for second_level in first_level.next_l.filter(status=1).all():
            if second_level in second_level_list:
                second_level_dict = {  # 获取第二层导航路由
                    'title': second_level.title,
                    'name': second_level.name,
                    'jump': second_level.jump,
                    'icon': second_level.icon,
                    'list': []
                }
                for third_level in second_level.next_l.filter(status=1).all():
                    if third_level in third_level_list:
                        third_level_dict = {  # 获取第三层导航路由
                            'title': third_level.title,
                            'name': third_level.name,
                            'jump': third_level.jump,
                            'icon': third_level.icon,
                            'list': []
                        }
                        second_level_dict['list'].append(third_level_dict)
                first_level_dict['list'].append(second_level_dict)
        ret_data['data'].append(first_level_dict)

    return HttpResponse(json.dumps(ret_data))
Example #24
0
def get_reflesh_project(request):
    '''
        获取 清缓存 列表数据
    '''
    username, role, clientip = User(request).get_default_values()

    # 初始化返回数据
    ret_data = RET_DATA.copy()
    ret_data['code'] = 0 # 请求正常,返回 0
    ret_data['msg']  = '获取[清缓存列表数据]成功'
    ret_data['data'] = {'domain_project': [], 'cdn': []}

    # 获取 cdn缓存项目
    domain_project_list = DoaminProjectTb.objects.filter(status=1).all()
    for prot in domain_project_list:
        tmpdict = {}
        tmpdict['project'] = prot.project
        tmpdict['domain']  = [ {'id': domain.id,
                                'name': urlparse(domain.name).scheme+"://"+urlparse(domain.name).netloc,
                                'product': domain.get_product_display(),
                                'customer': domain.get_customer_display()} for domain in prot.domain.all() ]
        #tmpdict['cdn']     = [ {'name': cdn.get_name_display(),
        #                        'account': cdn.account} for cdn in cdn_t.objects.all() ]
        ret_data['data']['domain_project'].append(tmpdict)

    # 获取cdn 账号
    cdn_acc_list = Domainns(request).get_cdn_account()
    for cdn in cdn_acc_list:
        tmpdict = {
            'id':      cdn.id,
            'name':    cdn.get_name_display(),
            'account': cdn.account,
            'domain': [],
        }
        if cdn.get_name_display() == "wangsu":
            req = WsApi(cdn.secretid, cdn.secretkey)
            results, status = req.getdomains()
            if status:
                for line in results:
                    if line['enabled'] == 'true':
                        tmpdict['domain'].append({
                                'name': line['domain-name'],
                                'ssl' : 1 if line['service-type']=='web-https' else 0,
                            })
        # elif cdn.get_name_display() == "tencent": # 腾讯云接口有问题,后面再修复
        #     req = TcApi(cdn.secretid, cdn.secretkey)
        #     results, status = req.getdomains()
        #     for line in results['data']['hosts']:
        #         if line['disabled'] == 0 and line['status'] in [3, 4, 5]:
        #             tmpdict['domain'].append({
        #                     'name': line['host'],
        #                     'ssl' : 1 if line['ssl_type']!=0 else 0,
        #                 })
        elif cdn.get_name_display() == "aws":
            req = AwsApi(cdn.secretid, cdn.secretkey)
            results, status = req.getdomains(['fenghuang'])
            if status:
                for item in results:
                    tmpdict['domain'].append({
                            'Id': item['Id'],
                            'name': item['domains'],
                            'ssl' : 0,
                            'product':  item['product'],
                            'customer': item['customer']
                        })
        else:
            tmpdict['domain'] = []
        ret_data['data']['cdn'].append(tmpdict)
        # break

    #logger.info(ret_data['data'])
    ret_data['data']['cdn'].sort(key=lambda acc: acc['name']) # CDN账号按 name的分类 排序

    return HttpResponse(json.dumps(ret_data))