Beispiel #1
0
def apply(request, template_name='apply.html'):
    if request.method == "POST":
        if not checksmscode(request, is_ajax=False):
            return HttpResponse(u'注册失败')
        username = request.POST.get('username', '')
        company = request.POST.get('company', '')
        linkman = request.POST.get('linkman', '')
        email = request.POST.get('email', '')
        qq = request.POST.get('qq', '')
        client_ip = get_client_ip(request)
        ApplyCustomer.objects.create(username=username,
                                     company=company,
                                     linkman=linkman,
                                     email=email,
                                     ip=client_ip,
                                     qq=qq)
        redis = get_redis_connection()
        redis.lpush(
            'edm_web_apply_notice_queue',
            json.dumps({
                'username': username,
                'company': company,
                'linkman': linkman,
                'email': email,
                'ip': client_ip,
                'qq': qq,
                'time': time.strftime('%Y-%m-%d %H:%M:%S')
            }))
        return HttpResponseRedirect(reverse('apply_step2'))

    return render(request, template_name, context={})
Beispiel #2
0
def ajax_smscode(request):
    status = 'Y'
    username = request.POST.get('username', '')
    not_check_username = request.POST.get('not_check_username', '')
    if not not_check_username:
        _exsited = Customer.objects.filter(username=username).exists()
        # 验证用户名是否存在
        if _exsited:
            return HttpResponse(json.dumps({'status': "N"}),
                                content_type="application/json")
    client_ip = get_client_ip(request)
    cache_key = 'register_smscode:{}'.format(client_ip)
    codes = cache.get(cache_key)

    if codes is None:
        cache.set(cache_key, {}, 24 * 60 * 60)
        codes = {}

    # 当天获取验证码次数
    if sum([len(v) for k, v in codes.iteritems()]) >= 3:
        return HttpResponse(json.dumps({'status': "C"}),
                            content_type="application/json")
    # 发送短信
    code, msg = sms_code.sms(username)
    # code, msg = 1, '1234'

    if code == -1:
        return HttpResponse(json.dumps({'status': 'E'}),
                            content_type="application/json")
    else:
        codes.setdefault(username, []).append((int(time.time()), msg, 1))
        cache.set(cache_key, codes)
    return HttpResponse(json.dumps({'status': status}),
                        content_type="application/json")
Beispiel #3
0
def get_user_agent_info(request):
    user_agent = get_user_agent(request)
    return {
        'browser':
        '{} {}'.format(user_agent.browser.family,
                       user_agent.browser.version_string),
        'os':
        '{} {}'.format(user_agent.os.family, user_agent.os.version_string),
        # 'ip': request.META['REMOTE_ADDR'],
        'ip':
        get_client_ip(request)
    }
Beispiel #4
0
def checksmscode(request, is_ajax=True):
    smscode = request.POST.get('smscode', '')
    username = request.POST.get('username', '')
    client_ip = get_client_ip(request)
    cache_key = 'register_smscode:{}'.format(client_ip)
    try:
        dict_codes = cache.get(cache_key)
        codes = dict_codes.get(username, [])

        send_time, code, status = codes[-1]
        if int(time.time()) - int(send_time) > 120 or int(status) != 1:
            code = ''
    except:
        code = ''
    if smscode == code:
        if not is_ajax:
            send_time, code, status = codes.pop()
            codes.append([send_time, code, 0])
            dict_codes[username] = codes
            cache.set(cache_key, dict_codes)
        return True
    return False
Beispiel #5
0
def sub_account_login(request):
    from django.contrib.auth.models import update_last_login
    from django.contrib.auth.views import logout, auth_login
    from django.contrib.auth import authenticate
    from django.contrib.auth.signals import user_logged_in

    parent_user_id = request.user.id
    client_ip = get_client_ip(request)
    agent = request.META.get('HTTP_USER_AGENT', None)
    ip_search = IpSearch()
    ip_info = ip_search.Find(client_ip)
    area, title = split_ip_to_area_title(ip_info)
    customer_id = request.POST.get('subloging_customer_id', '')
    auth = request.POST.get('subloging_auth', '')
    obj = get_customer_child_obj(request, customer_id)

    if auth == hashlib.md5(
            '%s-%s' %
        (settings.WEB_API_AUTH_KEY,
         datetime.datetime.now().strftime("%Y%m%d"))).hexdigest():
        logout(request)
        CoreLog.objects.create(
            user_id=parent_user_id,
            user_type='users',
            target_id=customer_id,
            target_name=u'{0} - {0}'.format(obj.username),
            action='user_login',
            ip=client_ip,
            desc=u'登录IP:{}<br>登录地区:{}<br>浏览器信息:{}'.format(
                client_ip, title, agent),
        )
        user = authenticate(username=obj.username,
                            password='',
                            t_password=obj.password)
        user_logged_in.disconnect(update_last_login)
        auth_login(request, user)
        user_logged_in.connect(update_last_login)
        return HttpResponseRedirect(reverse('home'))
    raise Http404
Beispiel #6
0
def sub_account_reback(request, user_id):
    obj = get_customer_child_obj(request, user_id)
    sub_service_obj = obj.service()
    if request.method == "POST":
        if sub_service_obj.is_share_flag == '2':
            service_obj = request.user.service()
            share_type = request.POST.get('share_type', '')
            qty_count = sub_service_obj.qty_count
            if qty_count <= 0:
                messages.add_message(request, messages.ERROR,
                                     _(u'收回群发量失败,子账户已经没有群发量'))
                return HttpResponseRedirect(reverse('sub_account'))

            if share_type == '1':  # 全部共享
                limit_qty = qty_count
            else:
                limit_qty = int(request.POST.get('limit_qty', '0'))
                if limit_qty <= 0:
                    limit_qty = 0
                if limit_qty > qty_count:
                    limit_qty = qty_count
            if limit_qty <= 0:
                messages.add_message(request, messages.ERROR,
                                     _(u'收回群发量失败,群发量不能填写小于等于0'))
                return HttpResponseRedirect(reverse('sub_account'))

            service_obj.qty_count = F('qty_count') + limit_qty
            service_obj.qty_valid = F('qty_valid') + limit_qty
            # 服务状态改变
            if service_obj.disabled == "1":
                service_obj.disabled = '0'
            service_obj.save()

            sub_service_obj.qty_count = F('qty_count') - limit_qty
            sub_service_obj.qty_valid = F('qty_valid') - limit_qty
            sub_service_obj.save()

            client_ip = get_client_ip(request)
            CoreLogList = [
                CoreLog(user=request.user,
                        user_type='users',
                        target=request.user,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='recharge_subuser',
                        ip=client_ip,
                        desc=u'+{}(母账户收回子账户({})群发量)'.format(
                            limit_qty, obj.username)),
                CoreLog(user=request.user,
                        user_type='users',
                        target=obj,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='recharge_subuser',
                        ip=client_ip,
                        desc=u'-{}(子账户({})被母账户收回群发量)'.format(
                            limit_qty, obj.username)),
            ]
            CoreLog.objects.bulk_create(CoreLogList)
            messages.add_message(request, messages.SUCCESS, (u'收回群发量成功'))
        return HttpResponseRedirect(reverse('sub_account'))
    return render(request,
                  template_name='setting/sub_account_reback.html',
                  context={
                      'user_id': user_id,
                      'user_obj': obj,
                      'sub_service_obj': sub_service_obj,
                  })
Beispiel #7
0
def sub_account_modify(request, user_id):
    obj = get_customer_child_obj(request, user_id)
    sub_service_obj = obj.service()
    if request.method == "POST":
        if sub_service_obj.is_share_flag == '2':
            service_obj = request.user.service()
            qty_count = int(request.POST.get('qty_count', '0'))
            if qty_count >= int(service_obj.qty_count):
                messages.add_message(request, messages.ERROR,
                                     _(u'分配的群发量已大于等于剩余群发量,分配群发量失败!'))
                return HttpResponseRedirect(reverse('sub_account'))

            service_obj.qty_count = F('qty_count') - qty_count
            service_obj.qty_valid = F('qty_valid') - qty_count
            # service_obj.qty_buytotal = F('qty_buytotal') - qty_count
            service_obj.save()

            sub_service_obj.qty_count = F('qty_count') + qty_count
            sub_service_obj.qty_valid = F('qty_valid') + qty_count
            # sub_service_obj.qty_buytotal = F('qty_buytotal') + qty_count
            # 服务状态改变
            if sub_service_obj.disabled == "1":
                sub_service_obj.disabled = '0'
            sub_service_obj.save()

            client_ip = get_client_ip(request)
            CoreLogList = [
                CoreLog(user=request.user,
                        user_type='users',
                        target=request.user,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='recharge_subuser',
                        ip=client_ip,
                        desc=u'-{}(分配群发量)'.format(qty_count)),
                CoreLog(user=request.user,
                        user_type='users',
                        target=obj,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='recharge_subuser',
                        ip=client_ip,
                        desc=u'+{}(分配群发量)'.format(qty_count)),
            ]
            CoreLog.objects.bulk_create(CoreLogList)
            msg = _(u'分配群发量成功')
        elif sub_service_obj.is_share_flag in ('3', '4'):
            share_type = request.POST.get('share_type', '')
            if share_type == '1':  # 全部共享
                limit_qty = 0
                is_share_flag = '4'
            else:
                is_share_flag = '3'
                limit_qty = int(request.POST.get('limit_qty', '0'))
            sub_service_obj.is_share_flag = is_share_flag
            sub_service_obj.limit_qty = limit_qty
            # 服务状态改变
            if sub_service_obj.disabled == "1":
                sub_service_obj.disabled = '0'
            sub_service_obj.save()
            msg = _(u'共享群发量成功')
        messages.add_message(request, messages.SUCCESS, msg)
        return HttpResponseRedirect(reverse('sub_account'))
    return render(request,
                  template_name='setting/sub_account_modify.html',
                  context={
                      'user_id': user_id,
                      'user_obj': obj,
                      'sub_service_obj': sub_service_obj,
                  })
Beispiel #8
0
def sub_account_create(request):
    service_obj = request.user.service()
    qty_buytotal = service_obj.qty_buytotal
    if service_obj.is_share_flag in ('2', '3', '4'):
        raise Http404
    if qty_buytotal < 100000:
        # messages.add_message(request, messages.ERROR, _('充值总量不足10万, 每充值10万封允许添加一个子账户。'))
        # return HttpResponseRedirect(reverse('sub_account'))
        # messages.add_message(request, messages.ERROR, _('充值总量不足10万, 每充值10万封允许添加一个子账户。'))
        # return redirect('sub_account')
        return render(request,
                      template_name='setting/sub_account_create.html',
                      context={
                          "cannot_add": True,
                      })

    limit_count = int(math.floor(float(qty_buytotal) / float(100000)))
    limit_count = 50 if limit_count > 50 else limit_count
    sub_count = Customer.objects.filter(parent_id=request.user.id).count()
    if request.method == "POST":
        if sub_count >= limit_count:
            messages.add_message(
                request, messages.ERROR,
                _(u'添加子账户失败,已达到添加子账户的上限(%(limit_count)s)!') % {
                    'limit_count': limit_count,
                })
            return HttpResponseRedirect(reverse('sub_account'))
        data = request.POST
        new_password2 = data.get('new_password2', None)
        password = md5_crypt.hash(new_password2)

        company = data.get('company', None)
        linkman = data.get('linkman', None)
        mobile = data.get('mobile', None)
        email = data.get('email', None)

        create_type = data.get('create_type', '')
        if create_type == '1':  # 分配
            is_share_flag = '2'
            limit_qty = 0
            qty_count = data.get('qty_count', '')
            qty_count = int(qty_count)
            if qty_count >= int(service_obj.qty_count):
                messages.add_message(request, messages.ERROR,
                                     _(u'分配的群发量已大于等于剩余群发量,添加子账户失败!'))
                return HttpResponseRedirect(reverse('sub_account'))
        else:
            qty_count = 0
            share_type = data.get('share_type', '')
            if share_type == '1':  # 全部共享
                limit_qty = 0
                is_share_flag = '4'
            else:  # 部分共享
                is_share_flag = '3'
                limit_qty = int(data.get('limit_qty', '0'))

        username = generate_username(request, sub_count, limit_count)

        manager_id = request.user.manager_id if request.user.manager_id else None
        sub_obj = Customer.objects.create(
            username=username,
            password=password,
            company=company,
            linkman=linkman,
            mobile=mobile,
            email=email,
            is_new=True,
            parent=request.user,
            manager_id=manager_id,
            phone=request.user.phone,
            im=request.user.im,
            address=request.user.address,
            homepage=request.user.homepage,
            estimate=request.user.estimate,
            industry=request.user.industry,
            web_style=request.user.web_style,
            lang_code=request.user.lang_code,
        )

        sub_service_obj = Services.objects.create(
            customer=sub_obj,
            is_trial=service_obj.is_trial,
            is_verify=service_obj.is_verify,
            server_type=service_obj.server_type,
            send_type=service_obj.send_type,
            service_type=service_obj.service_type,
            service_end='2099-12-31 23:59:59',
            error_stat_ratio=service_obj.error_stat_ratio,
            refuse_error_stat_ratio=service_obj.refuse_error_stat_ratio,
            ws_rate_limit=service_obj.ws_rate_limit,
            addr_export=service_obj.addr_export,
            addr_export_max=service_obj.addr_export_max,
            timezone=service_obj.timezone,
            cannotview_html=service_obj.cannotview_html,
            unsubscribe_html=service_obj.unsubscribe_html,
            is_maintain=service_obj.is_maintain,
            is_high_quality=service_obj.is_high_quality,
            is_replace_sender=service_obj.is_replace_sender,
            is_allow_red_tpl=service_obj.is_allow_red_tpl,
            is_allow_cy_tpl=service_obj.is_allow_cy_tpl,
            maintain_rate=service_obj.maintain_rate,
            is_autoremove=service_obj.is_autoremove,
            is_auto_duplicate=service_obj.is_auto_duplicate,
            duplicate_type=service_obj.duplicate_type,
            is_stmp=service_obj.is_stmp,
            is_need_receipt=service_obj.is_need_receipt,
            is_open_accurate=service_obj.is_open_accurate,
            is_umail=service_obj.is_umail,
            qty_count=qty_count,
            qty_valid=qty_count,
            qty_buytotal=0,
            is_share_flag=is_share_flag,
            limit_qty=limit_qty,
            is_address=False,
            is_template=False,
            is_task=False,
        )
        client_ip = get_client_ip(request)
        if create_type == '1':
            service_obj.qty_count = F('qty_count') - qty_count
            service_obj.qty_valid = F('qty_valid') - qty_count
            # service_obj.qty_buytotal = F('qty_buytotal') - qty_count
            service_obj.save()

            CoreLogList = [
                CoreLog(user=request.user,
                        user_type='users',
                        target=request.user,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='add_subuser',
                        ip=client_ip,
                        desc=u'给子账户分配群发量:{}'.format(qty_count)),
                CoreLog(user=request.user,
                        user_type='users',
                        target=request.user,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='recharge_subuser',
                        ip=client_ip,
                        desc=u'-{}(分配群发量)'.format(qty_count)),
                CoreLog(user=request.user,
                        user_type='users',
                        target=sub_obj,
                        target_name=u'{0} - {0}'.format(sub_obj.username),
                        action='add_subuser',
                        ip=client_ip,
                        desc=u'分配方式创建,获得群发量:{}'.format(qty_count)),
                CoreLog(user=request.user,
                        user_type='users',
                        target=sub_obj,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='recharge_subuser',
                        ip=client_ip,
                        desc=u'+{}(分配群发量)'.format(qty_count)),
            ]
            CoreLog.objects.bulk_create(CoreLogList)
        else:
            desc = u'全部共享' if share_type == '1' else u'部分共享,子账户最多可以使用母账户群发量为:{}'.format(
                limit_count)
            CoreLogList = [
                CoreLog(user=request.user,
                        user_type='users',
                        target=request.user,
                        target_name=u'{0} - {0}'.format(request.user.username),
                        action='add_subuser',
                        ip=client_ip,
                        desc=desc),
                CoreLog(user=request.user,
                        user_type='users',
                        target=sub_obj,
                        target_name=u'{0} - {0}'.format(sub_obj.username),
                        action='add_subuser',
                        ip=client_ip,
                        desc=desc),
            ]
            CoreLog.objects.bulk_create(CoreLogList)
        messages.add_message(request, messages.SUCCESS, _(u'添加子账户成功'))
        return HttpResponseRedirect(reverse('sub_account'))
    return render(request,
                  template_name='setting/sub_account_create.html',
                  context={
                      'leave_qty': service_obj.qty_count,
                  })
Beispiel #9
0
    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        captcha = self.cleaned_data.get('captcha')
        redis = get_redis_connection()
        key = 'captcha:{}'.format(captcha)
        if redis.hget(key, 'res') != 'True':
            raise forms.ValidationError(
                self.error_messages_captcha['invalid_login'],
                code='invalid_login',
                params={'username': self.username_field.verbose_name},
            )
        redis.delete(key)

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            login_ip = get_client_ip(self.request)
            ##### 地区登录保护 #####
            if self.user_cache:
                if self.user_cache.disabled == '1':
                    raise forms.ValidationError(
                        self.error_messages_disabled['invalid_login'],
                        code='invalid_login',
                        params={'username': self.username_field.verbose_name},
                    )
                if self.user_cache.parent and self.user_cache.parent.disabled == '1':
                    raise forms.ValidationError(
                        self.error_messages_disabled2['invalid_login'],
                        code='invalid_login',
                        params={'username': self.username_field.verbose_name},
                    )
                weixin_customer_id = self.user_cache.weixin_customer_id
                customer_id = self.user_cache.id
                ip_search = IpSearch()
                ip_info = ip_search.Find(login_ip)
                login_area1, login_area2 = parse_login_area(ip_info)
                obj, _created = CoreLoginAreaIp.objects.get_or_create(
                    user_id=customer_id)
                is_open = False if _created else obj.is_open
                _exists = CoreLoginAreaIp.objects.filter(
                    Q(user_id=customer_id, ip__icontains=login_ip)
                    | Q(user_id=customer_id, area__icontains=login_area1)
                    | Q(user_id=customer_id, area__icontains=login_area2)
                ).exists()
                if is_open and not _exists:
                    j_area, j_title = split_ip_to_area_title(ip_info)
                    redis.rpush(
                        'edm_web_notice_queue',
                        json.dumps({
                            "type": "1",
                            'customer_id': customer_id,
                            "area": j_title,
                            'point': '',
                            'domain': '',
                            'task': '',
                        }))
                    if weixin_customer_id:
                        raise forms.ValidationError(
                            self.error_messages_loginsafe['invalid_login'],
                            code='invalid_login',
                            params={
                                'username': self.username_field.verbose_name
                            },
                        )
                    else:
                        raise forms.ValidationError(
                            self.error_messages_loginsafe2['invalid_login'],
                            code='invalid_login',
                            params={
                                'username': self.username_field.verbose_name
                            },
                        )

            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.user_cache.last_ip = login_ip
                self.user_cache.last_login = timezone.now()
                self.user_cache.save(update_fields=['last_ip', 'last_login'])
                agent = self.request.META.get('HTTP_USER_AGENT', None)
                self.user_cache.save_login_log(login_ip, ip_info, agent)
                self.confirm_login_allowed(self.user_cache)

                # 关注用户上线通知
                s = self.user_cache.service()
                if s and s.is_pushcrew:
                    action = "service"
                    title = u"登录提醒"
                    message = u"{}(ID: {}) 于 {} 时间登录平台".format(
                        self.user_cache.company, self.user_cache.id,
                        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    pushcrew_notice(action, title, message)

        return self.cleaned_data