コード例 #1
0
ファイル: decorators.py プロジェクト: dx150717/newton-www
 def _decorator(request, *args, **kwargs):
     sign = request.POST.get('sign')
     app_key = request.POST.get('app_key')
     if app_key in settings.APP_KEY_TO_SECRET:
         secret = settings.APP_KEY_TO_SECRET[app_key]
     else:
         secret = settings.API_ACCESS_SECRET
     if settings.LOGGING_API_REQUEST:
         logger.debug("request: %s" % str(request.POST))
     signed_string = security.sign_hmac(request.POST, secret=secret)
     if sign == signed_string or (settings.DEBUG and
                                  not settings.SECURITY_API_ACCESS_AUTH):
         if settings.CHANGE_SYSTEM_SERVICE_ENABLE:
             status_info = operation_services.get_service_status()
             if status_info.get(
                     'status') == codes.SystemServiceStatus.MAINTAIN.value:
                 return http.JsonErrorResponse(
                     codes.ErrorCode.MAINTAIN.value,
                     error_message=status_info.get('msg'),
                     data={'m_time': status_info.get('m_time')})
         response = func(request, *args, **kwargs)
         if settings.LOGGING_API_REQUEST:
             logger.debug("response: %s" % str(response))
         return response
     logger.error("signed_string error!")
     return http.JsonErrorResponse(codes.ErrorCode.SIGN_ERROR.value)
コード例 #2
0
ファイル: views.py プロジェクト: dx150717/newton-www
def check_session_auth(request):
    try:
        session_key = request.GET.get('sid')
        cache_key = 'django.contrib.sessions.cache' + session_key
        if cache.get(cache_key):
            return http.JsonSuccessResponse()
        return http.JsonErrorResponse()
    except Exception, inst:
        logger.exception("fail to check session auth:%s" % str(inst))
        return http.JsonErrorResponse()
コード例 #3
0
ファイル: decorators.py プロジェクト: dx150717/newton-www
 def _decorator(request, *args, **kwargs):
     auth_token = request.POST.get('auth_token')
     user = auth_services.check_auth_token(auth_token)
     if user and hasattr(user, 'userprofile'):
         request.user = User.objects.get(id=user.id)
         if request.user.is_active == False:
             return http.JsonErrorResponse(codes.ErrorCode.BLOCK_USER.value)
         return func(request, *args, **kwargs)
     logger.info('auth_required:unauth:POST:%s' % request.POST)
     return http.JsonErrorResponse(codes.ErrorCode.UNAUTH.value)
コード例 #4
0
def check_captcha(request):
    """Check the captcha
    """
    try:
        code = request.GET.get('code')
        real_code = ishuman_services.get_captcha(request.session.session_key)
        if code and code.lower() == real_code.lower():
            return http.JsonSuccessResponse()
        else:
            return http.JsonErrorResponse()
    except Exception, inst:
        logger.exception("fail to check captcha:%s" % str(inst))
        return http.JsonErrorResponse()
コード例 #5
0
def subscribe(request):
    """
    Add email address to email list database.
    User can add email once per minute.
    """
    try:
        # check robot
        form = forms.SubscribeForm(request.POST)
        if not form.is_valid():
            return http.JsonErrorResponse(error_message=_("Email Error"))
        code = form.cleaned_data['code']
        if code != ishuman_services.get_captcha(request.session.session_key):
            return http.JsonErrorResponse(
                error_message=_("Authenticator Recaptcha Error"))
        was_limited = getattr(request, 'limited', False)
        if was_limited:
            return http.JsonErrorResponse(
                error_message=_("You can only subscribe once per minute."))
        email_address = form.cleaned_data['email_address']
        subscribed_email = subscription_model.SubscribedEmail.objects.filter(
            email_address=email_address).first()
        if subscribed_email:
            if subscribed_email.status == codes.StatusCode.RELEASE.value:
                return http.JsonErrorResponse(
                    error_message=_('Email Has Exist!'))
            else:
                is_send_success = do_send_mail(subscribed_email, request)
                if is_send_success:
                    return http.JsonSuccessResponse(
                        data={
                            "msg":
                            _("we've sent you a confirming e-mail,please check your email box."
                              )
                        })
                else:
                    return http.JsonErrorResponse(
                        error_message=_("Subscribe Failed!"))
        else:
            subscribed_email = subscription_model.SubscribedEmail(
                email_address=email_address)
            subscribed_email.uuid = security.generate_uuid()
            subscribed_email.save()
            is_send_success = do_send_mail(subscribed_email, request)
            if is_send_success:
                return http.JsonSuccessResponse(
                    data={
                        "msg":
                        _("we've sent you a confirming e-mail,please check your email box."
                          )
                    })
            else:
                return http.JsonErrorResponse(
                    error_message=_("Subscribe Failed!"))
    except ValidationError:
        return http.JsonErrorResponse(
            error_message=_("Invalid Email Address!"))
    except Exception, inst:
        logger.error("fail to subscribe: %s" % str(inst))
        return http.JsonErrorResponse()
コード例 #6
0
 def decorator(request, *args, **kwargs):
     try:
         os_type = request.POST['os']
         version = request.POST['version']
         is_valid_platform = True
         if os_type == 'ios':
             platform_type = codes.AppPlatform.IOS.value
         elif os_type == 'android':
             platform_type = codes.AppPlatform.ANDROID.value
         else:
             is_valid_platform = False
             logger.error('check_upgrade: invalid platform type %s' % os_type)
         if is_valid_platform:
             cache_key = '%s-%s' % (settings.CACHE_KEY_CHECK_UPGRADE, platform_type)
             upgrade_cache = cache.get(cache_key)
             if not upgrade_cache:
                 upgrade = Upgrade.objects.filter(status=codes.StatusCode.AVAILABLE.value, is_show=True,
                                              platform_type = platform_type).order_by('-created_at').first()
                 if upgrade:
                     upgrade_cache = model_to_dict(upgrade, fields=['version_code', 'download_url', ])
                     upgrade_cache['version'] = upgrade.version_name
                     upgrade_cache['is_force_upgrade'] = upgrade.is_force
                     upgrade_cache['is_show'] = upgrade.is_show
                     upgrade_cache['message'] = str(upgrade.description)
                     cache.set(cache_key, upgrade_cache)
             if upgrade_cache and upgrade_cache.get('is_show') and upgrade_cache.get('version') and upgrade_cache.get('version') > version and upgrade_cache.get('is_force_upgrade'):
                 return http.JsonErrorResponse(codes.ErrorCode.UPGRADE.value, data=upgrade_cache)
     except Exception, inst:
         logger.error("force upgrade required: %s", inst)
コード例 #7
0
 def _decorator(request, *args, **kwargs):
     auth_token = request.POST.get('auth_token')
     user = auth_services.check_auth_token(auth_token)
     request.user = user
     if user:
         if hasattr(request.user, 'userprofile'):
             if request.user.userprofile.user_type == codes.UserType.COMPANY.value:
                 try:
                     request.user = User.objects.get(id=user.id)
                     if request.user.is_active == True:
                         return func(request, *args, **kwargs)
                 except Exception, e:
                     logger.error(str(e))
             else:
                 return http.JsonErrorResponse(error_message=u'您未注册企业。')
コード例 #8
0
def subscribed_confirm(request):
    try:
        uuid = request.GET['uuid']
        subscribed_email = subscription_model.SubscribedEmail.objects.filter(
            uuid=uuid).first()
        if subscribed_email:
            code = subscribed_email.status
            if code == codes.StatusCode.AVAILABLE.value:
                subscribed_email.status = codes.StatusCode.RELEASE.value
                subscribed_email.save()
            return render(request, 'subscription/confirm.html')
        else:
            logger.error("fail to find email by uuid: %s" % str(uuid))
            error_message = _("Links expire or invalid pages.")
            return render(request, "subscription/subscribe_failed.html",
                          locals())
    except Exception, inst:
        logger.error("fail to confirm email: %s" % str(inst))
        return http.JsonErrorResponse()
コード例 #9
0
ファイル: __init__.py プロジェクト: dx150717/newton-www
def get_events_date(request):
    """
    Get all events date for events calendar request
    :param request:
    :return: JsonResponse
    """
    try:
        entry = EntryDetail()
        entries_date = entry.get_queryset().filter(entry_type=TYPE_EVENTS).dates("event_date", "day")
        result = []
        for entry_date in entries_date:
            event_data = {}
            event_data["start"] = str(entry_date)
            event_data["url"] = "?event_date=%s" % str(entry_date)
            result.append(event_data)
        return http.JsonSuccessResponse(data=result)
    except Exception, inst:
        logger.exception("fail to get events date: %s" % str(inst))
        return http.JsonErrorResponse()
コード例 #10
0
def api_show_top_accounts(request, version):
    """ show the accounts ordered by balance descending

    response
    -------
    {
        "total_page": 1,
        "current_page": 1,
        "total_addresses": 210000,
        "total_transactions": 32600,
        "account_list": [
            {
                "rank": 1,
                "address": "NEW17xJKkRcaXhG9G51b5iy8vs37AVsTw9XPgGw",
                "balance": '1000000',
                "txn_count": 273            # the number of transactions
            },
        ]
    }
    """
    try:
        page_id = int(request.GET.get('pageNum', 1))
        res = {}
        limit = int(request.GET.get('limit', settings.PAGE_SIZE))
        if limit > settings.PAGE_SIZE:
            limit = settings.PAGE_SIZE
        if ":" in settings.MONGODB_HOST:                      # split MONGODB_HOST to host and port
            mongo_list = settings.MONGODB_HOST.split(":")
            client = MongoClient(mongo_list[0], int(mongo_list[1]))
        else:
            client = MongoClient(host=settings.MONGODB_HOST)
        db = client[settings.BLOCK_CHAIN_DB_NAME]
        collection = db['account']
        objs = collection.find({}).collation({"locale": "en", "numericOrdering": True}).sort([("balance", -1), ("transactions_number", -1)])
        if objs:
            cnt = collection.count_documents({})
            if cnt == 0:
                total_page = 1
            elif cnt >= settings.PAGE_SIZE * settings.ADDRESS_MAX_PAGE_NUM:
                total_page = settings.ADDRESS_MAX_PAGE_NUM
            else:
                if cnt % settings.PAGE_SIZE != 0:
                    total_page = (cnt / settings.PAGE_SIZE) + 1
                else:
                    total_page = (cnt / settings.PAGE_SIZE)
            res['total_page'] = total_page
            if page_id > total_page:
                return http.JsonErrorResponse(error_message='large', data=res)
            skip_num = (page_id - 1) * settings.PAGE_SIZE
            obj = objs.skip(skip_num).limit(limit)
            account_list = []
            for index, ele in enumerate(obj):
                account = {}
                account['rank'] = skip_num + index + 1
                account['address'] = addr_translation.address_encode(ele['_id'])
                account['balance'] = Decimal(ele['balance']) / DECIMAL_SATOSHI
                account['txn_count'] = ele['transactions_number']
                account_list.append(account)
            res['account_list'] = account_list
            res['current_page'] = page_id
            res['total_addresses'] = cnt
            res['total_transactions'] = provider_models.Statistics.objects.first().transactions_number
        client.close()
        return http.JsonResponse(res)
    except Exception, inst:
        print inst
        logger.exception("fail to show top accounts:%s" % str(inst))
        return http.HttpResponseServerError()