def send_signoff_request(self, request: WSGIRequest):
     if self.is_signed_off or self.sent_for_signoff:
         return None
     contrib_sign_off_group_users = Group.objects.get(name="Contributions Sign Off").user_set.all()
     url_to_preview_pdf = request.build_absolute_uri(reverse("users:certificate_pdf", kwargs={"id": self.id}))
     url_to_cert_signoff_list = request.build_absolute_uri(
         reverse("admin:users_contributioncertificate_changelist") + "?is_signed_off__exact=0"
     )
     requesting_user: User = request.user
     subject = f"[INTERNAL] Contribution Certificate request from {requesting_user.name} - {requesting_user.email}"
     message = (
         f"Hi there, \n"
         f"{requesting_user.name} (member id {requesting_user.member_id}) has requested one of us to sign "
         f"off on the Contribution Certificate for {self.user.name} ({self.user.email}).\n\n"
         f"You can view the un-signed preview here: {url_to_preview_pdf}\n\n"
         f"You can view all pending Contribution Certificate Requests here: {url_to_cert_signoff_list}\n\n"
         f"You do not need to notify the user or reply to this email, they will receive an email when the signoff completes."
     )
     recipients = [u.email for u in contrib_sign_off_group_users]
     msg = EmailMultiAlternatives(
         subject=subject,
         body=message,
         from_email=settings.DEFAULT_FROM_EMAIL,
         to=recipients,
         cc=[request.user.email],
         reply_to=[request.user.email],
     )
     if not settings.DEBUG:
         msg.send()
     else:
         logger.warning(f"DID NOT SEND MESSAGE AS DEBUG MODE IS ACTIVE. Message below\n: \n{message}")
     self.sent_for_signoff = True
     self.date_sent_for_signoff = datetime.today().date()
     self.save()
Exemplo n.º 2
0
def fake_request(path='/', method='GET', user=True, extra={}):
    params = {
        'REQUEST_METHOD': method,
        'PATH_INFO': path,
        'wsgi.input': StringIO()
    }
    params.update(extra)

    req = WSGIRequest(params)

    if user:
        req.user = UserFactory.create(groups=(GroupFactory(), GroupFactory()))
    else:
        req.user = AnonymousUser()

    req.build_absolute_uri = lambda x=None: '/'

    # for sessions middleware
    req.session = build_fake_session()

    # for messages middleware
    req._messages = default_storage(req)

    req.get_host = lambda x=None: 'localhost'

    return req
Exemplo n.º 3
0
def fake_request(path='/', method='GET', user=None, extra={}):
    params = {
        'REQUEST_METHOD': method,
        'PATH_INFO': path,
        'wsgi.input': StringIO()
    }
    params.update(extra)

    req = WSGIRequest(params)

    req.user = user or AnonymousUser()
    req.user.id = ''
    req.user.username = '******'
    req.user.first_name = 'mock_user'
    req.user.is_superuser = True
    req.user.groups.all = lambda: [GroupFactory(id=1)]

    req.build_absolute_uri = lambda x=None: '/'

    # for sessions middleware
    req.session = build_fake_session()

    # for messages middleware
    req._messages = default_storage(req)

    req.get_host = lambda x=None: 'localhost'

    return req
Exemplo n.º 4
0
def render_xml(request: WSGIRequest, context: dict):
    """Returns the page context as XML."""
    xml = Element('page')
    SubElement(xml, 'link', href=request.build_absolute_uri(request.path))
    for name in context:
        if name == 'title':
            SubElement(xml, name).text = context[name]
        elif isinstance(context[name], Iterable):
            if any(isinstance(i, Feed) for i in context[name]):
                feeds = SubElement(xml, 'feeds', name=name)
                feeds.extend(
                    [feed_xml(request, feed, False) for feed in context[name]])
            elif any(isinstance(i, Item) for i in context[name]):
                items = SubElement(xml, 'items', {'name': name})
                items.extend(
                    [item_xml(request, item, False) for item in context[name]])
            elif any(isinstance(i, User) for i in context[name]):
                xml.extend(
                    [user_xml(request, user, False) for user in context[name]])
        elif isinstance(context[name], Feed):
            xml.append(feed_xml(request, context[name], True))
        elif isinstance(context[name], Item):
            xml.append(item_xml(request, context[name], True))
        elif isinstance(context[name], User):
            xml.append(user_xml(request, context[name], True))
    return HttpResponse(prettify(xml), content_type='text/xml')
Exemplo n.º 5
0
def fake_request(path='/', method='GET', user=None, extra={}):
    params = {
        'REQUEST_METHOD': method,
        'PATH_INFO': path,
        'wsgi.input': StringIO()
    }
    params.update(extra)

    req = WSGIRequest(params)

    req.user = user or AnonymousUser()
    req.user.id = ''
    req.user.username = '******'
    req.user.first_name = 'mock_user'
    req.user.is_superuser = True
    req.user.groups.all = lambda: [GroupFactory(id=1)]

    req.build_absolute_uri = lambda x=None: '/'

    # for sessions middleware
    req.session = build_fake_session()

    # for messages middleware
    req._messages = default_storage(req)

    req.get_host = lambda x=None: 'localhost'

    return req
    def sign_with_user(self, request: WSGIRequest, signing_user: User, email_user: True):
        assert signing_user.has_contrib_sign_off_permission()
        self.signed_off_by = signing_user
        self.signed_off_date = datetime.today().date()
        self.is_signed_off = True
        self.save()

        if email_user:
            url_to_signed_pdf = request.build_absolute_uri(
                reverse("users:certificate_pdf_signed", kwargs={"id": self.id})
            )
            cert_user = self.user
            subject = f"Contribution Certificate has been signed off"
            message = (
                f"Dear {cert_user.name}, \n"
                f"Your contribution certificate has been signed by {signing_user.name} ({signing_user.email}).\n\n"
                f"You can view the signed certificate here: {url_to_signed_pdf}\n\n"
                f"Kind regards,\n\n The MeDUSA team"
            )
            recipients = [self.user.email]
            msg = EmailMultiAlternatives(
                subject=subject,
                body=message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=recipients,
                cc=[signing_user.email],
                reply_to=[signing_user.email],
            )
            if not settings.DEBUG:
                msg.send()
            else:
                logger.warning(f"DID NOT SEND MESSAGE AS DEBUG MODE IS ACTIVE. Message below\n: \n{message}")
Exemplo n.º 7
0
def user_xml(request: WSGIRequest, user: User, detailed: bool):
    """Returns a User model as XML."""
    element = Element('user')
    SubElement(element, 'name').text = user.username
    if not detailed:
        SubElement(element,
                   'link',
                   href=request.build_absolute_uri('/user/' + user.username))
    return element
Exemplo n.º 8
0
def application(environ, start_response):
    from apps.core.helpers import import_class

    # Get and initialize if needed defined offload handler
    offload_handler = environ.get('OFFLOAD_HANDLER')

    if offload_handler not in HANDLERS:
        handler = import_class(offload_handler)()
        HANDLERS[offload_handler] = handler
    else:
        handler = HANDLERS[offload_handler]

    propagator = get_tracer_propagator()
    tracer = create_tracer(propagator.from_headers(environ))

    request = WSGIRequest(environ)

    with tracer.span(name='Async.' + str(request.path)) as span:
        response = handler.application(request)

        span.span_kind = span_module.SpanKind.SERVER
        span.add_attribute(attribute_key=HTTP_HOST,
                           attribute_value=request.get_host())
        span.add_attribute(attribute_key=HTTP_METHOD,
                           attribute_value=request.method)
        span.add_attribute(attribute_key=HTTP_PATH,
                           attribute_value=str(request.path))
        span.add_attribute(attribute_key=HTTP_ROUTE,
                           attribute_value=str(request.path))
        span.add_attribute(attribute_key=HTTP_URL,
                           attribute_value=str(request.build_absolute_uri()))
        span.add_attribute(attribute_key='async.offload_handler',
                           attribute_value=offload_handler)

        if response:
            span.add_attribute(attribute_key=HTTP_STATUS_CODE,
                               attribute_value=response.status_code)

    if not isinstance(response, HttpResponseBase):
        return response

    for k, v in DEFAULT_HEADERS:
        response[k] = v

    # If we're dealing with cross origin request, add necessary headers
    if environ.get('HTTP_ORIGIN'):
        for k, v in CORS_HEADER:
            response[k] = v

    http_status = '%s %s' % (response.status_code, response.reason_phrase)
    start_response(http_status, list(response.items()))
    return response
Exemplo n.º 9
0
def feed_xml(request: WSGIRequest, feed: Feed, detailed: bool):
    """Returns a Feed model as XML."""
    element = Element('feed')
    SubElement(element, 'title').text = feed.title
    SubElement(element, 'source').text = feed.source_pretty
    if detailed:
        SubElement(element, 'link', href=feed.link)
        SubElement(element, 'chosen').text = str(feed.chosen)
    else:
        SubElement(element,
                   'link',
                   href=request.build_absolute_uri('/feed/' + str(feed.pk)))
    return element
    def gen_pdf(self, request: WSGIRequest, signed: bool):
        headers = dict(request.headers)
        if signed:
            assert self.is_signed_off is True, "Attempted to generate signed pdf but it is not signed off"
            cert_url = request.build_absolute_uri(reverse("users:certificate_detail_signed", kwargs={"id": self.id}))
        else:
            cert_url = request.build_absolute_uri(reverse("users:certificate_detail", kwargs={"id": self.id}))
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.set_extra_http_headers({"Cookie": headers["Cookie"]})
            page.goto(cert_url)
            # https://playwright.dev/python/docs/api/class-page#page-pdf
            # Image size is 1754 x 1240
            pdf = page.pdf(prefer_css_page_size=True, print_background=True, width="1754px", height="1240px")
            browser.close()

        if signed:
            self.signed_pdf = ContentFile(content=pdf, name=f"{self.user.member_id}_certificate.pdf")
        else:
            self.preview_pdf = ContentFile(content=pdf, name=f"{self.user.member_id}_PREVIEW_certificate.pdf")
        self.save()
Exemplo n.º 11
0
    def session_set_pages(request: WSGIRequest):

        if not isinstance(request, WSGIRequest):
            raise TypeError("Parameter 1 invalid type")

        if not ("pages" in request.session): request.session['pages'] = []

        FULL_URL_WITH_QUERY_STRING = request.build_absolute_uri()
        FULL_URL = request.build_absolute_uri('?')
        ABSOLUTE_ROOT = request.build_absolute_uri('/')[:-1].strip("/")
        ABSOLUTE_ROOT_URL = request.build_absolute_uri('/').strip("/")
        REQUEST_PATH = request.get_full_path()

        if len(request.session['pages']) > 0 \
                and (request.session['pages'][0] == REQUEST_PATH):
            return

        request.session['pages'].append(REQUEST_PATH)
        request.session['pages'].reverse()

        # request.session['pages'] = list(set(request.session['pages']));

        pass
Exemplo n.º 12
0
    def __call__(self, request: WSGIRequest) -> HttpResponseBase:
        #         if settings.DEBUG:
        #             return self.get_response(request)

        request_uri = request.build_absolute_uri(request.get_full_path())
        if '/users/' in request.path_info:
            if not request.is_secure():
                new_url = request_uri.replace('http:', 'https:')
                return redirect(new_url, permanent=False)
            return self.get_response(request)
        elif request.is_secure():
            new_url = request_uri.replace('https:', 'http:')
            return redirect(new_url, permanent=False)

        return self.get_response(request)
Exemplo n.º 13
0
    def get_context(self, request: WSGIRequest, team_ID) -> dict:
        context = get_discord_context(request)
        if not context["is_verified"]:
            return context

        team = get_object_or_404(Team,
                                 ID=team_ID)  # Team.objects.get(ID=team_ID)

        members = team.members.all()
        discord_members = []
        for member in members:
            new_member = {}
            try:
                user = SocialAccount.objects.get(user_id=member.id)
            except SocialAccount.DoesNotExist:
                pass
            else:
                new_member["user_id"] = user.uid
                avatar_url = user.get_avatar_url()
                if avatar_url.endswith("None.png"):
                    random = randint(0, 4)
                    avatar_url = (
                        f"https://cdn.discordapp.com/embed/avatars/{random}.png"
                    )
                new_member["avatar_url"] = avatar_url
                new_member["username"] = user.extra_data["username"]
                new_member["discriminator"] = user.extra_data["discriminator"]
            discord_members.append(new_member)
        team.discord_members = discord_members
        print(team)
        context["team"] = team
        context["challenge"] = team.challenge
        if team.submitted:
            try:
                context["submission"] = Submission.objects.get(
                    team=team, challenge=team.challenge)
            except:
                pass
        print(context["challenge"].submissions_status)
        context["invite"] = request.build_absolute_uri(
            location=f"/timathon/member/{team.invite}")
        return context
Exemplo n.º 14
0
def item_xml(request: WSGIRequest, item: Item, detailed: bool):
    """Returns an Item model as XML."""
    element = Element('item')
    SubElement(element, 'title').text = item.title
    if detailed:
        SubElement(element, 'link', href=item.link)
        SubElement(element, 'description').text = item.description
        SubElement(element, 'image', src=item.picture)
        element.extend([
            comment_xml(comment)
            for comment in item.comments.all().order_by('-date')[:20]
        ])
    else:
        SubElement(element,
                   'link',
                   href=request.build_absolute_uri('/item/' + str(item.pk)))
    SubElement(element, 'upvotes').text = str(item.upvote_count)
    SubElement(element, 'downvotes').text = str(item.downvote_count)
    element.append(feed_xml(request, item.feed, False))
    return element
Exemplo n.º 15
0
def tutor_signup(request: WSGIRequest) -> HttpResponse:
    semester: Semester = get_object_or_404(Semester, pk=get_semester(request))
    settings = get_object_or_404(Settings, semester=semester)

    if not settings.registration_open:
        return render(
            request,
            "tutors/standalone/tutor_signup/registration_closed.html",
            {
                "start": settings.open_registration,
                "end": settings.close_registration,
            },
        )

    answer_formset, questions_exist = generate_answer_formset(
        request, semester)
    form = TutorForm(request.POST or None, semester=semester)
    if form.is_valid() and (not questions_exist or answer_formset.is_valid()):
        if settings.mail_registration is None:
            messages.error(
                request,
                _(
                    "We did not configure a mail to send to you in case you registered. Please Contact {mail} and "
                    "tell us about this error. We are very sorry about this inconvenience. To make up for it cute "
                    "cat-images: https://imgur.com/gallery/3OMii", ).format(
                        mail=TutorMail.SET_TUTOR),
            )
            return redirect("tutors:tutor_signup")
        try:
            tutor: Tutor = form.save()
        except IntegrityError:
            messages.error(
                request,
                _(
                    "The email {tutor_mail_address} does already exist for the {semester}. "
                    "Did you already sign up, or is the email invalid? "
                    "Please write us a mail at {set_mail_address} instead of trying again.",
                ).format(
                    semester=str(semester),
                    tutor_mail_address=form.cleaned_data["email"],
                    set_mail_address=TutorMail.SET_TUTOR,
                ),
            )
            return redirect("tutors:tutor_signup")

        tutor.log(None, "Signed up")
        save_answer_formset(answer_formset, tutor.id)

        activation_url = request.build_absolute_uri(
            reverse(
                "tutors:tutor_signup_confirm",
                kwargs={
                    "uidb64": urlsafe_base64_encode(force_bytes(tutor.pk)),
                    "token":
                    account_activation_token.make_token(tutor),  # type: ignore
                },
            ), )
        if not settings.mail_registration.send_mail_registration(
                tutor, activation_url):
            messages.error(
                request,
                _("Could not send email. If this error persists send a mail to {mail}"
                  ).format(mail=TutorMail.SET),
            )
            return redirect("tutors:tutor_signup")
        MailTutorTask.objects.create(tutor=tutor,
                                     mail=settings.mail_registration,
                                     task=None)
        return redirect("tutors:tutor_signup_confirmation_required")

    context = {
        "semester": semester,
        "answer_formset": answer_formset,
        "questions_exist": questions_exist,
        "form": form,
    }
    return render(request, "tutors/standalone/tutor_signup/signup.html",
                  context)
Exemplo n.º 16
0
    def process_response(self, request: WSGIRequest,
                         response: HttpResponse) -> HttpResponse:
        if not wagtailcache_settings.WAGTAIL_CACHE:
            return response

        if getattr(request, "_wagtailcache_skip", False):
            # If we should skip this response, add header and return.
            _patch_header(response, Status.SKIP)
            return response

        if not getattr(request, "_wagtailcache_update", False):
            # We don't need to update the cache, just return.
            return response

        # Check if the response is cacheable
        # Don't cache private or no-cache responses.
        # Do cache 200, 301, 302, 304, and 404 codes so that wagtail doesn't
        #   have to repeatedly look up these URLs in the database.
        # Don't cache streaming responses.
        is_cacheable = (CacheControl.NOCACHE.value not in response.get(
            "Cache-Control", "")
                        and CacheControl.PRIVATE.value not in response.get(
                            "Cache-Control", "")
                        and response.status_code in (200, 301, 302, 304, 404)
                        and not response.streaming)
        # Don't cache 200 responses that set a user-specific cookie in response
        # to a cookie-less request (e.g. CSRF tokens).
        if is_cacheable and response.status_code == 200:
            is_cacheable = not (not request.COOKIES and response.cookies
                                and has_vary_header(response, "Cookie"))

        # Allow the user to override our caching decision.
        for fn in hooks.get_hooks("is_response_cacheable"):
            result = fn(response, is_cacheable)
            if isinstance(result, bool):
                is_cacheable = result

        # If we are not allowed to cache the response, just return.
        if not is_cacheable:
            # Add response header to indicate this was intentionally not cached.
            _patch_header(response, Status.SKIP)
            return response

        # Try to get the timeout from the ``max-age`` section of the
        # ``Cache-Control`` header before reverting to using the cache's
        # default.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self._wagcache.default_timeout
        patch_response_headers(response, timeout)
        if timeout:
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        None,
                                        cache=self._wagcache)

            # Track cache keys
            uri = unquote(request.build_absolute_uri())
            keyring = self._wagcache.get("keyring", {})

            if not re.findall("robots.txt|favicon.ico", uri) and is_cacheable:
                keyring[uri] = keyring.get(uri, []) + [cache_key]
                self._wagcache.set("keyring", keyring)

            if isinstance(response, SimpleTemplateResponse):
                response.add_post_render_callback(
                    lambda r: self._wagcache.set(cache_key, r, timeout))
            else:
                self._wagcache.set(cache_key, response, timeout)

            # Add a response header to indicate this was a cache miss.
            _patch_header(response, Status.MISS)

        return response
Exemplo n.º 17
0
def gen_absolute_link(request: WSGIRequest, slug):
    return request.build_absolute_uri(reverse('shortlink', args=(slug, )))