Exemplo n.º 1
0
def log_user_logged_in_failed(sender, credentials, request, **kwargs):
    try:
        user_agent_info = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255],
        user_login_activity_log = UserLoginLogoutActivity(locatiom_IP=get_client_ip(request),
                                                    username=credentials['email'],
                                                    user_agent_info=user_agent_info,
                                                    status=UserLoginLogoutActivity.FAILED,
                                                    category=UserLoginLogoutActivity.LOGIN)
        user_login_activity_log.save()
    except Exception as e:
        # log the error
        logger.error("log_user_logged_in request: %s, error: %s" % (request, e))
Exemplo n.º 2
0
def log_user_logged_out(sender, user, request, **kwargs):
    try:
        user_agent_info = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255],
        user_logout_activity_log = UserLoginLogoutActivity(location_IP=get_client_ip(request),
                                                    username=user.email,
                                                    user_agent_info=user_agent_info,
                                                    status=UserLoginLogoutActivity.SUCCESS,
                                                    category=UserLoginLogoutActivity.LOGOUT)
        user_logout_activity_log.save()
    except Exception as e:
        # log the error
        logger.error("log_user_logged_in request: %s, error: %s" % (request, e))
Exemplo n.º 3
0
    def can_i_create_claim(self, request):
        """
        Memcached store where keys is ip addresses of customers,
        and values is list of latest retries.
        """

        ip = get_client_ip(request)
        stored = self._get(ip)

        if not stored or type(stored) != list:
            self._set(ip, [time.time()])
            return True
        else:
            stored.append(time.time())
            self._set(ip, stored)

            return not len(stored) > settings.CLAIMS_PER_HOUR
Exemplo n.º 4
0
    def post(self, request):
        logger.info('Incident request data:{}'.format(request.data))
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid(raise_exception=True):
            try:
                print('user Ip address a:' +
                      request.META.get('HTTP_X_REAL_IP'))
            except:
                pass
            try:
                print('user Ip address b:' + request.headers['X-Real-IP'])
            except:
                pass

            client_ip_x = request.META['REMOTE_ADDR']
            print('user Ip address:' + client_ip_x)
            client_ip = get_client_ip(request)
            geo_location_response = geolocation.geolocationClient.get_location(
                client_ip)
            print(geo_location_response)
            logger.info('geo_location_response response:{}'.format(
                geo_location_response))
            data = serializer.validated_data
            if geo_location_response is not None:
                serializer.save(
                    ip_address=client_ip,
                    latitude=geo_location_response['latitude'],
                    longitude=geo_location_response['longitude'],
                    country_name=geo_location_response['country_name'],
                    country_code=geo_location_response['country_code'],
                    city=geo_location_response['city'],
                    region=geo_location_response['region'])
                response = {
                    'status': '00',
                    'message': "Incident was created successfully "
                }
                logger.info('incident was created successfully')
                return Response(response, status=status.HTTP_200_OK)
        return Response(
            {
                'message': 'An error occurred while processing yur request',
                'error': serializer.errors,
            },
            status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 5
0
    def get(self, request):
        resp_dict = {
            'login_error': request.GET.get('login_error', 0),
            'page': 'single',
            'org_types': OrganizationType.objects.all()
                .prefetch_related("claimtype_set").order_by('name'),
            'test_alarm': False}

        claim_type_sets = {}
        for org_type in resp_dict['org_types']:
            claim_type_set = []
            for claim_type in org_type.claimtype_set.all():
                claim_type_set.append({'id': claim_type.id,
                                      'value': claim_type.name})
            claim_type_sets[org_type.type_id] = claim_type_set

        resp_dict['claim_types'] = mark_safe(json.dumps(claim_type_sets))

        if settings.RECAPTCHA_ENABLED is False:
            settings.RECAPTCHA_PUBLIC = ''
        resp_dict['recaptcha_public'] = settings.RECAPTCHA_PUBLIC

        if settings.TEST_SERVER:
            resp_dict['test_alarm'] = True

        ip = get_client_ip(request)
        # cached_zoom = cache.get('lat_lon_for::%s' % ip)

        # if cached_zoom is not None:
        #     resp_dict['zoom_to']=cached_zoom
        # else:
        g = GeoIP2()
        try:
            if g.country(ip)['country_code'] == settings.COUNTRY_CODE:
                resp_dict['zoom_to'] = list(g.lat_lon(ip))
            else:
                resp_dict['zoom_to'] = settings.DEFAULT_ZOOM
        except AddressNotFoundError:
            resp_dict['zoom_to'] = settings.DEFAULT_ZOOM

            # cache.set('lat_lon_for::%s' % ip, resp_dict['zoom_to'])

        return render(request, self.template_name, resp_dict)
Exemplo n.º 6
0
def add_claim(request):
    if settings.RECAPTCHA_ENABLED and not request.user.is_authenticated():
        if not request.POST.get('g-recaptcha-response', False):
            raise Exception('Google reCaptcha verification not passed')

        response = requests.post(
            "https://www.google.com/recaptcha/api/siteverify",
            {
                "secret": settings.RECAPTCHA_SECRET,
                "response": request.POST.get('g-recaptcha-response', False),
                "remoteip": get_client_ip(request)
            }
        ).json()

        if not response['success']:
            raise Exception('Google think user is not real.')

    user = None if request.POST.get(
        'anonymously',
        False) or not request.user.is_authenticated() else request.user

    code = 500

    if (
        request.POST.get('org_id', False) and
        request.POST.get('claim_text', False)
    ):
        claim = Claim(
            text=escape(request.POST.get('claim_text', False)),
            servant=escape(request.POST.get('servant', False)),
            bribe=escape(request.POST.get('bribe', 0)),
            complainer=user,
            organization=Organization.objects.get(
                id=request.POST.get('org_id', False)),
            claim_type=ClaimType.objects.get(
                id=request.POST.get('claim_type', False)),
            moderation=user and 'not_moderated' or 'anonymous',
        )
        claim.save()
        # Correct insert code
        code = 201

    return HttpResponse(status=code)
Exemplo n.º 7
0
    def get(self, request):
        resp_dict = {
            'login_error': request.GET.get('login_error', 0),
            'page': 'single',
            'org_types': OrganizationType.objects.all(),
            'test_alarm': False
        }

        claim_type_sets = {}
        for org_type in resp_dict['org_types']:
            claim_type_set = []
            for claim_type in org_type.claimtype_set.all():
                claim_type_set.append({
                    'id': claim_type.id,
                    'value': claim_type.name
                })
            claim_type_sets[org_type.type_id] = claim_type_set

        resp_dict['claim_types'] = mark_safe(json.dumps(claim_type_sets))

        if settings.RECAPTCHA_ENABLED is False:
            settings.RECAPTCHA_PUBLIC = ''
        resp_dict['recaptcha_public'] = settings.RECAPTCHA_PUBLIC

        if settings.TEST_SERVER:
            resp_dict['test_alarm'] = True

        if hasattr(settings, 'TEST_COORDINATES'):
            resp_dict['zoom_to'] = getattr(settings, 'TEST_COORDINATES')
        else:
            g = GeoIP2()
            ip = get_client_ip(request)
            try:
                if g.country(ip)['country_code'] == settings.COUNTRY_CODE:
                    resp_dict['zoom_to'] = list(g.lat_lon(ip))
                else:
                    resp_dict['zoom_to'] = settings.DEFAULT_ZOOM
            except AddressNotFoundError:
                resp_dict['zoom_to'] = settings.DEFAULT_ZOOM

        return render(request, self.template_name, resp_dict)
Exemplo n.º 8
0
def add_claim(request):
    if settings.RECAPTCHA_ENABLED and not request.user.is_authenticated():
        if not request.POST.get('g-recaptcha-response', False):
            raise Exception('Google reCaptcha verification not passed')

        response = requests.post(
            "https://www.google.com/recaptcha/api/siteverify", {
                "secret": settings.RECAPTCHA_SECRET,
                "response": request.POST.get('g-recaptcha-response', False),
                "remoteip": get_client_ip(request)
            }).json()

        if not response['success']:
            raise Exception('Google think user is not real.')

    user = None if request.POST.get(
        'anonymously',
        False) or not request.user.is_authenticated() else request.user

    code = 500

    if (request.POST.get('org_id', False)
            and request.POST.get('claim_text', False)):
        claim = Claim(
            text=escape(request.POST.get('claim_text', False)),
            servant=escape(request.POST.get('servant', False)),
            bribe=escape(request.POST.get('bribe', 0)),
            complainer=user,
            organization=Organization.objects.get(
                id=request.POST.get('org_id', False)),
            claim_type=ClaimType.objects.get(
                id=request.POST.get('claim_type', False)),
            moderation=user and 'not_moderated' or 'anonymous',
        )
        claim.save()
        # Correct insert code
        code = 201

    return HttpResponse(status=code)
Exemplo n.º 9
0
    def get(self, request):
        resp_dict = {
            'login_error': request.GET.get('login_error', 0),
            'page': 'single',
            'org_types': OrganizationType.objects.all(),
            'test_alarm': False}

        claim_type_sets = {}
        for org_type in resp_dict['org_types']:
            claim_type_set = []
            for claim_type in org_type.claimtype_set.all():
                claim_type_set.append({'id': claim_type.id,
                                      'value': claim_type.name})
            claim_type_sets[org_type.type_id] = claim_type_set

        resp_dict['claim_types'] = mark_safe(json.dumps(claim_type_sets))

        if settings.RECAPTCHA_ENABLED is False:
            settings.RECAPTCHA_PUBLIC = ''
        resp_dict['recaptcha_public'] = settings.RECAPTCHA_PUBLIC

        if settings.TEST_SERVER:
            resp_dict['test_alarm'] = True

        if hasattr(settings, 'TEST_COORDINATES'):
            resp_dict['zoom_to'] = getattr(settings, 'TEST_COORDINATES')
        else:
            g = GeoIP2()
            ip = get_client_ip(request)
            try:
                if g.country(ip)['country_code'] == settings.COUNTRY_CODE:
                    resp_dict['zoom_to'] = list(g.lat_lon(ip))
                else:
                    resp_dict['zoom_to'] = settings.DEFAULT_ZOOM
            except AddressNotFoundError:
                resp_dict['zoom_to'] = settings.DEFAULT_ZOOM

        return render(request, self.template_name, resp_dict)