Example #1
0
def gen_mailbox(obj):
    total = 0
    for a in DefaultMailbox.objects.all():
        mailbox = '{}@{}'.format(a.account, obj.domain)
        if not CustomerMailbox.objects.filter(mailbox=mailbox, disabled='0'):
            m_obj = CustomerMailbox.objects.create(
                customer=obj.customer,
                domain=obj.domain,
                name=a.account,
                mailbox=mailbox,
                password=get_random_string(10))
            m_obj.api_sync('add-mailbox')
            total += 1
    return total
Example #2
0
def ali_login_return(request):
    is_allow_register = False
    customer = None
    try:
        auth_code = request.GET.get('auth_code', '')
        state = request.GET.get('state', '')
        token_url = ALI.system_oauth_token(auth_code)
        res = json.loads(urllib.urlopen(token_url).read())
        data = res.get('alipay_system_oauth_token_response', {})
        access_token = data['access_token']
        user_info_url = ALI.user_info_share(access_token)
        user_info = json.loads(urllib.urlopen(user_info_url).read()).get(
            'alipay_user_info_share_response', {})
        user_id = user_info['user_id']
        ali_customer, _created = AliCustomer.objects.get_or_create(
            user_id=user_id)
        # 支付宝登录
        if state == 'login':
            users = Customer.objects.filter(ali_customer=ali_customer,
                                            disabled=0)
            if users:
                user = users[0]
                user = authenticate(username=user.username,
                                    password='',
                                    t_password=user.password)
                auth_login(request, user)
                # 登录日志
                user.save_fast_login_log(request, mode='ali')
                user.last_login = timezone.now()
                user.save(update_fields=['last_login'])

                # 支付宝登录通知销售
                sss = user.service()
                if sss and sss.is_pushcrew:
                    action = "service"
                    title = u"支付宝登录提醒"
                    message = u"{}(ID: {}) 于 {} 时间登录平台".format(
                        user.company, user.id,
                        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    pushcrew_notice(action, title, message)

                return HttpResponseRedirect('http://{}{}'.format(
                    settings.HOSTNAME, reverse('home')))
            else:
                messages.add_message(request, messages.ERROR,
                                     _(u'此支付宝并未于平台账号绑定,请先绑定账号!'))
                return HttpResponseRedirect('http://{}{}'.format(
                    settings.HOSTNAME, reverse('home')))

        elif state == 'bind':
            customer = request.user
        else:
            #芝麻信用验证
            cryp_obj = DES.new(settings.CRYP_KEY)
            customer_id, expired_time = cryp_obj.decrypt(
                a2b_hex(state)).split('----')
            customer = Customer.objects.get(id=customer_id)

        for field in [
                'avatar', 'city', 'gender', 'is_certified',
                'is_student_certified', 'province', 'user_status', 'user_type'
        ]:
            setattr(ali_customer, field, user_info.get(field, ''))
        transaction_id = time.strftime('%Y%m%d%H%M%S') + get_random_string(
            4).upper()
        try:
            min_score = int(Prefs.objects.get(name='register_credit').value)
        except:
            min_score = 630
        zhima_url = ALI.zhima_credit_score(access_token, transaction_id,
                                           user_id, min_score)
        zhima_info = json.loads(urllib.urlopen(zhima_url).read()).get(
            'zhima_credit_score_brief_get_response', {})
        is_admittance = zhima_info.get('is_admittance', '')
        ali_customer.is_admittance = is_admittance
        ali_customer.save()
        if ali_customer.user_type == '1' and ali_customer.user_status == 'T':
            is_allow_register = True
        elif is_admittance == "N":
            msg = _(u'抱歉,您的芝麻信用未符合快捷注册条件,如需测试, 请联系客服,电话/企业QQ:400-8181-568!')
        elif is_admittance == "Y":
            is_allow_register = True
        else:
            msg = _(u'抱歉,系统获取您的芝麻信用失败,无法进行快捷注册登陆!')
    except:
        msg = _(u'支付宝接口异常,请稍后重试!')

    if customer and is_allow_register and not customer.is_bind_ali:
        try:
            register_point = int(
                Prefs.objects.get(name='register_point').value)
        except:
            register_point = 100

        if customer.is_register:
            register_manager_lists = [
                'register_manager_1', 'register_manager_2',
                'register_manager_3'
            ]
            redis = get_redis_connection()
            find_next_manager = 'register_manager_1'
            find_next_count = None
            for key in register_manager_lists:
                count = redis.hget("edm_web_register_manager_hash", key=key)
                count = int(count) if count else 0
                if find_next_count is None or find_next_count >= count:
                    find_next_manager = key
                    find_next_count = count
            redis.hincrby("edm_web_register_manager_hash", find_next_manager,
                          1)

            # manager, _created = Prefs.objects.get_or_create(name=random.choice(register_manager_lists))
            manager, _created = Prefs.objects.get_or_create(
                name=find_next_manager)
            manager_id = int(manager.value) if manager.value else None
            if not manager_id:
                manager = Manager.objects.first()
                manager_id = manager.id
            customer.disabled = "0"
            customer.manager_id = manager_id
        service = customer.service()

        service.qty_valid += register_point
        service.qty_count += register_point
        customer.is_bind_ali = True
        service.save()

        # 支付宝注册通知销售
        action = "sale"
        title = u"注册提醒(验证通过)"
        message = u"{}(ID: {}) 于 {} 时间注册并登录平台".format(
            customer.company, customer.id,
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        pushcrew_notice(action, title, message, customer_id=customer.id)

        msg = _(u'恭喜您,芝麻信用验证通过,注册成功!')
    customer.ali_customer = ali_customer
    customer.save()
    if state == 'bind':
        messages.add_message(request, messages.SUCCESS, _(u'支付宝绑定成功'))
        return HttpResponseRedirect(reverse('account'))
    else:
        messages.add_message(request, messages.INFO, msg)
        return HttpResponseRedirect('{}?result={}&key={}'.format(
            reverse('register_new_step3'), is_allow_register, state))
Example #3
0
 def __check(self):
     if not self.token.value.strip():
         value = get_random_string(32)
         self.token = BaseFied(value, error=None)
     return self.__valid
Example #4
0
def send_domain(request):
    if request.method == "POST":
        domain = request.POST.get('domain', '')
        action = request.POST.get('action', '')
        id = request.POST.get('id', '')
        if request.user.service().is_umail:
            messages.add_message(request, messages.ERROR, _(u'测试帐号不允许此类操作!'))
            return HttpResponseRedirect(reverse('send_domain'))
        if id:
            obj = get_object(CustomerDomain, request.user, id)
        if action == 'track_delete':
            track_id = request.POST.get('track_id', '')
            trackobj = get_object(CustomerTrackDomain, request.user, track_id)
            trackobj.delete()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'跟踪域名:%(domain)s 删除成功!') % {'domain': trackobj.domain})
        elif action == 'track_default':
            track_id = request.POST.get('track_id', '')
            trackobj = get_object(CustomerTrackDomain, request.user, track_id)
            trackobj.isdefault = True
            trackobj.save()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'跟踪域名:%(domain)s 设置默认成功!') % {'domain': trackobj.domain})
        elif action == 'track_default_false':
            track_id = request.POST.get('track_id', '')
            trackobj = get_object(CustomerTrackDomain, request.user, track_id)
            trackobj.isdefault = False
            trackobj.save()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'跟踪域名:%(domain)s 关闭默认成功!') % {'domain': trackobj.domain})
        elif action == 'add':
            domain = domain.strip()
            if not validators.check_domains(domain):
                messages.add_message(
                    request, messages.ERROR,
                    _(u'添加失败,域名%(domain)s格式错误!') % {'domain': domain})
                return HttpResponseRedirect(reverse('send_domain'))
            if CustomerDomain.objects.filter(domain=domain,
                                             customer=request.user):
                messages.add_message(request, messages.ERROR,
                                     _(u'添加失败,发送域名重复添加!'))
            else:
                private_key, public_key = GenDkimKeys()
                public_key = 'k=rsa;p={}'.format(public_key)
                CustomerDomain.objects.create(customer=request.user,
                                              domain=domain,
                                              dkim_private=private_key,
                                              dkim_public=public_key)
                messages.add_message(request, messages.SUCCESS, _(u'发送域名添加成功'))
        elif action == 'valid_domain':
            if not validators.check_domains(obj.domain):
                messages.add_message(
                    request, messages.ERROR,
                    _(u'该域名%(domain)s格式错误,无法验证!') % {'domain': domain})
                return HttpResponseRedirect(reverse('send_domain'))
            # 判断是否有相同已验证通过的域名
            if CustomerDomain.objects.exclude(id=id).filter(
                    domain=obj.domain, status__in=['Y', 'T']):
                obj.status = 'f'
                obj.save()
                messages.add_message(
                    request, messages.ERROR,
                    _(u'该域名:%(domain)s 已被其他客户占用,无法验证!') %
                    {'domain': obj.domain})
            else:
                obj.is_spf = 'Y' if valid_domain(
                    obj.domain, 'spf', 'include:spf.bestedm.org') else 'f'
                obj.is_mx = 'Y' if valid_domain(obj.domain, 'mx',
                                                'mail.bestedm.org') else 'f'
                obj.is_dkim = 'Y' if valid_domain(
                    obj.domain,
                    'dkim',
                    obj.dkim_public,
                    dkim_selector=obj.dkim_selector) else 'f'
                res = True if obj.is_spf == 'Y' and obj.is_mx == 'Y' else False
                obj.status = 'Y' if res else 'f'
                obj.save()
                if res:
                    loglevel = messages.SUCCESS
                    obj.api_sync('add-domain')
                    add_count = gen_mailbox(obj)
                    message = _(u'域名:%(domain)s, 验证通过!并随机生成%(count)d个账号!') % {
                        'domain': obj.domain,
                        'count': add_count
                    }
                else:
                    message = _(u'域名:%(domain)s, 验证未通过!') % {
                        'domain': obj.domain
                    }
                    loglevel = messages.WARNING
                messages.add_message(request, loglevel, message)
        elif action == 'delete':
            messages.add_message(
                request, messages.SUCCESS,
                _(u'域名:%(domain)s 删除成功!') % {'domain': obj.domain})
            CustomerMailbox.objects.filter(customer=request.user,
                                           domain=obj.domain).delete()
            obj.api_sync('del-domain')
            obj.delete()
        elif action == 'gen_mailbox':
            total = 0
            for a in DefaultMailbox.objects.all():
                mailbox = '{}@{}'.format(a.account, obj.domain)
                if not CustomerMailbox.objects.filter(mailbox=mailbox,
                                                      disabled='0'):
                    m_obj = CustomerMailbox(customer=request.user,
                                            domain=obj.domain,
                                            name=a.account,
                                            mailbox=mailbox,
                                            password=get_random_string(10))
                    m_obj.save()
                    m_obj.api_sync('add-mailbox')
                    total += 1
            messages.add_message(
                request, messages.SUCCESS,
                _(u'域名:%(domain)s 成功随机生成%(count)d个账号!') % {
                    'domain': obj.domain,
                    'count': total
                })

        return HttpResponseRedirect(reverse('send_domain'))

    lists = CustomerDomain.objects.filter(customer=request.user)
    count = lists.count()
    # 共享域名以及获取发件人
    ctype = CustomerDomainMailboxRel.objects.get_content_type('domain')
    share_domain_ids = CustomerDomainMailboxRel.objects.filter(
        customer=request.user, content_type=ctype).values_list('object_id',
                                                               flat=True)
    share_lists = CustomerDomain.objects.filter(customer=request.user.parent,
                                                id__in=share_domain_ids,
                                                status__in=['Y', 'T'])
    for obj in share_lists:
        count += 1
        obj.no_index = count

    form = CustomerDomainForm()
    # 获取系统域名
    domain_list = CustomerMailbox.objects.filter(
        customer=request.user).values_list('domain', flat=True).distinct()
    sys_domain_list = CustomerDomain.objects.filter(
        domain__in=list(domain_list), customer_id=0)

    track_domain_list = CustomerTrackDomain.objects.filter(
        customer=request.user)
    return render(request,
                  template_name='core/senddomain_list.html',
                  context={
                      'lists': lists,
                      'share_lists': share_lists,
                      'form': form,
                      'sys_domain_list': sys_domain_list,
                      'track_domain_list': track_domain_list,
                  })
Example #5
0
def core_mailbox_add(request):
    domain = request.GET.get('domain', '')
    is_share = request.GET.get('is_share', '')
    if is_share == '1':
        is_not_share = False
        domains = CustomerDomain.objects.filter(domain=domain,
                                                customer=request.user.parent)
        if not domains:
            raise Http404
    else:
        is_not_share = True
        domains = CustomerDomain.objects.filter(
            domain=domain, customer_id__in=[0, request.user.id])
        if not domains:
            raise Http404
    # 判读是不是系统域名
    is_sys = True if domains[0].customer_id == 0 else False
    lists = CustomerMailbox.objects.filter(customer=request.user,
                                           domain=domain).order_by('-id')
    is_customer_add = True if lists.count() < 20 else False

    if request.method == "POST":
        action = request.POST.get('action', '')
        id = request.POST.get('id', '')
        if request.user.service().is_umail:
            messages.add_message(request, messages.ERROR, _(u'测试帐号不允许此类操作!'))
            return HttpResponseRedirect(
                '/core/mailbox/add/?domain={}'.format(domain))

        if action == 'sub_del' and id:  # 删除共享发件人
            obj = get_object(CustomerMailbox, request.user.parent, id)
            ctype = CustomerDomainMailboxRel.objects.get_content_type(
                'mailbox')
            CustomerDomainMailboxRel.objects.filter(customer=request.user,
                                                    content_type=ctype,
                                                    object_id=id).delete()

            box_ids = CustomerDomainMailboxRel.objects.filter(
                customer=request.user,
                content_type=ctype).values_list('object_id', flat=True)
            box_count = CustomerMailbox.objects.filter(
                customer=request.user.parent, domain=domain,
                id__in=box_ids).count()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'删除账号( %(mailbox)s )成功') % {'mailbox': obj.mailbox})
            if box_count:
                return HttpResponseRedirect(
                    '/core/mailbox/add/?domain={}&is_share={}'.format(
                        domain, is_share))
            else:
                domain_obj = CustomerDomain.objects.filter(
                    customer=request.user.parent, domain=domain).first()
                if domain_obj:
                    domain_ctype = CustomerDomainMailboxRel.objects.get_content_type(
                        'domain')
                    CustomerDomainMailboxRel.objects.filter(
                        customer=request.user,
                        content_type=domain_ctype,
                        object_id=domain_obj.id).delete()
                return HttpResponseRedirect(reverse('send_domain'))

        password = request.POST.get('input_password', '')
        domain = request.POST.get('domain', '')
        mailbox = request.POST.get('input_mailbox', '').strip()
        ids = request.POST.get('ids', '')

        if action == 'sub_alter' and id:
            obj = get_object(CustomerMailbox, request.user.parent, id)
            obj.password = password
            obj.save()
            obj.api_sync('set-mailbox-pass')
            messages.add_message(request, messages.SUCCESS, _(u'修改账号密码成功'))
            return HttpResponseRedirect(
                '/core/mailbox/add/?domain={}&is_share={}'.format(
                    domain, is_share))

        if id:
            obj = get_object(CustomerMailbox, request.user, id)
        if action == 'del':
            messages.add_message(
                request, messages.SUCCESS,
                _(u'删除账号( %(mailbox)s )成功') % {'mailbox': obj.mailbox})
            obj.api_sync('del-mailbox')
            obj.delete()
        elif action == 'alter':
            obj.password = password
            obj.save()
            obj.api_sync('set-mailbox-pass')
            messages.add_message(request, messages.SUCCESS, _(u'修改账号密码成功'))
        elif action == 'add':
            #系统域名禁止添加账号
            if is_sys:
                raise Http404
            num = random.randint(10, 32)
            password = get_random_string(num)
            obj = CustomerMailbox(customer=request.user,
                                  domain=domain,
                                  name=mailbox,
                                  mailbox='{}@{}'.format(mailbox, domain),
                                  password=password,
                                  disabled='0')
            obj.api_sync('add-mailbox')
            obj.save()
            messages.add_message(request, messages.SUCCESS, _(u'新增账号成功'))
        elif action == 'muldel':
            ids = ids.split(',')
            for d in CustomerMailbox.objects.filter(id__in=ids):
                d.api_sync('del-mailbox')
                d.delete()
            messages.add_message(request, messages.SUCCESS, _(u'批量删除成功'))
        return HttpResponseRedirect(
            '/core/mailbox/add/?domain={}'.format(domain))

    return render(request,
                  template_name='core/core_mailbox_add.html',
                  context={
                      'domain': domain,
                      'is_sys': is_sys,
                      'is_customer_add': is_customer_add,
                      'is_not_share': is_not_share,
                  })
Example #6
0
def custom_kkserver_token2(request):
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
    from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
    from Crypto import Random

    random_generator = Random.new().read

    data = request.body
    print "data is ", data
    import json
    data = json.loads(data)
    mailbox = data.get("mailbox", "")
    rsakey = data.get("key", "")

    if not mailbox or not rsakey:
        rs = {
            "result": 1,
            "reason": _(u"数据不完整"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    private_key = DomainAttr.objects.filter(item='sw_custom_kkserver_rsakey',
                                            type='system',
                                            domain_id=0).first()
    if not private_key or not private_key.value:
        rs = {
            "result": 2,
            "reason": _(u"服务器未设置密钥"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    open_obj = DomainAttr.objects.filter(item='sw_custom_kkserver_sys_open',
                                         type='system',
                                         domain_id=0).first()
    if not open_obj or open_obj.value != "1":
        rs = {
            "result": 3,
            "reason": _(u"服务器未开启验证"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    verify_token = DomainAttr.objects.filter(
        item='sw_custom_kkserver_sys_token', type='system',
        domain_id=0).first()
    if not verify_token or not verify_token.value:
        rs = {
            "result": 4,
            "reason": _(u"服务器未设置验证口令"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    if isinstance(rsakey, unicode):
        rsakey = rsakey.encode("utf-8")

    code = base64.b64decode(rsakey)
    private_key = private_key.value
    cipher = Cipher_pkcs1_v1_5.new(private_key)
    decode_text = cipher.decrypt(base64.b64decode(rsakey), random_generator)

    if decode_text != verify_token:
        rs = {
            "result": 5,
            "reason": _(u"口令匹配失败"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    result = 0
    token = get_random_string(32)
    rs = {
        "result": result,
        "token": token,
    }
    return HttpResponse(json.dumps(rs), content_type="application/json")
Example #7
0
def custom_kkserver_token(request):
    try:
        data = json.loads(request.body)
    except:
        data = {}

    mailbox = data.get("mailbox", "")
    key = data.get("key", "")

    if not mailbox or not key:
        rs = {
            "result": 1,
            "reason": _(u"数据不完整"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    open_obj = DomainAttr.objects.filter(item='sw_custom_kkserver_sys_open',
                                         type='system',
                                         domain_id=0).first()
    if not open_obj or open_obj.value != "1":
        rs = {
            "result": 5,
            "reason": _(u"服务器未开启验证"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    obj = Mailbox.objects.filter(mailbox=mailbox).first()
    if not obj:
        rs = {
            "result": 2,
            "reason": _(u"无效用户"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    mailbox_id = obj.id
    verify_token = DomainAttr.objects.filter(
        item='sw_custom_kkserver_sys_token', type='system',
        domain_id=0).first()
    if not verify_token or not verify_token.value:
        rs = {
            "result": 3,
            "reason": _(u"服务器未设置验证口令"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    verify_token = verify_token.value
    if key != verify_token:
        rs = {
            "result": 4,
            "reason": _(u"口令匹配失败"),
        }
        return HttpResponse(json.dumps(rs), content_type="application/json")

    result = 0
    token = get_random_string(32)
    obj = ExtMailboxExtra.objects.filter(mailbox_id=mailbox_id,
                                         type="c_kkserver_token").first()
    if not obj:
        obj = ExtMailboxExtra.objects.create(
            mailbox_id=u"{}".format(mailbox_id),
            mailbox=u"{}".format(mailbox),
            type=u'c_kkserver_token',
            data=u"{}".format(token),
            last_update=time.strftime('%Y-%m-%d %H:%M:%S'))
    else:
        obj.type = u'c_kkserver_token'
        obj.data = u"{}".format(token)
        obj.last_update = time.strftime('%Y-%m-%d %H:%M:%S')
    obj.save()

    rs = {
        "result": result,
        "token": token,
    }
    return HttpResponse(json.dumps(rs), content_type="application/json")