def test_adzerk_returns_none_sponsored(self): self.populate_es() signer = TimestampSigner() with mock.patch('olympia.shelves.views.get_addons_from_adzerk') as get: get.return_value = { str(self.sponsored_ext.id): { 'impression': '123456', 'click': 'abcdef'}, str(self.sponsored_theme.id): { 'impression': '012345', 'click': 'bcdefg'}, str(self.verified_ext.id): { 'impression': '55656', 'click': 'efef'}, str(self.not_promoted.id): { 'impression': '735754', 'click': 'jydh'}, '0': { 'impression': '', 'click': ''}, } data = self.perform_search() get.assert_called_with(6) # non sponsored are ignored assert data['count'] == 2 assert len(data['results']) == 2 assert data['impression_data'] == signer.sign('123456,012345') assert {(itm['id'], itm['click_data']) for itm in data['results']} == { (self.sponsored_ext.pk, signer.sign('abcdef')), (self.sponsored_theme.pk, signer.sign('bcdefg')), }
def test_impression_endpoint(self, ping_mock): url = reverse_ns('sponsored-shelf-impression') # no data response = self.client.post(url) assert response.status_code == 400, response.content ping_mock.assert_not_called() # bad data response = self.client.post(url, {'impression_data': 'dfdfd:3434'}) assert response.status_code == 400 ping_mock.assert_not_called() # good data signer = TimestampSigner() impressions = ['i.gif?e=assfsf', 'i.gif?e=fwafsf'] data = signer.sign(','.join(impressions)) response = self.client.post(url, {'impression_data': data}) assert response.status_code == 202 ping_mock.assert_has_calls([ mock.call( f'https://e-10521.adzerk.net/{im}', type='impression') for im in impressions]) assert response.content == b'' # good data but stale ping_mock.reset_mock() with freeze_time('2020-01-01') as freezer: data = signer.sign(','.join(impressions)) freezer.tick(delta=timedelta(seconds=61)) response = self.client.post(url, {'impression_data': data}) assert response.status_code == 400 ping_mock.assert_not_called()
def test_click_endpoint(self, ping_mock): url = reverse_ns('sponsored-shelf-click') # no data response = self.client.post(url) assert response.status_code == 400 ping_mock.assert_not_called() # bad data response = self.client.post(url, {'click_data': 'r?dfdfd:3434'}) assert response.status_code == 400 ping_mock.assert_not_called() # good data signer = TimestampSigner() click = 'sdwwdw' data = signer.sign(click) response = self.client.post(url, {'click_data': data}) assert response.status_code == 202, response.content ping_mock.assert_called_with( f'https://e-10521.adzerk.net/{click}', type='click') assert response.content == b'' # good data but stale ping_mock.reset_mock() with freeze_time('2020-01-01') as freezer: data = signer.sign(click) freezer.tick(delta=timedelta(days=1, minutes=1)) response = self.client.post(url, {'click_data': data}) assert response.status_code == 400 ping_mock.assert_not_called()
def test_adzerk_returns_none_sponsored(self): self.populate_es() signer = TimestampSigner() log_msg = ( 'Addon id [%s] returned from Adzerk, but not in a valid Promoted ' 'group [%s]') log_groups = 'Sponsored; Verified; By Firefox' with mock.patch('olympia.shelves.views.get_addons_from_adzerk') as get: get.return_value = { str(self.sponsored_ext.id): { 'impression': '123456', 'click': 'abcdef' }, str(self.sponsored_theme.id): { 'impression': '012345', 'click': 'bcdefg', }, str(self.verified_ext.id): { 'impression': '55656', 'click': 'efef' }, str(self.recommended_ext.id): { 'impression': '9494', 'click': '4839' }, str(self.not_promoted.id): { 'impression': '735754', 'click': 'jydh' }, '0': { 'impression': '', 'click': '' }, } with mock.patch('django_statsd.clients.statsd.incr') as incr_mock: with mock.patch('olympia.shelves.views.log.error') as log_mock: data = self.perform_search() incr_mock.assert_any_call('services.adzerk.elasticsearch_miss', 3) log_mock.assert_has_calls(( mock.call(log_msg, str(self.recommended_ext.id), log_groups), mock.call(log_msg, str(self.not_promoted.id), log_groups), mock.call(log_msg, '0', log_groups), )) get.assert_called_with(6) # non .can_be_returned_from_azerk are ignored assert data['count'] == 3 assert len(data['results']) == 3 assert data['impression_data'] == signer.sign('123456,012345,55656') assert {(itm['id'], itm['click_data']) for itm in data['results']} == { (self.sponsored_ext.pk, signer.sign('abcdef')), (self.sponsored_theme.pk, signer.sign('bcdefg')), (self.verified_ext.pk, signer.sign('efef')), }
def dumps_qs_query(query): serialized_str = base64.b64encode(zlib.compress( pickle.dumps(query))).decode() signer = TimestampSigner() signed_data = signer.sign(serialized_str) payload = {'data': signed_data} return mark_safe(json.dumps(payload))
def provision(self, prefix="", user=None): nonce = self.random_nonce(prefix) user_id = user.pk if user else "" payload = "%s:%s" % (nonce, user_id) signer = TimestampSigner() return signer.sign(payload)
def post(self, request, *args, **kwargs): try: data = confirm(request) except PaymentError as e: messages.error(self.request, str(e)) self.restore_frozen_basket() logger.exception(e) return TemplateResponse(request, 'worldpay/worldpay_response.html', {'url': self.request.build_absolute_uri(reverse("worldpay-fail") + "?error=%s" % str(e))}) basket = Basket.objects.get(pk=data['M_basket']) basket.strategy = Selector().strategy() if data['M_user'] == 'None': user = AnonymousUser() else: user = User.objects.get(pk=data['M_user']) # Fetch submission data out of session order_number = data['cartId'] total = Decimal(data['amount']) # Record payment source source_type, is_created = SourceType.objects.get_or_create(name='WorldPay') source = Source(source_type=source_type, currency=data['currency'], amount_allocated=total, amount_debited=total, reference=data['transId']) self.add_payment_source(source) self.add_payment_event('paid', total, reference=data['transId']) shipping_address = ShippingAddress.objects.get(pk=data['M_shipping_address']) if data['M_billing_address'] == 'None': billing_address = None else: billing_address = BillingAddress.objects.get(pk=data['M_billing_address']) shipping_methods = Repository().get_shipping_methods(basket, user=user, shipping_addr=shipping_address) shipping_method = [method for method in shipping_methods if method.code == data['M_shipping_method']][0] order_kwargs = json.loads(data['M_order_kwargs']) # Place order calc_total = self.get_order_totals(basket, shipping_method.calculate(basket)) self.handle_order_placement( order_number, user, basket, shipping_address, shipping_method, shipping_method.calculate(basket), billing_address, calc_total, **order_kwargs ) signer = TimestampSigner() order_number = signer.sign(order_number) success_url = self.request.build_absolute_uri(reverse("worldpay-success") + '?order_number=%s' % (order_number)) return TemplateResponse(request, 'worldpay/worldpay_response.html', {'url': success_url})
def check_email(request): """Function""" email = request.POST.get('email') if User.objects.filter(email__iexact=email).exists(): msg = u"이미 존재하는 이메일 주소입니다. 비밀번호 찾기를 이용해 보세요." data = { 'msg': msg, } return JsonResponse(data, status=201) signer = TimestampSigner() value = signer.sign(email) subject = u'[노룩뉴스] 회원가입 인증 메일입니다.' body = u'인증코드(이메일주소 포함): %s' % value try: send_mail(subject, body, settings.EMAIL_HOST_USER, [email], fail_silently=False) msg = u"인증코드를 이메일로 발송했습니다." data = { 'msg': msg, } return JsonResponse(data, status=201) except SMTPException: return JsonResponse({'status': 'false'}, status=400)
def task(request, task_id): task = get_object_or_404(Task.objects.select_related('task_group', 'tg_set'), id=task_id) role = task.task_group.check_membership(request.user) if role == 'user' and not task.published: raise Http404('Task not found') submissions = Submission.objects.filter(user=request.user, task_id=task_id) context = { 'title': task.name, 'task': task, 'group': task.task_group, 'submissions': submissions, 'evaluations': {}, 'tokens': {}, 'limits': task.get_user_limits(request.user.id), 'deadline': task.get_deadline_data() } evaluations = SubmissionEvaluation.objects.filter(submission__uuid__in=[sbm.uuid for sbm in submissions]) signer = TimestampSigner() for submission in submissions: context['tokens'][submission.uuid] = signer.sign(submission.uuid) for evaluation in evaluations: context['evaluations'][evaluation.submission_id] = evaluation return render(request, 'webapp/task.html', context)
def gen_token(self): ''' 生成接口认证的token ''' signer = TimestampSigner() token = signer.sign(self.id) return token
def test_basic(self): self.populate_es() signer = TimestampSigner() with mock.patch('olympia.shelves.views.get_addons_from_adzerk') as get: get.return_value = { str(self.sponsored_ext.id): { 'impression': '123456', 'click': 'abcdef', 'conversion': 'ddfdfdf', }, str(self.sponsored_theme.id): { 'impression': '012345', 'click': 'bcdefg', 'conversion': 'eeer', }, } data = self.perform_search() get.assert_called_with(6), get.call_args assert data['count'] == 2 assert len(data['results']) == 2 assert data['impression_data'] == signer.sign('123456,012345') assert {itm['id'] for itm in data['results']} == { self.sponsored_ext.pk, self.sponsored_theme.pk, }
def get_download_url_temp(self, obj): signer = TimestampSigner() value = signer.sign(obj.pid) relative_url = reverse("api_temp_download_url", kwargs={"spid": value}) return f"{getattr(settings, 'FTL_ONLY_OFFICE_INTERNAL_DOWNLOAD_SERVER_URL', '')}{relative_url}"
def send_all_emails(request): all_faculty = Faculty.objects.all() signer = TimestampSigner() msgs = [] subject = "Scheduled email" for faculty in all_faculty: token = signer.sign(slugify(faculty.name + '_' + str(faculty.pk))) name, token = token.split(':', 1) url = reverse('faculty_schedule', kwargs={ 'name': name, 'token': token }) body = """ Update your free schedule for the current week. %s The above link will be valid for next 5 days. Regards digiVIT team """ % (request.build_absolute_uri(url)) msg = (subject, body, '*****@*****.**', [faculty.email]) msgs.append(msg) send_mass_mail(msgs) messages.add_message(request, messages.SUCCESS, "Emails sent successfully!") return redirect(reverse('home'))
def provision(self, prefix='', user=None): nonce = self.random_nonce(prefix) user_id = user.pk if user else '' payload = '%s:%s' % (nonce, user_id) signer = TimestampSigner() return signer.sign(payload)
def get_verification_code(request): """API get_verification_code""" email = request.POST.get('email') if User.objects.filter(email__iexact=email).exists(): msg = _('E-mail exists. Why don\'t you try to find your password?') data = { 'result': False, 'msg': msg, } return JsonResponse(data, status=201) signer = TimestampSigner() value = signer.sign(email) subject = _('[%(site_name)s] Verification code for signing in') % { 'site_name': settings.SITE_NAME } body = value try: send_mail(subject, body, settings.EMAIL_HOST_USER, [email], fail_silently=False) msg = _('Verification code sent. Please check your E-mail.') data = { 'result': True, 'msg': msg, } return JsonResponse(data, status=201) except SMTPException: return JsonResponse({'status': 'false'}, status=400)
def _build_hook_signature(self, method, url, body): signer = TimestampSigner(settings.WATERCOOLER_SECRET) value = '{method}:{url}:{body}'.format(method=method.lower(), url=url, body=hashlib.sha256( body or b'').hexdigest()) return signer.sign(value)
def index(request): error_message = None reset_request = ResetRequestForm(request.POST or None) email_response = False try: if reset_request.is_valid(): if reset_request.cleaned_data['email'] != '': user_data = ContactInformation.objects.get(alternate_email=reset_request.cleaned_data['email']) email_response = True else: user_data = ContactInformation.objects.get(cell_phone=reset_request.cleaned_data['cell']) signer = TimestampSigner() token = signer.sign(user_data.psu_uuid) if email_response == True: password_reset_email(user_data.psu_uuid, user_data.alternate_email, token) else: shortcode = TextMessageShortCode() shortcode.token = token shortcode.save() password_reset_sms(user_data.cell_phone, shortcode.code) return HttpResponseRedirect(reverse("PasswordReset:reset_notoken")) except (ContactInformation.DoesNotExist, ContactInformation.MultipleObjectsReturned): # Either we couldn't find it or we couldn't uniquely identify it. logger.info("service=myinfo email=" + reset_request.cleaned_data['email'] + " cell=" + reset_request.cleaned_data['cell'] + "error = \"Unable to identify.\"") error_message = "We were unable to find an identity that matched your information." return render(request, 'PasswordReset/index.html', {'form' : reset_request, 'error' : error_message,})
def index(request): limited = getattr(request, 'limited', False) if limited: return HttpResponseRedirect(reverse('rate_limited')) error_message = None reset_request = ResetRequestForm(request.POST or None) email_response = False try: if reset_request.is_valid(): if reset_request.cleaned_data['email'] != '': user_data = ContactInformation.objects.get(alternate_email=reset_request.cleaned_data['email']) email_response = True else: user_data = ContactInformation.objects.get(cell_phone=reset_request.cleaned_data['cell']) signer = TimestampSigner() token = signer.sign(user_data.psu_uuid) if email_response is True: r = password_reset_email(user_data.psu_uuid, user_data.alternate_email, token) else: short_code = TextMessageShortCode() short_code.token = token short_code.save() r = password_reset_sms(user_data.cell_phone, short_code.code) if r is not True: raise APIException("Reset code not sent. Email? " + str(email_response)) logger.info( "service=myinfo page=passwordreset action=reset_request status=success email={0} cell={1}".format( reset_request.cleaned_data['email'], reset_request.cleaned_data['cell'])) return HttpResponseRedirect(reverse("PasswordReset:reset_notoken")) except (ContactInformation.DoesNotExist, ContactInformation.MultipleObjectsReturned) as e: # Either we couldn't find it or we couldn't uniquely identify it. if isinstance(e, ContactInformation.DoesNotExist): status = "id_not_found" else: status = "multiple_matches" logger.info( "service=myinfo page=passwordreset action=reset_request status={0} email={1} cell={2}".format( status, reset_request.cleaned_data['email'], reset_request.cleaned_data['cell'])) error_message = ("We could not uniquely identify a user with this information. " "Ensure this information is correct and please try again. " "If you continue to have difficulty, contact the Helpdesk (503-725-4357) for assistance.") except APIException: logger.info( "service=myinfo page=passwordreset action=reset_request status=code_not_sent email={0} cell={1}".format( reset_request.cleaned_data['email'], reset_request.cleaned_data['cell'])) error_message = "Sorry, we were unable to send a reset code. Please try again later." return render(request, 'PasswordReset/index.html', {'form': reset_request, 'error': error_message, })
def send_restore_password(self): signer = TimestampSigner() value = signer.sign(self.user.username) x = value.index(':') key = value[x+1:] self.password_restore_key = key self.save() sender = '*****@*****.**' msg = {} msg['subject'] = 'Восстановление пароля' magic_url = 'http://draftwatcher.pythonanywhere.com/' msg['body'] = ''' Вы запросили восстановление пароля. Если Вы хотите сбросить пароль, перейдите по ссылке: {url}. Ссылка будет активна в течение пяти минут. Если вы не иницировали отправление этого сообщения, просто проигнорируйте его. '''.format( url=''.join( (magic_url,'restore_password/', key))) send_mail(msg['subject'], msg['body'], sender, [self.user.email], fail_silently=False) return key
def generate_activation_code(self): email = self.player.email if self.player else self.placeholder.first().email value = '{0}:{1}'.format(email, self.team.name) signer = TimestampSigner() self.activation_code = signer.sign(value) self.save() return self.activation_code
def microsoft(request): """ Adds global template variables for microsoft_auth """ login_type = None if config.MICROSOFT_AUTH_LOGIN_TYPE == LOGIN_TYPE_XBL: login_type = _("Xbox Live") else: login_type = _("Microsoft") if config.DEBUG: # pragma: no branch expected_domain = Site.objects.get_current().domain current_domain = request.get_host() if expected_domain != current_domain: # pragma: no branch logger.warning( "\nWARNING:\nThe domain configured for the sites framework " "does not match the domain you are accessing Django with. " "Microsoft authentication may not work.\n") do_warning = get_scheme( request) == "http" and not current_domain.startswith("localhost") if do_warning: # pragma: no branch logger.warning( "\nWARNING:\nYou are not using HTTPS. Microsoft " "authentication only works over HTTPS unless the hostname for " "your `redirect_uri` is `localhost`\n") # initialize Microsoft client using CSRF token as state variable signer = TimestampSigner() state = signer.sign(get_token(request)) microsoft = MicrosoftClient(state=state, request=request) auth_url = microsoft.authorization_url()[0] return { "microsoft_login_enabled": config.MICROSOFT_AUTH_LOGIN_ENABLED, "microsoft_authorization_url": mark_safe(auth_url), "microsoft_login_type_text": login_type, }
def notify_survey(survey_tracker, request): if survey_tracker.intern_info: name = survey_tracker.intern_info.applicant.applicant.public_name email = survey_tracker.intern_info.applicant.applicant.email_address() community = survey_tracker.intern_info.project.project_round.community.name internstarts = survey_tracker.intern_info.project.project_round.participating_round.internstarts internends = survey_tracker.intern_info.project.project_round.participating_round.internends elif survey_tracker.alumni_info: name = survey_tracker.alumni_info.name email = Address(name, addr_spec=survey_tracker.alumni_info.email) community = survey_tracker.alumni_info.community internstarts = survey_tracker.alumni_info.page.round_start internends = survey_tracker.alumni_info.page.round_end else: return signer = TimestampSigner() token = signer.sign(survey_tracker.pk) send_group_template_mail('home/email/alum_survey.txt', { 'name': name, 'email': email, 'community': community, 'internstarts': internstarts, 'internends': internends, 'token': token, }, request=request, recipient_list=[email])
def handle_accounts_reigster(msg): """ 处理用户点击注册/绑定的事件""" open_id = msg['FromUserName'] we_user = WeProfile.objects.get(open_id=open_id) signer = TimestampSigner() encrypt_id = base64.b64encode(signer.sign(open_id)) return response_text_msg(msg, u'欢迎光临')
def _build_hook_signature(self, method, url, body): signer = TimestampSigner(settings.WATERCOOLER_SECRET) value = '{method}:{url}:{body}'.format( method=method.lower(), url=url, body=hashlib.sha256(body or b'').hexdigest() ) return signer.sign(value)
def get_signed_impression_blob_from_results(adzerk_results): impressions = [ result.get('impression') for result in adzerk_results.values() if result.get('impression')] if not impressions: return None signer = TimestampSigner() return signer.sign(','.join(impressions))
def get_authentication_url(self, next=None): signer = TimestampSigner() return build_absolute_url( reverse('users-authenticate'), parse.urlencode({ 'sig': signer.sign(self.email), 'next': next or '', }))
def accountkitheadjs(): signer = TimestampSigner() state = signer.sign(accountkit_app_id) html = ''' <!-- HTTPS required. HTTP will give a 403 forbidden response --> <script src="https://sdk.accountkit.com/{}/sdk.js"></script> '''.format(accountkit_language_code) return mark_safe(html)
def get_grade_token(self, request, pk): from django.core.signing import TimestampSigner signer = TimestampSigner(salt=str(pk)) from datetime import datetime, timedelta import json, base64 expire_time = datetime.now() + timedelta(days=7) d = dict(exam=pk, expire=expire_time.isoformat()) token = signer.sign(base64.b64encode(json.dumps(d))) return response.Response(dict(token=token))
def setUp(self): super().setUp() self.channel = Channel(project=self.project, kind="email") self.channel.value = "*****@*****.**" self.channel.save() signer = TimestampSigner(salt="alerts") signed_token = signer.sign(self.channel.make_token()) self.url = f"/integrations/{self.channel.code}/unsub/{signed_token}/"
def generate_api_token(user, expiry_seconds=EXPIRY_SECONDS): signer = TimestampSigner() token = signer.sign(user.username) api_token = ApiToken(user=user, expiry_seconds=expiry_seconds, token=token) api_token.save() return api_token
class TestWelcomeCommenter(GitmateTestCase): def setUp(self): self.signer = TimestampSigner() super().setUpWithPlugin('welcome_commenter') @patch.object(GitHubMergeRequest, 'add_comment') def test_github(self, mock_add_comment): data = { 'repository': { 'full_name': environ['GITHUB_TEST_REPO'], 'id': 49558751 }, 'pull_request': { 'number': 7 }, 'action': 'opened' } response = self.simulate_github_webhook_call('pull_request', data) self.assertEqual(response.status_code, status.HTTP_200_OK) sign = self.signer.sign('') msg = ('\n\n(Powered by [GitMate.io](https://gitmate.io))\n\n' '<!-- Timestamp signature `{}` -->'.format(sign)) mock_add_comment.assert_called_once_with(msg) @patch.object(GitLabMergeRequest, 'add_comment') def test_gitlab(self, mock_add_comment): data = { 'object_attributes': { 'target': { 'path_with_namespace': environ['GITLAB_TEST_REPO'] }, 'action': 'open', 'iid': 2 } } response = self.simulate_gitlab_webhook_call('Merge Request Hook', data) self.assertEqual(response.status_code, status.HTTP_200_OK) sign = self.signer.sign('') msg = ('\n\n(Powered by [GitMate.io](https://gitmate.io))\n\n' '<!-- Timestamp signature `{}` -->'.format(sign)) mock_add_comment.assert_called_once_with(msg)
def timestampsigner_test(): from django.core.signing import TimestampSigner signer = TimestampSigner() value = signer.sign('hello') print(value) original = signer.unsign(value) print(original) original = signer.unsign(value, max_age=10) print(original)
def setUp(self): self.user_details_record = mock_identity_record self.nanny_application_record = mock_nanny_application self.personal_details_record = mock_personal_details_record signer = TimestampSigner() signed_email = signer.sign('*****@*****.**') self.client.cookies = SimpleCookie({'_ofs': signed_email})
def test_send_event_ping(incr_mock): click = r'r%3Fe%3DeyJ2IjLtg%26Bug' responses.add(responses.GET, settings.ADZERK_EVENT_URL + 'r?e=eyJ2IjLtg&Bug') signer = TimestampSigner() send_event_ping(signer.sign(click), 'foo') incr_mock.assert_called_with('services.adzerk.foo.success') assert responses.calls[0].request.url == (settings.ADZERK_EVENT_URL + 'r?e=eyJ2IjLtg&Bug')
def test_fresh_signature_does_not_autosubmit(self): signer = TimestampSigner(salt="alerts") signed_token = signer.sign(self.channel.make_token()) url = "/integrations/%s/unsub/%s/" % (self.channel.code, signed_token) r = self.client.get(url) self.assertContains(r, "Please press the button below to unsubscribe", status_code=200) self.assertNotContains(r, "submit()", status_code=200)
def save(self, *args, **kwargs): # COLOCAR AQUI CONSUMIR EL REST DE ORGANIGRAMA # Envio un uid y me devuelve el uid del jefe, si este esta inactivo me devuelve la del superior self.jefe = User.objects.get(pk=1) # Crear un Token Para confirmacion de Permiso mediante correo, por temas de la url cambio el separador por - from django.core.signing import TimestampSigner signer = TimestampSigner(salt="4g3t1c") self.token_mail = signer.sign(self.pk) super(DesignacionPermiso, self).save(*args, **kwargs)
def form_valid(self, form): ''' ''' user = get_object_or_404(UserProfile, username=form.cleaned_data['username']) signer = TimestampSigner() recovery_key = signer.sign(str(user)) self.send_recovery_mail(user) messages.success(self.request, _('An email has been sent to your email account.')) response = super(PasswordRecovery, self).form_valid(form) response.set_signed_cookie('recovery_key', recovery_key, max_age=1200) return response
def get_links(self, obj): request = self.context['request'] signer = TimestampSigner(settings.WEBSOCKET_SECRET) channel = signer.sign(obj.pk) return { 'self': reverse('sprint-detail', kwargs={'pk': obj.pk}, request=request), 'tasks': reverse('task-list', request=request) + '?sprint={}'.format(obj.pk), 'channel': '{proto}://{server}/socket?channel={channel}'.format( proto='wss' if settings.WEBSOCKET_SECURE else 'ws', server=settings.WEBSOCKET_SERVER, channel=channel), }
def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) signer = TimestampSigner(settings.SOCKET_SECRET) channel = signer.sign(1) # el 1 deberia ser el ID de la empresa url = '{protocol}://{server}/socket?channel={channel}'.format( protocol = 'wss' if settings.SOCKET_SECURE else 'ws', server = settings.SOCKET_SERVER, channel = channel ) context.update(socket_url=url) return context
def authorise(request): client_id = request.GET.get("client_id", None) state = request.GET.get("state", None) if not (client_id and state): response = PrettyJsonResponse({ "ok": False, "error": "incorrect parameters supplied" }) response.status_code = 400 return response try: # We only allow the process to happen if the app exists and has not # been flagged as deleted app = App.objects.filter(client_id=client_id, deleted=False)[0] except IndexError: response = PrettyJsonResponse({ "ok": False, "error": "App does not exist for client id" }) response.status_code = 400 return response if app.callback_url is None or app.callback_url.strip() == "": response = PrettyJsonResponse({ "ok": False, "error": ("This app does not have a callback URL set. " "If you are the developer of this app, " "please ensure you have set a valid callback " "URL for your application in the Dashboard. " "If you are a user, please contact the app's " "developer to rectify this.") }) response.status_code = 400 return response # Sign the app and state pair before heading to Shibboleth to help protect # against CSRF and XSS attacks signer = TimestampSigner() data = app.client_id + state signed_data = signer.sign(data) # Build Shibboleth callback URL url = os.environ.get("SHIBBOLETH_ROOT") + "/Login?target=" target = request.build_absolute_uri( "/oauth/shibcallback?appdata={}".format(signed_data)) target = quote(target) url += target # Send the user to Shibboleth to log in return redirect(url)
def get_links(self, obj): request = self.context["request"] signer = TimestampSigner(settings.WATERCOOLER_SECRET) channel = signer.sign(obj.pk) return { "self": reverse("sprint-detail", kwargs={"pk": obj.pk}, request=request), "tasks": reverse("task-list", request=request) + "?sprint={}".format(obj.pk), "channel": "{proto}://{server}/socket?channel={channel}".format( proto="wss" if settings.WATERCOOLER_SECURE else "ws", server=settings.WATERCOOLER_SERVER, channel=channel, ), }
def get_absolute_file_url(self, authenticated=False): if not self.name: return '' url = reverse('foirequest-auth_message_attachment', kwargs={ 'message_id': self.belongs_to_id, 'attachment_name': self.name }) if settings.FOI_MEDIA_TOKENS and authenticated: signer = TimestampSigner() value = signer.sign(url).split(':', 1)[1] return '%s?token=%s' % (url, value) return url
def send_password_reset_email(self, request, user): signer = TimestampSigner() reset_token = signer.sign(user.get_username()) context = { "request": request, "user": user, "project_name": get_configuration("QS_PROJECT_NAME"), "project_url": get_configuration("QS_PROJECT_URL"), "reset_token": reset_token, } mails = template_mail.MagicMailBuilder() email = mails.password_reset(user, context) email.send()
def send_activation_email(self, request, user): signer = TimestampSigner() context = { 'request': request, 'user': user, 'activation_key': signer.sign(user.get_username()), 'project_name': get_configuration("QS_PROJECT_NAME"), 'project_url': get_configuration("QS_PROJECT_URL"), 'expiration_days': get_configuration("QS_SIGNUP_TOKEN_EXPIRATION_DAYS"), } mails = template_mail.MagicMailBuilder() email = mails.activation(user, context) email.send()
def handle(self, *args, **options): """ With no arguments, find the first user in the system with the is_superuser or is_staff flag set to true, or just the first user in the system period. With a single argument, look for the user with that value as the USERNAME_FIELD value. When a user is found, print out a URL slug you can paste into your browser to login as the user. """ user_model = get_user_model() if len(args) == 0: # find the first superuser, or staff member or user filters = [{"is_superuser": True}, {"is_staff": True}, {}] user = None for f in filters: try: user = user_model._default_manager.filter(**f).order_by("pk").first() if user: break except FieldError as e: pass if user is None: raise CommandError("No users found!") elif len(args) == 1: # find the user with the email field or USERNAME_FIELD equal to the command line # argument key = args[0] user = user_model._default_manager.filter(email=key).order_by("-is_active").first() if not user: try: user = user_model._default_manager.get_by_natural_key(key) except user_model.DoesNotExist as e: raise CommandError("The user does not exist") else: raise CommandError("You passed me too many arguments") signer = TimestampSigner() signature = signer.sign(str(user.pk)) self.stdout.write(reverse(login, args=(signature,)))
def new_temporary_file(filename, mimetype, prefix=''): dir = secure_join(settings.MEDIA_ROOT, 'temporary') if not os.path.exists(dir): os.makedirs(dir) f = NamedTemporaryFile( mode='wb', prefix=prefix, suffix=os.path.splitext(filename)[1], delete=False, dir=dir) CleanupTemporary().apply_async((f.name,), countdown=TEMPORARY_FILE_TTL) signer = TimestampSigner(sep=':') url = reverse('filesystem-temporary-download', kwargs={ 'token': signer.sign(b64_encode('%s,%s,%s' % (os.path.basename(f.name), filename, mimetype))), 'filename': filename, }) return f, url
def send_password_reset (self, request, **kwargs): kwargs.setdefault("subject", "Reset Your Password") kwargs.setdefault("body", "You can reset your password with this link: {0}.\n\nThis link will expire in 60 minutes.") kwargs.setdefault("from", settings.SERVER_EMAIL) chars = 'abcdefghijklmnopqrstuvwxyz' signer = TimestampSigner() password_reset = get_random_string(50, chars) self.password_reset = signer.sign(password_reset) self.save() logger.info(self.password_reset) reset_url = request.build_absolute_uri(reverse("sv-reset", kwargs={ "code" : self.password_reset })) subject = kwargs.get("subject") body = kwargs.get("body").format(reset_url) from_email = kwargs.get("from") to = [self.email] send_mail(subject, body, from_email, to, fail_silently=False)
class AuthKey(object): """Command authorisation key class.""" def __init__(self, value=None): """Initialise new AuthKey instance.""" self.signer = TimestampSigner(salt="auth") self._data = { 'clear': value, 'signed': self.signer.sign(value) } @property def clear(self): """Get cleartext key value.""" return self._data['clear'] @property def signed(self): """Get cyphertext key value.""" return self._data['signed'] def validate(self, key, life=None): """Validate key value.""" if not life and settings.LIFETIME: life = settings.LIFETIME try: clear = self.signer.unsign(key, max_age=life) except SignatureExpired as e: raise KeyValidityExpired("{}".format(e)) if self.clear == clear: return True else: raise KeyValueMismatchError(keyval=clear, refval=self.clear) def __str__(self): """Return string representation.""" return self.signed def __unicode__(self): """Return string representation.""" return self.__str__() # pragma: no cover
def send_activation_email(new_user, request): current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain signer = TimestampSigner(salt='account activation', sep='.') token = signer.sign(str(new_user.pk)) c = { 'user': new_user, 'email': new_user.email, 'token': token, 'domain': domain, 'site_name': site_name, 'protocol': 'https' if request.is_secure() else 'http' } subject = render_to_string("osnap/accounts/registration/email-subject.txt", c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = render_to_string("osnap/accounts/registration/email.txt", c) send_mail(subject, email, None, [new_user.email])
def linked_form_field_model(model_form, field): model_class = model_form._meta.model model_field = model_class._meta.fields_by_name[field.name] related_model = model_field.related_model # 'related_app' : related_model._meta.app_label, # 'related_class' : related_model._meta.object_name, data_url = [{ 'referencing_app' : model_class._meta.app_label, 'referencing_class' : model_class._meta.object_name, 'referencing_field' : field.name, 'referencing_instance' : model_form.instance.pk, 'current_value' : field.value() }] from fedoralink.views import ModelViewRegistry link_view = ModelViewRegistry.get_view(related_model, 'link') data_url = base64.b64encode(zlib.compress(json.dumps(data_url).encode('utf-8'))) signer = TimestampSigner(salt='linked_form_field_model') data_url = signer.sign(data_url) return reverse(link_view, kwargs={'parametry': ''}) + '?linking=' + data_url
def get_signed_link(self): signer = TimestampSigner() advert_signed = signer.sign(self.pk) return reverse('advert:go', args=[advert_signed])
def enqueue(request, task, *args, **kwargs): result = task.delay(language=get_language(), *args, **kwargs) signer = TimestampSigner(key=request.session.session_key, sep=':') return signer.sign(b64_encode(result.id))
def generate_key(user, for_subscription=True): salt = 'subscription' if for_subscription else 'unsubscription' signer = TimestampSigner(settings.SECRET_KEY, salt=salt) return signer.sign(str(user.id))
def sign_user_id(user_id): id_signer = TimestampSigner() signed = id_signer.sign(user_id) b64encoded = base64.urlsafe_b64encode(signed.encode('utf-8')) return b64encoded.decode('utf-8')
def render(self, name, value, attrs=None): signer = TimestampSigner() value = signer.sign(value) return super(SatoriSignedWidget,self).render(name, value, attrs)
def get_signed_link(self): signer = TimestampSigner() advert_signed = signer.sign(self.pk) return reverse('advertisements.views.advanced_click_register', args=[advert_signed])
def enqueue(request, task, *args, **kwargs): status = task.delay(*args, **kwargs) signer = TimestampSigner(key=request.session.session_key, sep=':') return signer.sign(b64_encode(status.id))
def reports_unsub_url(self): signer = TimestampSigner(salt="reports") signed_username = signer.sign(self.user.username) path = reverse("hc-unsubscribe-reports", args=[signed_username]) return settings.SITE_ROOT + path
def timestamped_id(self): """ Returns self.id signed using TimestampSigner. """ signer = TimestampSigner() return signer.sign(str(self.id))