本文整理汇总了Python中sentry.app.ratelimiter.is_limited函数的典型用法代码示例。如果您正苦于以下问题:Python is_limited函数的具体用法?Python is_limited怎么用?Python is_limited使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_limited函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: recover
def recover(request):
from sentry.app import ratelimiter
if request.method == 'POST' and ratelimiter.is_limited(
'accounts:recover:{}'.format(request.META['REMOTE_ADDR']),
limit=5, window=60, # 5 per minute should be enough for anyone
):
return HttpResponse(
'You have made too many password recovery attempts. Please try again later.',
content_type='text/plain',
status=429,
)
form = RecoverPasswordForm(request.POST or None)
if form.is_valid():
password_hash = send_password_recovery_mail(request, form.cleaned_data['user'])
return render_to_response('sentry/account/recover/sent.html', {
'email': password_hash.user.email,
}, request)
context = {
'form': form,
}
return render_to_response('sentry/account/recover/index.html', context, request)
示例2: start_confirm_email
def start_confirm_email(request):
from sentry.app import ratelimiter
if ratelimiter.is_limited(
'auth:confirm-email:{}'.format(request.user.id),
limit=10, window=60, # 10 per minute should be enough for anyone
):
return HttpResponse(
'You have made too many email confirmation requests. Please try again later.',
content_type='text/plain',
status=429,
)
if 'primary-email' in request.POST:
email = request.POST.get('email')
try:
email_to_send = UserEmail.objects.get(user=request.user, email=email)
except UserEmail.DoesNotExist:
msg = _('There was an error confirming your email.')
level = messages.ERROR
else:
request.user.send_confirm_email_singular(email_to_send)
msg = _('A verification email has been sent to %s.') % (email)
level = messages.SUCCESS
messages.add_message(request, level, msg)
return HttpResponseRedirect(reverse('sentry-account-settings'))
elif request.user.has_unverified_emails():
request.user.send_confirm_emails()
unverified_emails = [e.email for e in request.user.get_unverified_emails()]
msg = _('A verification email has been sent to %s.') % (', ').join(unverified_emails)
else:
msg = _('Your email (%s) has already been verified.') % request.user.email
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect(reverse('sentry-account-settings-emails'))
示例3: _is_ip_rate_limited
def _is_ip_rate_limited(self):
limit = options.get('auth.ip-rate-limit')
if not limit:
return False
ip_address = self.request.META['REMOTE_ADDR']
return ratelimiter.is_limited(
u'auth:ip:{}'.format(ip_address),
limit,
)
示例4: should_notify
def should_notify(self, group, event):
if group.is_muted():
return False
project = group.project
rate_limited = ratelimiter.is_limited(project=project, key=self.get_conf_key(), limit=15)
if rate_limited:
self.logger.info("Notification for project %s dropped due to rate limiting", project.id)
return not rate_limited
示例5: post
def post(self, request):
"""
Create a New Organization
`````````````````````````
Create a new organization owned by the request's user. To create
an organization only the name is required.
:param string name: the human readable name for the new organization.
:param string slug: the unique URL slug for this organization. If
this is not provided a slug is automatically
generated based on the name.
:auth: required, user-context-needed
"""
if not request.user.is_authenticated():
return Response({"detail": "This endpoint requires user info"}, status=401)
if not features.has("organizations:create", actor=request.user):
return Response({"detail": "Organizations are not allowed to be created by this user."}, status=401)
limit = options.get("api.rate-limit.org-create")
if limit and ratelimiter.is_limited(u"org-create:{}".format(request.user.id), limit=5, window=3600):
return Response({"detail": "You are attempting to create too many organizations too quickly."}, status=429)
serializer = OrganizationSerializer(data=request.DATA)
if serializer.is_valid():
result = serializer.object
try:
with transaction.atomic():
org = Organization.objects.create(name=result["name"], slug=result.get("slug"))
except IntegrityError:
return Response({"detail": "An organization with this slug already exists."}, status=409)
om = OrganizationMember.objects.create(organization=org, user=request.user, role=roles.get_top_dog().id)
if result.get("defaultTeam"):
team = org.team_set.create(name=org.name)
OrganizationMemberTeam.objects.create(team=team, organizationmember=om, is_active=True)
self.create_audit_entry(
request=request,
organization=org,
target_object=org.id,
event=AuditLogEntryEvent.ORG_ADD,
data=org.get_audit_log_data(),
)
return Response(serialize(org, request.user), status=201)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例6: _is_user_rate_limited
def _is_user_rate_limited(self):
limit = options.get('auth.user-rate-limit')
if not limit:
return False
username = self.cleaned_data.get('username')
if not username:
return False
return ratelimiter.is_limited(
u'auth:username:{}'.format(username),
limit,
)
示例7: recover
def recover(request):
from sentry.app import ratelimiter
extra = {
'ip_address': request.META['REMOTE_ADDR'],
'user_agent': request.META.get('HTTP_USER_AGENT'),
}
if request.method == 'POST' and ratelimiter.is_limited(
u'accounts:recover:{}'.format(extra['ip_address']),
limit=5,
window=60, # 5 per minute should be enough for anyone
):
logger.warning('recover.rate-limited', extra=extra)
return HttpResponse(
'You have made too many password recovery attempts. Please try again later.',
content_type='text/plain',
status=429,
)
prefill = {'user': request.GET.get('email')}
form = RecoverPasswordForm(request.POST or None, initial=prefill)
extra['user_recovered'] = form.data.get('user')
if form.is_valid():
email = form.cleaned_data['user']
if email:
password_hash = LostPasswordHash.for_user(email)
password_hash.send_email(request)
extra['passwordhash_id'] = password_hash.id
extra['user_id'] = password_hash.user_id
logger.info('recover.sent', extra=extra)
tpl = 'sentry/account/recover/sent.html'
context = {'email': email}
return render_to_response(tpl, context, request)
if form._errors:
logger.warning('recover.error', extra=extra)
tpl = 'sentry/account/recover/index.html'
context = {'form': form}
return render_to_response(tpl, context, request)
示例8: should_notify
def should_notify(self, group, event):
if group.is_muted():
return False
project = group.project
rate_limited = ratelimiter.is_limited(
project=project,
key=self.get_conf_key(),
limit=10,
)
if rate_limited:
self.logger.info('notification.rate_limited', extra={'project_id': project.id})
return not rate_limited
示例9: should_notify
def should_notify(self, group, event):
if group.is_muted():
return False
project = group.project
rate_limited = ratelimiter.is_limited(
project=project,
key=self.get_conf_key(),
limit=10,
)
if rate_limited:
logger = logging.getLogger('sentry.plugins.{0}'.format(self.get_conf_key()))
logger.info('Notification for project %s dropped due to rate limiting', project.id)
return not rate_limited
示例10: post
def post(self, request, user):
"""
Sends a confirmation email to user
``````````````````````````````````
:auth required:
"""
from sentry.app import ratelimiter
if ratelimiter.is_limited(
'auth:confirm-email:{}'.format(user.id),
limit=10,
window=60, # 10 per minute should be enough for anyone
):
return self.respond({'detail': 'You have made too many email confirmation requests. Please try again later.', },
status=status.HTTP_429_TOO_MANY_REQUESTS)
serializer = EmailSerializer(data=request.DATA)
if not serializer.is_valid():
return InvalidEmailResponse()
# If email is specified then try to only send one confirmation email
try:
email_to_send = UserEmail.objects.get(
user=user, email=serializer.object['email'].lower().strip())
except UserEmail.DoesNotExist:
return InvalidEmailResponse()
else:
if email_to_send.is_verified:
return self.respond({'detail': 'Email is already verified'},
status=status.HTTP_400_BAD_REQUEST)
user.send_confirm_email_singular(email_to_send)
logger.info(
'user.email.start_confirm',
extra={
'user_id': user.id,
'ip_address': request.META['REMOTE_ADDR'],
'email': email_to_send,
}
)
return self.respond(status=status.HTTP_204_NO_CONTENT)
示例11: should_notify
def should_notify(self, group, event):
if group.is_muted():
return False
project = group.project
send_to = self.get_sendable_users(project)
if not send_to:
return False
rate_limited = ratelimiter.is_limited(
project=project,
key=self.get_conf_key(),
limit=15,
)
if rate_limited:
logger = logging.getLogger('sentry.plugins.{0}'.format(self.get_conf_key()))
logger.info('Notification dropped due to rate limiting')
return not rate_limited
示例12: __is_rate_limited
def __is_rate_limited(self, group, event):
return ratelimiter.is_limited(
project=group.project,
key=self.get_conf_key(),
limit=10,
)
示例13: post
def post(self, request):
"""
Create a New Organization
`````````````````````````
Create a new organization owned by the request's user. To create
an organization only the name is required.
:param string name: the human readable name for the new organization.
:param string slug: the unique URL slug for this organization. If
this is not provided a slug is automatically
generated based on the name.
:param bool agreeTerms: a boolean signaling you agree to the applicable
terms of service and privacy policy.
:auth: required, user-context-needed
"""
if not request.user.is_authenticated():
return Response({'detail': 'This endpoint requires user info'}, status=401)
if not features.has('organizations:create', actor=request.user):
return Response(
{
'detail': 'Organizations are not allowed to be created by this user.'
}, status=401
)
limit = options.get('api.rate-limit.org-create')
if limit and ratelimiter.is_limited(
u'org-create:{}'.format(request.user.id),
limit=limit,
window=3600,
):
return Response(
{
'detail': 'You are attempting to create too many organizations too quickly.'
},
status=429
)
serializer = OrganizationSerializer(data=request.DATA)
if serializer.is_valid():
result = serializer.object
try:
with transaction.atomic():
org = Organization.objects.create(
name=result['name'],
slug=result.get('slug'),
)
om = OrganizationMember.objects.create(
organization=org,
user=request.user,
role=roles.get_top_dog().id,
)
if result.get('defaultTeam'):
team = org.team_set.create(
name=org.name,
)
OrganizationMemberTeam.objects.create(
team=team, organizationmember=om, is_active=True
)
self.create_audit_entry(
request=request,
organization=org,
target_object=org.id,
event=AuditLogEntryEvent.ORG_ADD,
data=org.get_audit_log_data(),
)
analytics.record(
'organization.created',
org,
actor_id=request.user.id if request.user.is_authenticated() else None
)
except IntegrityError:
return Response(
{
'detail': 'An organization with this slug already exists.'
},
status=409,
)
# failure on sending this signal is acceptable
if result.get('agreeTerms'):
terms_accepted.send_robust(
user=request.user,
organization=org,
ip_address=request.META['REMOTE_ADDR'],
sender=type(self),
)
return Response(serialize(org, request.user), status=201)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例14: handle_basic_auth
def handle_basic_auth(self, request, organization=None, *args, **kwargs):
can_register = self.can_register(
request, organization=organization, *args, **kwargs)
op = request.POST.get('op')
# Detect that we are on the register page by url /register/ and
# then activate the register tab by default.
if not op and '/register' in request.path_info and can_register:
op = 'register'
login_form = self.get_login_form(request)
if can_register:
register_form = self.get_register_form(
request, initial={
'username': request.session.get('invite_email', '')}
)
else:
register_form = None
if can_register and register_form.is_valid():
user = register_form.save()
user.send_confirm_emails(is_new_user=True)
# HACK: grab whatever the first backend is and assume it works
user.backend = settings.AUTHENTICATION_BACKENDS[0]
auth.login(
request,
user,
organization_id=organization.id if organization else None,
)
# can_register should only allow a single registration
request.session.pop('can_register', None)
request.session.pop('invite_email', None)
return self.redirect(auth.get_login_redirect(request))
elif request.method == 'POST':
from sentry.app import ratelimiter
from sentry.utils.hashlib import md5_text
login_attempt = op == 'login' and request.POST.get('username'
) and request.POST.get('password')
if login_attempt and ratelimiter.is_limited(
u'auth:login:username:{}'.
format(md5_text(request.POST['username'].lower()).hexdigest()),
limit=10,
window=60, # 10 per minute should be enough for anyone
):
login_form.errors['__all__'] = [
u'You have made too many login attempts. Please try again later.'
]
elif login_form.is_valid():
user = login_form.get_user()
auth.login(
request,
user,
organization_id=organization.id if organization else None,
)
if not user.is_active:
return self.redirect(reverse('sentry-reactivate-account'))
return self.redirect(auth.get_login_redirect(request))
context = {
'op': op or 'login',
'server_hostname': get_server_hostname(),
'login_form': login_form,
'organization': organization,
'register_form': register_form,
'CAN_REGISTER': can_register,
}
return self.respond_login(request, context, organization=organization, *args, **kwargs)
示例15: post_process
def post_process(self, event, **kwargs):
token = self.get_option('token', event.project)
index = self.get_option('index', event.project)
instance = self.get_option('instance', event.project)
if not (token and index and instance):
metrics.incr('integrations.splunk.forward-event.unconfigured', tags={
'project_id': event.project_id,
'organization_id': event.project.organization_id,
'event_type': event.get_event_type(),
})
return
if not instance.endswith('/services/collector'):
instance = instance.rstrip('/') + '/services/collector'
source = self.get_option('source', event.project) or 'sentry'
rl_key = 'splunk:{}'.format(md5_text(token).hexdigest())
# limit splunk to 50 requests/second
if ratelimiter.is_limited(rl_key, limit=1000, window=1):
metrics.incr('integrations.splunk.forward-event.rate-limited', tags={
'project_id': event.project_id,
'organization_id': event.project.organization_id,
'event_type': event.get_event_type(),
})
return
payload = {
'time': int(event.datetime.strftime('%s')),
'source': source,
'index': index,
'event': self.get_event_payload(event),
}
host = self.get_host_for_splunk(event)
if host:
payload['host'] = host
session = http.build_session()
try:
# https://docs.splunk.com/Documentation/Splunk/7.2.3/Data/TroubleshootHTTPEventCollector
resp = session.post(
instance,
json=payload,
# Splunk cloud instances certifcates dont play nicely
verify=False,
headers={
'Authorization': 'Splunk {}'.format(token)
},
timeout=5,
)
if resp.status_code != 200:
raise SplunkError.from_response(resp)
except Exception as exc:
metrics.incr('integrations.splunk.forward-event.error', tags={
'project_id': event.project_id,
'organization_id': event.project.organization_id,
'event_type': event.get_event_type(),
'error_code': getattr(exc, 'code', None),
})
raise
metrics.incr('integrations.splunk.forward-event.success', tags={
'project_id': event.project_id,
'organization_id': event.project.organization_id,
'event_type': event.get_event_type(),
})