Example #1
0
def test_basket_update_errors():
    request = get_request_with_basket()
    basket = request.basket
    product = get_default_product()
    basket_commands.handle_add(request, basket, product_id=product.pk, quantity=1)

    # Hide product and now updating quantity should give errors
    shop_product = product.get_shop_instance(request.shop)
    shop_product.suppliers.clear()

    line_id = basket.get_lines()[0].line_id
    basket_commands.handle_update(request, basket, **{"q_%s" % line_id: "2"})
    error_messages = messages.get_messages(request)
    # One warning is added to messages
    assert len(error_messages) == 1
    assert any("not supplied" in msg.message for msg in error_messages)

    shop_product.visible = False
    shop_product.save()

    basket_commands.handle_update(request, basket, **{"q_%s" % line_id: "2"})

    error_messages = messages.get_messages(request)
    # Two warnings is added to messages
    assert len(error_messages) == 3
    assert any("not visible" in msg.message for msg in error_messages)
    assert all("[" not in msg.message for msg in error_messages)
Example #2
0
    def process_response(self, request, response):
        for message in messages.get_messages(request):
            log.debug(message)
        if request.is_ajax():
            if response['Content-Type'] in ["application/javascript",
                                            "application/json"]:
                try:
                    content = json.loads(response.content)
                except ValueError:
                    return response

                django_messages = []

                for message in messages.get_messages(request):

                    django_messages.append({
                        "level": message.level,
                        "message": message.message,
                        "extra_tags": message.tags,
                    })

                content['django_messages'] = django_messages

                response.content = json.dumps(content)
        return response
Example #3
0
def dnsmanager(request):
    messages.get_messages(request)

    subdomains = models.Subdomain.objects.filter(user=request.user)
    if len(subdomains)>0:
        records_in_dnsimple = subdomain_in_dnsimple(subdomains[0].name)
        main_subdomain = subdomains[0].name

    if request.method == 'POST':
        user = User.objects.get(username=request.user.username)
        new_subdomain = models.Subdomain(user=user)
        form = forms.SubdomainForm(request.POST, instance=new_subdomain)
        if form.is_valid():
            cleaned_info = form.cleaned_data
            if  models.Subdomain.objects.filter(name=cleaned_info['name']).exists():
                messages.add_message(request, messages.WARNING, "该网址已被申请了!")
                return redirect('/dnsmanager')
            else:
                form.save()
                messages.add_message(request, messages.SUCCESS, "网址申请成功!")
                return redirect('/dnsmanager')
    else:
        form = forms.SubdomainForm()

    template = get_template('dnsmanager.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)
    return HttpResponse(html)
Example #4
0
def contact(request):
    form_class = ContactForm
    if request.method == "POST":
        form = form_class(data=request.POST)
        if form.is_valid():
            contact_name = request.POST.get("contact_name", "")
            contact_email = request.POST.get("contact_email", "")
            form_content = request.POST.get("content", "")
            # email the profile with the contact information
            template = get_template("pages/contact_template.txt")
            context = Context(
                {"contact_name": contact_name, "contact_email": contact_email, "form_content": form_content}
            )
            content = template.render(context)
            email = EmailMessage(
                "New contact form submission",
                content,
                "Your website" + "<*****@*****.**>",
                ["*****@*****.**"],
                headers={"Reply-To": contact_email},
            )
            email.send()
            # messages.add_message(request, messages.SUCCESS, 'Hello world.')
            messages.success(request, "Email sent successfully!")
            get_messages(request)
            return redirect("contact")
    return render(request, "pages/contact.html", {"form": form_class})
Example #5
0
def assert_config_value(rf, admin_user, form_id, key, value, expected_value, shop=None):
    if not shop:
        shop = get_default_shop()

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    view_func = SystemSettingsView.as_view()
    response = view_func(request)
    assert response.status_code == 200

    form_field = "%s-%s" % (form_id, key)
    data = {form_field: value}
    request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
    response = view_func(request)
    assert response.status_code == 302
    if expected_value == "unset":
        expected_value = value
    assert configuration.get(None, key) == expected_value

    assert len(messages.get_messages(request)) == 1

    # Double save the form and the configuration should still be unchanged
    response = view_func(request)
    assert response.status_code == 302
    assert configuration.get(None, key) == expected_value

    assert len(messages.get_messages(request)) == 2

    return shop
Example #6
0
def posting(request):
    if request.user.is_authenticated():
        username = request.user.username
        useremail = request.user.email
    messages.get_messages(request)
        
    if request.method == 'POST':
        user = User.objects.get(username=username)
        diary = models.Diary(user=user)
        post_form = forms.DiaryForm(request.POST, instance=diary)
        if post_form.is_valid():
            messages.add_message(request, messages.INFO, "日记已保存")
            post_form.save()  
            return HttpResponseRedirect('/')
        else:
            messages.add_message(request, messages.INFO, '要张贴日记,每一个字段都要填...')
    else:
        post_form = forms.DiaryForm()
        messages.add_message(request, messages.INFO, '要张贴日记,每一个字段都要填...')

    template = get_template('posting.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)

    return HttpResponse(html)
Example #7
0
def maintenance(request):
    """Handle the maintenance view"""
    messages.get_messages(request)
    template_name = getattr(
        settings, 'DS_MAINTENANCE_TEMPLATE', 'django_shared/maintenance.html')
    return render(request, template_name, {
        'settings': settings,
    })
Example #8
0
 def test_email_address_can_change(self):
     assert len(get_messages(self.request)) == 0
     self.user.update(email='*****@*****.**')
     views.login_user(self.request, self.user, self.identity)
     user = self.user.reload()
     assert user.fxa_id == '9001'
     assert user.email == '*****@*****.**'
     assert len(get_messages(self.request)) == 0
Example #9
0
 def test_fxa_data_gets_set(self):
     assert len(get_messages(self.request)) == 0
     self.user.update(fxa_id=None)
     views.login_user(self.request, self.user, self.identity)
     user = self.user.reload()
     assert user.fxa_id == '9001'
     assert not user.has_usable_password()
     assert len(get_messages(self.request)) == 1
Example #10
0
def page_not_found(request):
    """Handle the page_not_found view"""
    messages.get_messages(request)
    template_name = getattr(
        settings, 'DS_404_TEMPLATE', 'django_shared/404.html')
    return render(request, template_name, {
        'settings': settings,
    }, status=404)
Example #11
0
def server_error(request):
    """Handle the server_error view"""
    messages.get_messages(request)
    template_name = getattr(
        settings, 'DS_500_TEMPLATE', 'django_shared/500.html')
    return render(request, template_name, {
        'settings': settings,
    }, status=500)
Example #12
0
def index(request, pid=None, del_pass=None):

    messages.get_messages(request)

    template = get_template('index.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)
    return HttpResponse(html)
 def test_fxa_data_gets_set_migration_over(self):
     assert len(get_messages(self.request)) == 0
     self.user.update(fxa_id=None)
     self.create_switch('fxa-migrated', active=True)
     views.login_user(self.request, self.user, self.identity)
     user = self.user.reload()
     assert user.fxa_id == '9001'
     assert not user.has_usable_password()
     assert len(get_messages(self.request)) == 0
Example #14
0
def edit_recipe(request, recipe_id):
    recipe = Recipe.objects.get(pk=recipe_id)
    ingredients = Ingredient.objects.filter(recipe_id=recipe)

    if request.method == 'POST':
        recipe_form = RecipeForm(request.POST, instance=Recipe.objects.get(id=recipe_id))
        ingredient_form = IngredientForm(request.POST)

        if recipe_form.is_valid():
            recipe_save = recipe_form.save(commit=False)
            recipe_save.user = request.user
            recipe_save.edited = datetime.now()
            recipe_save.save()
            recipe_id = recipe_save.id
            messages.info(request, 'Recipe successfully updated.')
            return HttpResponseRedirect(reverse('menu:recipe_details', args=(recipe_id,)))

        if ingredient_form.is_valid():
            # clears messages
            storage = messages.get_messages(request)
            for _ in storage:
                pass

            ingredient_save = ingredient_form.save(commit=False)
            ingredient_save.recipe = recipe
            messages.info(request, 'Ingredient ' + ingredient_save.name + ' added.')

            if ingredients:
                max_ingredient_sorting = Ingredient.objects.filter(recipe_id=recipe).order_by('-sorting')[0]
                ingredient_save.sorting = max_ingredient_sorting.sorting + 10
            else:
                ingredient_save.sorting = 10

            ingredient_save.save()
            return HttpResponseRedirect(reverse('menu:edit_recipe', args=(recipe_id,)))

        else:
            # clears messages
            storage = messages.get_messages(request)
            for _ in storage:
                pass

            messages.error(request, 'Ingredient name and amount are required.')
            ingredient_form = IngredientForm(request.POST)
    else:
        ingredient_form = IngredientForm()

    recipe_form = RecipeForm(instance=recipe)

    return render_to_response('menu/edit_recipe.html', {
        'form': recipe_form,
        'ingredient_form': ingredient_form,
        'recipe': recipe,
    },
        context_instance=RequestContext(request)
    )
Example #15
0
def del_record(request, rec_id):
    messages.get_messages(request)
    try:
        dns = DNSimple(username=settings.DNSIMPLE_USERNAME, password=settings.DNSIMPLE_PASSWORD)    
        dns.delete_record('raspi.tw', rec_id)
        messages.add_message(request, messages.SUCCESS, "成功删除记录!")
    except:
        messages.add_message(request, messages.WARNING, "记录删除失败!")
        pass
    return redirect('/dnsmanager')
Example #16
0
 def test_error_no_profile_with_no_path(self):
     request = self.make_request()
     assert len(get_messages(request)) == 0
     response = self.render_error(request, views.ERROR_NO_PROFILE)
     assert response.status_code == 302
     messages = get_messages(request)
     assert len(messages) == 1
     assert ('Firefox Account could not be found'
             in next(iter(messages)).message)
     assert_url_equal(response['location'], self.login_url())
Example #17
0
def index(request, pid=None, del_pass=None):
    if request.user.is_authenticated():
        username = request.user.username
        useremail = request.user.email
    messages.get_messages(request)
    template = get_template('index.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)
    return HttpResponse(html)
Example #18
0
 def test_error_no_code_with_safe_path(self):
     request = self.make_request()
     assert len(get_messages(request)) == 0
     response = self.render_error(
         request, views.ERROR_NO_CODE, next_path='/over/here')
     assert response.status_code == 302
     messages = get_messages(request)
     assert len(messages) == 1
     assert 'could not be parsed' in next(iter(messages)).message
     assert_url_equal(response['location'], self.login_url(to='/over/here'))
Example #19
0
def index(request):

    messages.get_messages(request)

    pics = random.sample(range(1,87),6)

    template = get_template('index.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)
    return HttpResponse(html)
Example #20
0
 def test_error_state_mismatch_with_unsafe_path(self):
     request = self.make_request()
     assert len(get_messages(request)) == 0
     response = self.render_error(
         request, views.ERROR_STATE_MISMATCH,
         next_path='https://www.google.com/')
     assert response.status_code == 302
     messages = get_messages(request)
     assert len(messages) == 1
     assert 'could not be logged in' in next(iter(messages)).message
     assert_url_equal(response['location'], self.login_url())
Example #21
0
def messages_to_json(request):
    json = {'messages': []}
    for message in messages.get_messages(request):
        json['messages'].append({
            "level": message.level,
            "level_tag": message.level_tag,
            "message": message.message,
        })
    json['messages_html'] = render_to_string(
        'includes/messages.html',
        {'messages': messages.get_messages(request)})
    return json
 def merengue_messagebox(context):
     request = context['request']
     portal_messages = messages.get_messages(request)
     if not portal_messages:
         if 'form' in context:
             form = context['form']
             if getattr(form, 'errors', []):
                 if form.non_field_errors():
                     send_error(request, form.non_field_errors())
                 send_error(request, _('Form filled has errors. Please correct'))
                 portal_messages = messages.get_messages(request)
     return {'portal_messages': portal_messages}
Example #23
0
def test_basket_update_with_package_product():
    if "shuup.simple_supplier" not in settings.INSTALLED_APPS:
        pytest.skip("Need shuup.simple_supplier in INSTALLED_APPS")
    from shuup_tests.simple_supplier.utils import get_simple_supplier

    request = get_request_with_basket()
    basket = request.basket
    shop = get_default_shop()
    supplier = get_simple_supplier()
    parent, child = get_unstocked_package_product_and_stocked_child(shop, supplier, child_logical_quantity=2)

    # There should be enough stock for 1 parent and 1 extra child, each of quantity 1
    basket_commands.handle_add(request, basket, product_id=parent.pk, quantity=1)
    assert basket.product_count == 1
    basket_commands.handle_add(request, basket, product_id=child.pk, quantity=1)
    assert basket.product_count == 2
    assert not messages.get_messages(request)

    basket_lines = {line.product.id: line for line in basket.get_lines()}
    package_line = basket_lines[parent.id]
    extra_child_line = basket_lines[child.id]

    # Trying to increase package product line quantity should fail, with error message
    basket_commands.handle_update(request, basket, **{"q_%s" % package_line.line_id: "2"})
    assert basket.product_count == 2
    assert len(messages.get_messages(request)) == 1

    # So should increasing the extra child line quantity
    basket_commands.handle_update(request, basket, **{"q_%s" % extra_child_line.line_id: "2"})
    assert basket.product_count == 2
    assert len(messages.get_messages(request)) == 2

    # However, if we delete the parent line, we can increase the extra child
    basket_commands.handle_update(request, basket, **{"delete_%s" % package_line.line_id: "1"})
    assert basket.product_count == 1
    basket_commands.handle_update(request, basket, **{"q_%s" % extra_child_line.line_id: "2"})
    assert basket.product_count == 2

    # Resetting to original basket contents
    basket_commands.handle_update(request, basket, **{"q_%s" % extra_child_line.line_id: "1"})
    basket_commands.handle_add(request, basket, product_id=parent.pk, quantity=1)
    basket_lines = {line.product.id: line for line in basket.get_lines()}
    package_line = basket_lines[parent.id]  # Package line will have a new ID
    assert basket.product_count == 2

    # Like above, delete the child line and we can now increase the parent
    basket_commands.handle_update(request, basket, **{"delete_%s" % extra_child_line.line_id: "1"})
    assert basket.product_count == 1
    basket_commands.handle_update(request, basket, **{"q_%s" % package_line.line_id: "2"})
    assert basket.product_count == 2
Example #24
0
    def serve(self, request):
        if request.method == 'POST':
            # honeypot
            if len(request.POST.get('url_h', '')):
                messages.success(request, self.success_message)
                return HttpResponseRedirect(self.url)

            form = self.get_form(request.POST)

            if form.is_valid():
                self.process_form_submission(form)
                messages.success(request, self.success_message)

                if request.is_ajax():
                    # Valid ajax post
                    data = {'messages': []}
                    for message in messages.get_messages(request):
                        data['messages'].append({
                            "level": message.level,
                            "level_tag": message.level_tag,
                            "message": message.message,
                        })
                    data['messages_html'] = render_to_string(
                        'includes/messages.html',
                        {'messages': messages.get_messages(request)})
                    return JsonResponse(data)
                else:
                    # Valid (non-ajax) post
                    if self.thank_you_page:
                        return HttpResponseRedirect(self.thank_you_page.url)
                    else:
                        return HttpResponseRedirect(self.url)

            elif request.is_ajax():
                # Invalid ajax post
                data = {'errors': form.errors}
                return JsonResponse(data, status=400)

        else:
            # GET request
            form = self.get_form()

        context = self.get_context(request)
        context['form'] = form
        return render(
            request,
            self.template,
            context
        )
Example #25
0
def add_record(request, subdomain):
    messages.get_messages(request)
    if request.method=='POST':
        content = request.POST.get('content')
        record_type = request.POST.get('record_type')
        try:
            dns = DNSimple(username=settings.DNSIMPLE_USERNAME, password=settings.DNSIMPLE_PASSWORD)
            dns.add_record('raspi.tw', { 'name':subdomain, 
                                         'record_type':record_type,
                                         'content':content})   
            messages.add_message(request, messages.SUCCESS, "添加记录成功!")
        except:
            messages.add_message(request, messages.WARNING, "添加记录失败!")
            pass
    return redirect('/dnsmanager')    
Example #26
0
    def test_post_with_superuser(self):
        """Test POST with superuser."""
        self.create_inactive()
        user = UserFactory.create(**{"is_superuser": True})
        self.request.method = "POST"
        self.request.POST = QueryDict("activate_users=%s&activate_users=%s" % (self.inactive_1.id, self.inactive_2.id))
        self.request.user = user
        response = self.view(self.request).render()

        rendered = render_to_string(
            "superusertools/manage_inactive_users.html",
            {
                "GEOKEY_VERSION": version.get_version(),
                "PLATFORM_NAME": get_current_site(self.request).name,
                "user": user,
                "messages": get_messages(self.request),
                "inactive_users": [self.inactive_3],
            },
        )

        self.assertEqual(response.status_code, 200)
        response = render_helpers.remove_csrf(response.content.decode("utf-8"))
        self.assertEqual(response, rendered)
        self.assertEqual(User.objects.filter(is_active=False).count(), 1)
        self.assertEqual(len(EmailAddress.objects.filter(verified=False)), 1)
Example #27
0
def voter_summary_view(request, voter_id):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    voter_id = convert_to_int(voter_id)
    voter_on_stage_found = False
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        voter_on_stage_found = True
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Voter.DoesNotExist:
        # This is fine, create new
        pass

    if voter_on_stage_found:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'voter': voter_on_stage,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
        }
    return render(request, 'voter/voter_summary.html', template_values)
Example #28
0
def voter_guide_list_view(request):
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    voter_guide_list = []
    voter_guide_list_object = VoterGuideList()
    if positive_value_exists(google_civic_election_id):
        results = voter_guide_list_object.retrieve_voter_guides_for_election(
            google_civic_election_id=google_civic_election_id)

        if results['success']:
            voter_guide_list = results['voter_guide_list']
    else:
        results = voter_guide_list_object.retrieve_all_voter_guides()

        if results['success']:
            voter_guide_list = results['voter_guide_list']

    election_list = Election.objects.order_by('-election_day_text')

    messages_on_stage = get_messages(request)
    template_values = {
        'election_list': election_list,
        'google_civic_election_id': google_civic_election_id,
        'messages_on_stage': messages_on_stage,
        'voter_guide_list': voter_guide_list,
    }
    return render(request, 'voter_guide/voter_guide_list.html', template_values)
Example #29
0
def index(request, pid=None, del_pass=None):
    if request.user.is_authenticated():
        username = request.user.username
        useremail = request.user.email
        try:
            user = models.User.objects.get(username=username)
            diaries = models.Diary.objects.filter(user=user).order_by('-ddate')
        except:
            pass
    messages.get_messages(request)

    template = get_template('index.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)
    return HttpResponse(html)
Example #30
0
def position_edit_view(request, position_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    position_id = convert_to_int(position_id)
    position_on_stage_found = False
    try:
        position_on_stage = CandidateCampaign.objects.get(id=position_id)
        position_on_stage_found = True
    except CandidateCampaign.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except CandidateCampaign.DoesNotExist:
        # This is fine, create new
        pass

    if position_on_stage_found:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'position': position_on_stage,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
        }
    return render(request, 'position/position_edit.html', template_values)
Example #31
0
def index(request, pid=None, del_pass=None):
    if request.user.is_authenticated:
        username = request.user.username
        useraddress = request.user.address
    messages.get_messages(request)
    return render(request, 'index.html', locals())
Example #32
0
    def get(self, request):  # pylint: disable=too-many-statements
        """
        Looks up the passed code and adds the matching product to a basket,
        then applies the voucher and if the basket total is FREE places the order and
        enrolls the user in the course.
        """
        template_name = 'coupons/_offer_error.html'
        code = request.GET.get('code')
        sku = request.GET.get('sku')
        failure_url = request.GET.get('failure_url')
        site_configuration = request.site.siteconfiguration

        if not code:
            return render(request, template_name,
                          {'error': _('Code not provided.')})
        if not sku:
            return render(request, template_name,
                          {'error': _('SKU not provided.')})

        try:
            voucher = Voucher.objects.get(code=code)
        except Voucher.DoesNotExist:
            msg = 'No voucher found with code {code}'.format(code=code)
            return render(request, template_name, {'error': _(msg)})

        try:
            product = StockRecord.objects.get(partner_sku=sku).product
        except StockRecord.DoesNotExist:
            return render(request, template_name,
                          {'error': _('The product does not exist.')})

        valid_voucher, msg, hide_error_message = voucher_is_valid(
            voucher, [product], request)
        if not valid_voucher:
            logger.warning(
                '[Code Redemption Failure] The voucher is not valid for this product. '
                'User: %s, Product: %s, Code: %s, Message: %s',
                request.user.username, product.id, voucher.code, msg)
            return render(request, template_name, {
                'error': msg,
                'hide_error_message': hide_error_message
            })

        offer = voucher.best_offer
        if not offer.is_email_valid(request.user.email):
            logger.warning(
                '[Code Redemption Failure] Unable to apply offer because the user\'s email '
                'does not meet the domain requirements. '
                'User: %s, Offer: %s, Code: %s', request.user.username,
                offer.id, voucher.code)
            return render(
                request, template_name,
                {'error': _('You are not eligible to use this coupon.')})

        email_confirmation_response = get_redirect_to_email_confirmation_if_required(
            request, offer, product)
        if email_confirmation_response:
            return email_confirmation_response

        try:
            enterprise_customer = get_enterprise_customer_from_voucher(
                request.site, voucher)
        except EnterpriseDoesNotExist as e:
            # If an EnterpriseException is caught while pulling the EnterpriseCustomer, that means there's no
            # corresponding EnterpriseCustomer in the Enterprise service (which should never happen).
            logger.exception(six.text_type(e))
            return render(
                request, template_name, {
                    'error':
                    _('Couldn\'t find a matching Enterprise Customer for this coupon.'
                      )
                })

        if enterprise_customer and product.is_course_entitlement_product:
            return render(
                request, template_name, {
                    'error':
                    _('This coupon is not valid for purchasing a program. Try using this on an individual '
                      'course in the program. If you need assistance, contact edX support.'
                      )
                })

        if enterprise_customer is not None and enterprise_customer_user_needs_consent(
                request.site,
                enterprise_customer['id'],
                product.course.id,
                request.user.username,
        ):
            consent_token = get_enterprise_customer_data_sharing_consent_token(
                request.user.access_token, product.course.id,
                enterprise_customer['id'])
            received_consent_token = request.GET.get('consent_token')
            if received_consent_token:
                # If the consent token is set, then the user is returning from the consent view. Render out an error
                # if the computed token doesn't match the one received from the redirect URL.
                if received_consent_token != consent_token:
                    logger.warning(
                        '[Code Redemption Failure] Unable to complete code redemption because of '
                        'invalid consent. User: %s, Offer: %s, Code: %s',
                        request.user.username, offer.id, voucher.code)
                    return render(request, template_name, {
                        'error':
                        _('Invalid data sharing consent token provided.')
                    })
            else:
                # The user hasn't been redirected to the interstitial consent view to collect consent, so
                # redirect them now.
                redirect_url = get_enterprise_course_consent_url(
                    request.site,
                    code,
                    sku,
                    consent_token,
                    product.course.id,
                    enterprise_customer['id'],
                    failure_url=failure_url)
                return HttpResponseRedirect(redirect_url)

        try:
            basket = prepare_basket(request, [product], voucher)
        except AlreadyPlacedOrderException:
            msg = _('You have already purchased {course} seat.').format(
                course=product.course.name)
            return render(request, template_name, {'error': msg})

        if basket.total_excl_tax == 0:
            try:
                order = self.place_free_order(basket)
                return HttpResponseRedirect(
                    get_receipt_page_url(
                        site_configuration,
                        order.number,
                        disable_back_button=True,
                    ), )
            except:  # pylint: disable=bare-except
                logger.exception(
                    'Failed to create a free order for basket [%d]', basket.id)
                return absolute_redirect(self.request, 'checkout:error')

        if enterprise_customer:
            if is_voucher_applied(basket, voucher):
                message = _(
                    'A discount has been applied, courtesy of {enterprise_customer_name}.'
                ).format(
                    enterprise_customer_name=enterprise_customer.get('name'))
                messages.info(self.request, message)
            else:
                # Display a generic message to the user if a condition-specific
                # message has not already been added by an unsatified Condition class.
                if not messages.get_messages(self.request):
                    messages.warning(
                        self.request,
                        _('This coupon code is not valid for this course. Try a different course.'
                          ))
                self.request.basket.vouchers.remove(voucher)

        # The coupon_redeem_redirect query param is used to communicate to the Payment MFE that it may redirect
        # and should not display the payment form before making that determination.
        # TODO: It would be cleaner if the user could be redirected to their final destination up front.
        redirect_url = get_payment_microfrontend_or_basket_url(
            self.request) + "?coupon_redeem_redirect=1"
        return HttpResponseRedirect(redirect_url)
Example #33
0
def refresh_button(request):
    req = json.loads(request.POST.get('data'))
    print('refresh', req)

    # get data
    button = req.get('button')
    update = req.get('update')
    search_date = req.get('search_date')
    search_year = int(search_date[:4])
    search_month = int(search_date[5:7])
    search_day = int(search_date[8:])
    datetime_search_date = datetime.datetime(search_year, search_month,
                                             search_day)

    # get last crawled time
    formatted_updated_time, _ = get_formatted_updated_time()

    # refresh 를 누른 경우
    if update == 'true':
        # DB 업데이트 해주기
        print(update_members())
        print(update_questions_and_solves())
        print(update_question_tiers())

        # update update time
        now = timezone.now()
        print(now)
        Update_time.objects.create(updated_time=now)
        print('last crawl time update to: ', now)

        # 1분 안에 크롤링 또 했으면 경고 메세지 -> 여기 버그 왠지 모르겠는데 여기서 끊겨버림
        if now.hour == int(formatted_updated_time[:2]) and now.minute - int(
                formatted_updated_time[3:5]) <= 1:
            messages.warning(request, '크롤링 쿨타임 1분! 너무 자주하면 백준한테 막혀요ㅋㅋ..(경험담)')

        # 새로운 마지막 크롤링 시간 새로 반영
        formatted_updated_time = get_time()

        # message
        messages.success(request, 'DB has been updated successfully!')

    # 각각 누른 버튼에 대한 db 정보 가져오기
    if button == 'day':
        results, formatted_start_date = get_prob_info('day',
                                                      datetime_search_date)
    elif button == 'week':
        results, formatted_start_date = get_prob_info('week',
                                                      datetime_search_date)
    elif button == 'month':
        results, formatted_start_date = get_prob_info('month',
                                                      datetime_search_date)
    elif button == 'total':
        results, formatted_start_date = get_prob_info('total',
                                                      datetime_search_date)

    # ajax request 이니깐 messages 는 별도 처리
    django_messages = []

    for message in messages.get_messages(request):
        django_messages.append({
            "tag": message.level_tag,
            "message": message.message,
        })

    # 반환 : 최신화된 DB 정보랑 업데이트 한 지금 시간
    context = {
        'results': results,
        'update_time': formatted_updated_time,
        'start_date': formatted_start_date,
        'messages': django_messages,
        'page': 'details'
    }
    print('sending data to client')
    return HttpResponse(json.dumps(context), content_type='application/json')
Example #34
0
def index(request):
    storage = messages.get_messages(request)
    storage.used = True
    return render(request, 'semi_restful_app/index.html',
                  {"users": User.objects.all()})
Example #35
0
def index(request):
    msg = messages.get_messages(request)
    return render(request, "login.html", {'messages': msg})
Example #36
0
def index(request):

    context = {'messages': get_messages(request)}

    return render(request, 'email_app/index.html', context)
Example #37
0
def index(request):
    context = {'messages': get_messages(request)}
    return render(request, 'log_and_reg/index.html', context)
Example #38
0
 def test_add_new_book_by_form(self, client):
     response = client.post(reverse('books:new_book'), book_for_test)
     messages = [m.tags for m in get_messages(response.wsgi_request)]
     assert messages[0] == 'success'
Example #39
0
    def get(self, request):

        try:
            storage = get_messages(request)
            auth = None
            for message in storage:
                auth = message
                break
            user = auth.message.split(' ')

            dw = datawiz.DW(user[0], user[1])
            date_from = datetime.date(2015, 11, 17)
            date_to = datetime.date(2015, 11, 18)
            data = {
                'date_from': date_from,
                'date_to': date_to,
            }

            turnover = dw.get_products_sale(by='turnover',
                                            date_from=date_from,
                                            date_to=date_to)
            data['turnover'] = {
                'from':
                round(turnover.sum(axis=1)[0], 2),
                'to':
                round(turnover.sum(axis=1)[1], 2),
                'percent':
                round((round(turnover.sum(axis=1)[1], 2) -
                       round(turnover.sum(axis=1)[0], 2)) /
                      max(round(turnover.sum(axis=1)[1], 2),
                          round(turnover.sum(axis=1)[0], 2)) * 100, 2),
                'diff':
                round(
                    round(turnover.sum(axis=1)[1], 2) -
                    round(turnover.sum(axis=1)[0], 2), 2),
            }

            quantity = dw.get_products_sale(by='qty',
                                            date_from=date_from,
                                            date_to=date_to)
            data['quantity'] = {
                'from':
                round(quantity.sum(axis=1)[0], 2),
                'to':
                round(quantity.sum(axis=1)[1], 2),
                'percent':
                round((round(quantity.sum(axis=1)[1], 2) -
                       round(quantity.sum(axis=1)[0], 2)) /
                      max(round(quantity.sum(axis=1)[1], 2),
                          round(quantity.sum(axis=1)[0], 2)) * 100, 2),
                'diff':
                round(
                    round(quantity.sum(axis=1)[1], 2) -
                    round(quantity.sum(axis=1)[0], 2), 2),
            }

            receipts = dw.get_products_sale(by='receipts_qty',
                                            date_from=date_from,
                                            date_to=date_to)
            data['receipts'] = {
                'from':
                round(receipts.sum(axis=1)[0], 2),
                'to':
                round(receipts.sum(axis=1)[1], 2),
                'percent':
                round((round(receipts.sum(axis=1)[1], 2) -
                       round(receipts.sum(axis=1)[0], 2)) /
                      max(round(receipts.sum(axis=1)[1], 2),
                          round(receipts.sum(axis=1)[0], 2)) * 100, 2),
                'diff':
                round(
                    round(receipts.sum(axis=1)[1], 2) -
                    round(receipts.sum(axis=1)[0], 2), 2),
            }

            data['average'] = {
                'from':
                round(data['turnover']['from'] / data['receipts']['from'], 2),
                'to':
                round(data['turnover']['to'] / data['receipts']['to'], 2),
            }
            data['average'] = {
                'from':
                data['average']['from'],
                'to':
                data['average']['to'],
                'percent':
                round(
                    (data['average']['to'] - data['average']['from']) /
                    max(data['average']['to'], data['average']['from']) * 100,
                    2),
                'diff':
                round((data['average']['to'] - data['average']['from']), 2),
            }

            messages.add_message(request, messages.INFO, auth)
            return render(request, 'info\general.html', context={'data': data})

        except:
            return redirect('/login/')
def modify(request,
           path,
           template_name='templatesadmin/edit.html',
           formclass=CodemirrorFormHtml,
           available_template_dirs=TEMPLATESADMIN_TEMPLATE_DIRS):

    template_path = _fixpath(path)

    # Check if file is within template-dirs
    if not any([
            template_path.startswith(templatedir)
            for templatedir in available_template_dirs
    ]):
        messages.error(
            request,
            message=_('Sorry, that file is not available for editing.'))
        return HttpResponseRedirect(
            reverse('admin:templatesadmin_ftemplate_changelist'))

    if request.method == 'POST':
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(
                hook.contribute_to_form(template_path))

        form = formclass(data=request.POST,
                         #widget_syntax = os.path.splitext(path)[1][1:]
                         )
        if form.is_valid():
            content = form.cleaned_data['content']

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    pre_save_notice = hook.pre_save(request, form,
                                                    template_path)
                    if pre_save_notice:
                        messages.warning(request, message=pre_save_notice)
            except TemplatesAdminException:
                e = sys.exc_info()[1]
                messages.error(request, message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            # Save the template
            try:
                f = open(template_path, 'r')
                file_content = f.read()
                f.close()

                # browser tend to strip newlines from <textarea/>s before
                # HTTP-POSTing: re-insert them if neccessary

                # content is in dos-style lineending, will be converted in next step
                if (file_content[-1] == '\n' or file_content[:-2] == '\r\n') \
                   and content[:-2] != '\r\n':
                    content = u"%s\r\n" % content

                # Template is saved in unix-style, save in unix style.
                if None == search("\r\n", file_content):
                    content = content.replace("\r\n", "\n")

                f = codecs.open(template_path, 'w', 'utf-8')
                f.write(content)
                f.close()
            except IOError:
                e = sys.exc_info()[1]
                messages.error(
                    request,
                    message=
                    _('Template "%(path)s" has not been saved! Reason: %(errormsg)s'
                      ) % {
                          'path': path,
                          'errormsg': e
                      })
                return HttpResponseRedirect(request.build_absolute_uri())

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    post_save_notice = hook.post_save(request, form,
                                                      template_path)
                    if post_save_notice:
                        messages.info(request, message=post_save_notice)
            except TemplatesAdminException:
                e = sys.exc_info()[1]
                messages.error(request, message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            messages.success(
                request,
                message=_('Template "%s" was saved successfully.' % path))
            return HttpResponseRedirect(
                reverse('admin:templatesadmin_ftemplate_changelist'))
    else:
        template_file = codecs.open(template_path, 'r', 'utf-8').read()

        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(
                hook.contribute_to_form(template_path))

        form = formclass(initial={'content': template_file},
                         #widget_syntax = os.path.splitext(path)[1][1:]
                         )

    template_context = {
        'messages': messages.get_messages(request),
        'form': form,
        'short_path': path,
        'template_path': path,
        'opts': FTemplate._meta,
        'template_writeable': os.access(template_path, os.W_OK),
    }

    return render_to_response(template_name, template_context,
                              RequestContext(request))
Example #41
0
    def repository(self, request, **kwargs):
        obj = self.get_object()

        if isinstance(obj, Translation):
            project = obj.component.project
        elif isinstance(obj, Component):
            project = obj.project
        else:
            project = obj

        if request.method == 'POST':
            serializer = RepoRequestSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)

            data = {
                'result':
                self.repository_operation(
                    request, obj, project,
                    serializer.validated_data['operation'])
            }

            storage = get_messages(request)
            if storage:
                data['detail'] = '\n'.join(m.message for m in storage)

            return Response(data)

        if not request.user.has_perm('meta:vcs.status', project):
            raise PermissionDenied()

        data = {
            'needs_commit': obj.needs_commit(),
            'needs_merge': obj.repo_needs_merge(),
            'needs_push': obj.repo_needs_push(),
        }

        if isinstance(obj, Project):
            data['url'] = reverse('api:project-repository',
                                  kwargs={'slug': obj.slug},
                                  request=request)
        else:

            if isinstance(obj, Translation):
                component = obj.component
                data['url'] = reverse(
                    'api:translation-repository',
                    kwargs={
                        'component__project__slug': component.project.slug,
                        'component__slug': component.slug,
                        'language__code': obj.language.code,
                    },
                    request=request,
                )
            else:
                component = obj
                data['url'] = reverse(
                    'api:component-repository',
                    kwargs={
                        'project__slug': obj.project.slug,
                        'slug': obj.slug
                    },
                    request=request,
                )

            data['remote_commit'] = component.get_last_remote_commit()
            data['status'] = component.repository.status()
            changes = Change.objects.filter(
                action__in=Change.ACTIONS_REPOSITORY,
                component=component).order_by('-id')

            if changes.exists() and changes[0].is_merge_failure():
                data['merge_failure'] = changes[0].target
            else:
                data['merge_failure'] = None

        return Response(data)
Example #42
0
def clear_messages(request):
    """
    Clear messages for given request.
    """
    storage = messages.get_messages(request)
    storage.used = True
Example #43
0
def login_and_registration_form(request, initial_mode="login"):
    """Render the combined login/registration form, defaulting to login

    This relies on the JS to asynchronously load the actual form from
    the user_api.

    Keyword Args:
        initial_mode (string): Either "login" or "register".

    """
    # Determine the URL to redirect to following login/registration/third_party_auth
    redirect_to = get_next_url_for_login_page(request)
    # If we're already logged in, redirect to the dashboard
    if request.user.is_authenticated():
        return redirect(redirect_to)

    # Retrieve the form descriptions from the user API
    form_descriptions = _get_form_descriptions(request)

    # Our ?next= URL may itself contain a parameter 'tpa_hint=x' that we need to check.
    # If present, we display a login page focused on third-party auth with that provider.
    third_party_auth_hint = None
    if '?' in redirect_to:
        try:
            next_args = urlparse.parse_qs(urlparse.urlparse(redirect_to).query)
            provider_id = next_args['tpa_hint'][0]
            tpa_hint_provider = third_party_auth.provider.Registry.get(provider_id=provider_id)
            if tpa_hint_provider:
                if tpa_hint_provider.skip_hinted_login_dialog:
                    # Forward the user directly to the provider's login URL when the provider is configured
                    # to skip the dialog.
                    if initial_mode == "register":
                        auth_entry = pipeline.AUTH_ENTRY_REGISTER
                    else:
                        auth_entry = pipeline.AUTH_ENTRY_LOGIN
                    return redirect(
                        pipeline.get_login_url(provider_id, auth_entry, redirect_url=redirect_to)
                    )
                third_party_auth_hint = provider_id
                initial_mode = "hinted_login"
        except (KeyError, ValueError, IndexError) as ex:
            log.error("Unknown tpa_hint provider: %s", ex)

    # If this is a themed site, revert to the old login/registration pages.
    # We need to do this for now to support existing themes.
    # Themed sites can use the new logistration page by setting
    # 'ENABLE_COMBINED_LOGIN_REGISTRATION' in their
    # configuration settings.
    if is_request_in_themed_site() and not configuration_helpers.get_value('ENABLE_COMBINED_LOGIN_REGISTRATION', False):
        if initial_mode == "login":
            return old_login_view(request)
        elif initial_mode == "register":
            return old_register_view(request)

    # Allow external auth to intercept and handle the request
    ext_auth_response = _external_auth_intercept(request, initial_mode)
    if ext_auth_response is not None:
        return ext_auth_response

    # Account activation message
    account_activation_messages = [
        {
            'message': message.message, 'tags': message.tags
        } for message in messages.get_messages(request) if 'account-activation' in message.tags
    ]

    # Otherwise, render the combined login/registration page
    context = {
        'data': {
            'login_redirect_url': redirect_to,
            'initial_mode': initial_mode,
            'third_party_auth': _third_party_auth_context(request, redirect_to, third_party_auth_hint),
            'third_party_auth_hint': third_party_auth_hint or '',
            'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
            'support_link': configuration_helpers.get_value('SUPPORT_SITE_LINK', settings.SUPPORT_SITE_LINK),
            'password_reset_support_link': configuration_helpers.get_value(
                'PASSWORD_RESET_SUPPORT_LINK', settings.PASSWORD_RESET_SUPPORT_LINK
            ) or settings.SUPPORT_SITE_LINK,
            'account_activation_messages': account_activation_messages,

            # Include form descriptions retrieved from the user API.
            # We could have the JS client make these requests directly,
            # but we include them in the initial page load to avoid
            # the additional round-trip to the server.
            'login_form_desc': json.loads(form_descriptions['login']),
            'registration_form_desc': json.loads(form_descriptions['registration']),
            'password_reset_form_desc': json.loads(form_descriptions['password_reset']),
            'account_creation_allowed': configuration_helpers.get_value(
                'ALLOW_PUBLIC_ACCOUNT_CREATION', settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True))
        },
        'login_redirect_url': redirect_to,  # This gets added to the query string of the "Sign In" button in header
        'responsive': True,
        'allow_iframing': True,
        'disable_courseware_js': True,
        'combined_login_and_register': True,
        'disable_footer': not configuration_helpers.get_value(
            'ENABLE_COMBINED_LOGIN_REGISTRATION_FOOTER',
            settings.FEATURES['ENABLE_COMBINED_LOGIN_REGISTRATION_FOOTER']
        ),
    }

    enterprise_customer = enterprise_customer_for_request(request)
    update_logistration_context_for_enterprise(request, context, enterprise_customer)

    response = render_to_response('student_account/login_and_register.html', context)
    handle_enterprise_cookies_for_logistration(request, response, context)

    return response
Example #44
0
def deleteStudent(request, sid):
    Student.objects.filter(sid=sid).delete()
    storage = messages.get_messages(request)
    storage.used = True
    messages.info(request, "Student Details Deleted")
    return redirect('/')
Example #45
0
 def _assertSuccess(self, response):
     self.assertRedirects(response,
                          reverse('dining_room:login'),
                          fetch_redirect_response=False)
     messages = list(get_messages(response.wsgi_request))
     self.assertEqual(messages, [])
Example #46
0
def login_and_registration_form(request, initial_mode="login"):
    """Render the combined login/registration form, defaulting to login

    This relies on the JS to asynchronously load the actual form from
    the user_api.

    Keyword Args:
        initial_mode (string): Either "login" or "register".

    """
    # Determine the URL to redirect to following login/registration/third_party_auth
    redirect_to = get_next_url_for_login_page(request)

    # If we're already logged in, redirect to the dashboard
    # Note: If the session is valid, we update all logged_in cookies(in particular JWTs)
    #  since Django's SessionAuthentication middleware auto-updates session cookies but not
    #  the other login-related cookies. See ARCH-282 and ARCHBOM-1718
    if request.user.is_authenticated:
        response = redirect(redirect_to)
        response = set_logged_in_cookies(request, response, request.user)
        return response

    # Retrieve the form descriptions from the user API
    form_descriptions = _get_form_descriptions(request)

    # Our ?next= URL may itself contain a parameter 'tpa_hint=x' that we need to check.
    # If present, we display a login page focused on third-party auth with that provider.
    third_party_auth_hint = None
    if '?' in redirect_to:  # lint-amnesty, pylint: disable=too-many-nested-blocks
        try:
            next_args = urllib.parse.parse_qs(
                urllib.parse.urlparse(redirect_to).query)
            if 'tpa_hint' in next_args:
                provider_id = next_args['tpa_hint'][0]
                tpa_hint_provider = third_party_auth.provider.Registry.get(
                    provider_id=provider_id)
                if tpa_hint_provider:
                    if tpa_hint_provider.skip_hinted_login_dialog:
                        # Forward the user directly to the provider's login URL when the provider is configured
                        # to skip the dialog.
                        if initial_mode == "register":
                            auth_entry = pipeline.AUTH_ENTRY_REGISTER
                        else:
                            auth_entry = pipeline.AUTH_ENTRY_LOGIN
                        return redirect(
                            pipeline.get_login_url(provider_id,
                                                   auth_entry,
                                                   redirect_url=redirect_to))
                    third_party_auth_hint = provider_id
                    initial_mode = "hinted_login"
        except (KeyError, ValueError, IndexError) as ex:
            log.exception("Unknown tpa_hint provider: %s", ex)

    # Redirect to authn MFE if it is enabled or user is not an enterprise user or not coming from a SAML IDP.
    saml_provider = False
    running_pipeline = pipeline.get(request)
    enterprise_customer = enterprise_customer_for_request(request)
    if running_pipeline:
        saml_provider, __ = third_party_auth.utils.is_saml_provider(
            running_pipeline.get('backend'), running_pipeline.get('kwargs'))

    if should_redirect_to_authn_microfrontend(
    ) and not enterprise_customer and not saml_provider:

        # This is to handle a case where a logged-in cookie is not present but the user is authenticated.
        # Note: If we don't handle this learner is redirected to authn MFE and then back to dashboard
        # instead of the desired redirect URL (e.g. finish_auth) resulting in learners not enrolling
        # into the courses.
        if request.user.is_authenticated and redirect_to:
            return redirect(redirect_to)

        query_params = request.GET.urlencode()
        url_path = '/{}{}'.format(initial_mode,
                                  '?' + query_params if query_params else '')
        return redirect(settings.AUTHN_MICROFRONTEND_URL + url_path)

    # Account activation message
    account_activation_messages = [{
        'message': message.message,
        'tags': message.tags
    } for message in messages.get_messages(request)
                                   if 'account-activation' in message.tags]

    account_recovery_messages = [{
        'message': message.message,
        'tags': message.tags
    } for message in messages.get_messages(request)
                                 if 'account-recovery' in message.tags]

    # Otherwise, render the combined login/registration page
    context = {
        'data': {
            'login_redirect_url':
            redirect_to,
            'initial_mode':
            initial_mode,
            'third_party_auth':
            third_party_auth_context(request, redirect_to,
                                     third_party_auth_hint),
            'third_party_auth_hint':
            third_party_auth_hint or '',
            'platform_name':
            configuration_helpers.get_value('PLATFORM_NAME',
                                            settings.PLATFORM_NAME),
            'support_link':
            configuration_helpers.get_value('SUPPORT_SITE_LINK',
                                            settings.SUPPORT_SITE_LINK),
            'password_reset_support_link':
            configuration_helpers.get_value(
                'PASSWORD_RESET_SUPPORT_LINK',
                settings.PASSWORD_RESET_SUPPORT_LINK)
            or settings.SUPPORT_SITE_LINK,
            'account_activation_messages':
            account_activation_messages,
            'account_recovery_messages':
            account_recovery_messages,

            # Include form descriptions retrieved from the user API.
            # We could have the JS client make these requests directly,
            # but we include them in the initial page load to avoid
            # the additional round-trip to the server.
            'login_form_desc':
            json.loads(form_descriptions['login']),
            'registration_form_desc':
            json.loads(form_descriptions['registration']),
            'password_reset_form_desc':
            json.loads(form_descriptions['password_reset']),
            'account_creation_allowed':
            configuration_helpers.get_value(
                'ALLOW_PUBLIC_ACCOUNT_CREATION',
                settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True)),
            'is_account_recovery_feature_enabled':
            is_secondary_email_feature_enabled(),
            'is_multiple_user_enterprises_feature_enabled':
            is_multiple_user_enterprises_feature_enabled(),
            'enterprise_slug_login_url':
            get_enterprise_slug_login_url(),
            'is_require_third_party_auth_enabled':
            is_require_third_party_auth_enabled(),
        },
        'login_redirect_url':
        redirect_to,  # This gets added to the query string of the "Sign In" button in header
        'responsive':
        True,
        'allow_iframing':
        True,
        'disable_courseware_js':
        True,
        'combined_login_and_register':
        True,
        'disable_footer':
        not configuration_helpers.get_value(
            'ENABLE_COMBINED_LOGIN_REGISTRATION_FOOTER',
            settings.FEATURES['ENABLE_COMBINED_LOGIN_REGISTRATION_FOOTER']),
    }

    update_logistration_context_for_enterprise(request, context,
                                               enterprise_customer)

    response = render_to_response('student_account/login_and_register.html',
                                  context)
    handle_enterprise_cookies_for_logistration(request, response, context)

    return response
Example #47
0
def add_once_message(request, level, msg):
    if msg not in [m.message for m in messages.get_messages(request)]:
        messages.add_message(request, level, msg)
def chat(request, update=""):
    user_name = None
    storage = get_messages(request)
    for message in storage:
        user_name = message
        print("MESSAGE : ", message)

    if user_name != None:
        print("username: "******"LOGIN VARS")
        print("session.matrix_user_name ", session.matrix_user_name)
        print("session.matrix_room_name ", session.matrix_room_name)
        print("session.matrix_server ", session.matrix_server)
        print("session.message_count ", session.message_count)
        print("session.show_images ", session.show_images)
        sys.stdout.flush()
        api = MatrixHttpApi(session.matrix_server, token=session.matrix_token)
        print("GET_MEMBERSHIP")
        api.join_room(api.get_room_id(session.matrix_room_name))
    else:
        return HttpResponseRedirect('/')

    if request.method == 'POST':  #If the user hit send button
        try:
            print("Posting chat")
            sys.stdout.flush()
            chat_form = ChatForm(request.POST)
            if chat_form.is_valid():
                response = api.send_message(
                    api.get_room_id(session.matrix_room_name),
                    chat_form.cleaned_data['text_entered'])
                chat_form = ChatForm()
                room_topic = api.get_room_topic(
                    api.get_room_id(session.matrix_room_name))['topic']
                messages.add_message(request, messages.INFO,
                                     session.matrix_user_name)
                synced = _get_messages(request,
                                       sync_token="end",
                                       direction='f')
                session.messages = json.dumps(synced['chunk'] +
                                              jsonDec.decode(session.messages))
                session.save()
                return render(
                    request, 'client_app/chat.html', {
                        'chat_form': chat_form,
                        'name': session.matrix_user_name,
                        'messages': jsonDec.decode(session.messages),
                        'room': session.matrix_room_name,
                        'topic': room_topic,
                        'show_images': session.show_images
                    })

        except MatrixRequestError as e:
            print(str(e))
            sys.stdout.flush()
            form = NameForm(request.POST)
            return render(request, 'client_app/login.html', {
                'form': form,
                'login_error': True,
                'error_text': str(e)
            })
        else:
            return render(
                request, 'client_app/chat.html', {
                    'chat_form': chat_form,
                    'name': session.matrix_user_name,
                    'messages': jsonDec.decode(session.messages),
                    'room': session.matrix_room_name,
                    'topic': room_topic,
                    'show_images': session.show_images
                })
    if update == "":  #If not asking for an update, get first sync to server
        try:
            chat_form = ChatForm()
            synced = api.sync()
            room_topic = api.get_room_topic(
                api.get_room_id(session.matrix_room_name))['topic']
            session.matrix_sync_token = synced["next_batch"]
            messages.add_message(request, messages.INFO,
                                 session.matrix_user_name)
            synced = _get_messages(request, sync_token="start", direction='b')
            session.messages = json.dumps(synced['chunk'])
            session.save()

        except MatrixRequestError as e:
            print(str(e))
            sys.stdout.flush()
            form = NameForm(request.POST)
            return render(request, 'client_app/login.html', {
                'form': form,
                'login_error': True
            })
        else:
            return render(
                request, 'client_app/chat.html', {
                    'chat_form': chat_form,
                    'name': session.matrix_user_name,
                    'messages': jsonDec.decode(session.messages),
                    'room': session.matrix_room_name,
                    'topic': room_topic,
                    'show_images': session.show_images
                })
    else:  # update is requested so return next messages using sync token from initial sync
        chat_form = ChatForm()
        room_topic = api.get_room_topic(
            api.get_room_id(session.matrix_room_name))['topic']
        messages.add_message(request, messages.INFO, session.matrix_user_name)
        synced = _get_messages(request, sync_token="end", direction='f')
        session.messages = json.dumps(synced['chunk'] +
                                      jsonDec.decode(session.messages))
        session.save()
        return render(
            request, 'client_app/chat.html', {
                'chat_form': chat_form,
                'name': session.matrix_user_name,
                'messages': jsonDec.decode(session.messages),
                'room': session.matrix_room_name,
                'topic': room_topic,
                'show_images': session.show_images
            })
Example #49
0
def get_messages_array(request):
    msgs = messages.get_messages(request)
    response = []
    for msg in msgs:
        response.append({'tags': msg.tags, 'message': msg.message})
    return response
Example #50
0
def clear_messages(request):
    storage = get_messages(request)
    for message in storage:  #removing all messages
        pass
Example #51
0
def showGoal(request):
    storage = messages.get_messages(request)
    storage.used = True
    import datetime
    today = datetime.date.today()
    if request.method == 'POST' and 'date_submit' in request.POST:
        # if request.method=='POST':
        print("hey")
        date_start = request.POST.get('date_start')
        date_end = request.POST.get('date_end')
        print(date_start)
        print(date_end)
        U_id = request.session.get("User_id")
        U_name = request.session["User_name"]

        if date_end > date_start:
            pass
        else:
            messages.error(request, "Please enter date properly")
            user_goal_details = goal.objects.filter(
                user_id=U_id, Active=False).order_by('Goal_deadline')
            user_goal_details2 = goal.objects.filter(
                user_id=U_id, Active=True).order_by('Goal_deadline')
            print(user_goal_details)
            return render(request, 'viewGoal.html', {
                'goals': user_goal_details,
                'goal_active': user_goal_details2
            })

        user_goal_details = goal.objects.filter(
            user_id=U_id, Goal_deadline__range=(date_start, date_end))
        user_goal_details2 = goal.objects.filter(
            user_id=U_id, Active=True).order_by('Goal_deadline')
        print(user_goal_details)
        U_name = request.session["User_name"]

        results2_u = {"current_user": U_name}

        results2_JSONu = json.dumps(results2_u)
        # return render(request,'viewExpenseStat.html',{'expenses': user_expenses_details,"dataval":results2_JSON})
        return render(
            request, 'viewGoal.html', {
                'goals': user_goal_details,
                'goal_active': user_goal_details2,
                'datavalu': results2_JSONu
            })

    else:
        print("HEYYYYYYYYYYY")
        U_id = request.session.get("User_id")
        user_goal_details = goal.objects.filter(
            user_id=U_id, Active=False).order_by('Goal_deadline')
        user_goal_details2 = goal.objects.filter(
            user_id=U_id, Active=True).order_by('Goal_deadline').annotate(
                rem=Cast(F('amount_till_now'), output_field=FloatField()) /
                Cast(F('Amount_to_save'), output_field=FloatField()))
        # user_goal_details2.rem=F('Amount_till_save')/F('amount_till_now')
        # user_goal_details2.save()
        print(user_goal_details2)
        # results2={
        #     "Goal_id":user_goal_details2.values('Goal_id'),
        #     "rem":user_goal_details2.values('rem')
        #     }
        # import datetime
        # import json

        U_name = request.session["User_name"]

        results2_u = {"current_user": U_name}

        results2_JSONu = json.dumps(results2_u)

        result_list = list(
            user_goal_details2.values('Goal_id', 'rem', 'Goal_name',
                                      'description', 'Amount_to_save',
                                      'Goal_deadline'))
        results2_JSON = json.dumps(result_list, default=default)
        return render(
            request, 'viewGoal.html', {
                'goals': user_goal_details,
                'goal_active': user_goal_details2,
                'dataval': results2_JSON,
                'datavalu': results2_JSONu
            })
Example #52
0
    def repository(self, request, **kwargs):
        obj = self.get_object()

        if isinstance(obj, Translation):
            project = obj.component.project
        elif isinstance(obj, Component):
            project = obj.project
        else:
            project = obj

        if request.method == "POST":
            serializer = RepoRequestSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)

            data = {
                "result":
                self.repository_operation(
                    request, obj, project,
                    serializer.validated_data["operation"])
            }

            storage = get_messages(request)
            if storage:
                data["detail"] = "\n".join(m.message for m in storage)

            return Response(data)

        if not request.user.has_perm("meta:vcs.status", project):
            raise PermissionDenied()

        data = {
            "needs_commit": obj.needs_commit(),
            "needs_merge": obj.repo_needs_merge(),
            "needs_push": obj.repo_needs_push(),
        }

        if isinstance(obj, Project):
            data["url"] = reverse("api:project-repository",
                                  kwargs={"slug": obj.slug},
                                  request=request)
        else:

            if isinstance(obj, Translation):
                component = obj.component
                data["url"] = reverse(
                    "api:translation-repository",
                    kwargs={
                        "component__project__slug": component.project.slug,
                        "component__slug": component.slug,
                        "language__code": obj.language.code,
                    },
                    request=request,
                )
            else:
                component = obj
                data["url"] = reverse(
                    "api:component-repository",
                    kwargs={
                        "project__slug": obj.project.slug,
                        "slug": obj.slug
                    },
                    request=request,
                )

            data["remote_commit"] = component.get_last_remote_commit()
            data["status"] = component.repository.status()
            changes = Change.objects.filter(
                action__in=Change.ACTIONS_REPOSITORY,
                component=component).order_by("-id")

            if changes.exists() and changes[0].is_merge_failure():
                data["merge_failure"] = changes[0].target
            else:
                data["merge_failure"] = None

        return Response(data)
Example #53
0
def student_dashboard(request):  # lint-amnesty, pylint: disable=too-many-statements
    """
    Provides the LMS dashboard view

    TODO: This is lms specific and does not belong in common code.
    Note:
        To load the all courses set course_limit=None as parameter in GET. If its not None then default course
        limit will be used  that is set in configuration
    Arguments:
        request: The request object.

    Returns:
        The dashboard response.

    """
    user = request.user
    if not UserProfile.objects.filter(user=user).exists():
        return redirect(reverse('account_settings'))

    platform_name = configuration_helpers.get_value("platform_name",
                                                    settings.PLATFORM_NAME)

    enable_verified_certificates = configuration_helpers.get_value(
        'ENABLE_VERIFIED_CERTIFICATES',
        settings.FEATURES.get('ENABLE_VERIFIED_CERTIFICATES'))
    display_course_modes_on_dashboard = configuration_helpers.get_value(
        'DISPLAY_COURSE_MODES_ON_DASHBOARD',
        settings.FEATURES.get('DISPLAY_COURSE_MODES_ON_DASHBOARD', True))
    activation_email_support_link = configuration_helpers.get_value(
        'ACTIVATION_EMAIL_SUPPORT_LINK',
        settings.ACTIVATION_EMAIL_SUPPORT_LINK) or settings.SUPPORT_SITE_LINK
    hide_dashboard_courses_until_activated = configuration_helpers.get_value(
        'HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED',
        settings.FEATURES.get('HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED', False))
    empty_dashboard_message = configuration_helpers.get_value(
        'EMPTY_DASHBOARD_MESSAGE', None)
    disable_unenrollment = configuration_helpers.get_value(
        'DISABLE_UNENROLLMENT', settings.FEATURES.get('DISABLE_UNENROLLMENT'))

    disable_course_limit = request and 'course_limit' in request.GET
    course_limit = get_dashboard_course_limit(
    ) if not disable_course_limit else None

    # Get the org whitelist or the org blacklist for the current site
    site_org_whitelist, site_org_blacklist = get_org_black_and_whitelist_for_site(
    )
    course_enrollments = list(
        get_course_enrollments(user, site_org_whitelist, site_org_blacklist,
                               course_limit))

    # Get the entitlements for the user and a mapping to all available sessions for that entitlement
    # If an entitlement has no available sessions, pass through a mock course overview object
    (course_entitlements, course_entitlement_available_sessions,
     unfulfilled_entitlement_pseudo_sessions
     ) = get_filtered_course_entitlements(user, site_org_whitelist,
                                          site_org_blacklist)

    # Record how many courses there are so that we can get a better
    # understanding of usage patterns on prod.
    monitoring_utils.accumulate('num_courses', len(course_enrollments))

    # Sort the enrollment pairs by the enrollment date
    course_enrollments.sort(key=lambda x: x.created, reverse=True)

    # Retrieve the course modes for each course
    enrolled_course_ids = [
        enrollment.course_id for enrollment in course_enrollments
    ]
    __, unexpired_course_modes = CourseMode.all_and_unexpired_modes_for_courses(
        enrolled_course_ids)
    course_modes_by_course = {
        course_id: {mode.slug: mode
                    for mode in modes}
        for course_id, modes in unexpired_course_modes.items()
    }

    # Check to see if the student has recently enrolled in a course.
    # If so, display a notification message confirming the enrollment.
    enrollment_message = _create_recent_enrollment_message(
        course_enrollments, course_modes_by_course)
    course_optouts = Optout.objects.filter(user=user).values_list('course_id',
                                                                  flat=True)

    # Display activation message
    activate_account_message = ''
    if not user.is_active:
        activate_account_message = Text(
            _("Check your {email_start}{email}{email_end} inbox for an account activation link from {platform_name}. "
              "If you need help, contact {link_start}{platform_name} Support{link_end}."
              )
        ).format(
            platform_name=platform_name,
            email_start=HTML("<strong>"),
            email_end=HTML("</strong>"),
            email=user.email,
            link_start=HTML(
                "<a target='_blank' href='{activation_email_support_link}'>").
            format(
                activation_email_support_link=activation_email_support_link, ),
            link_end=HTML("</a>"),
        )

    enterprise_message = get_dashboard_consent_notification(
        request, user, course_enrollments)

    recovery_email_message = recovery_email_activation_message = None
    if is_secondary_email_feature_enabled():
        try:
            pending_email = PendingSecondaryEmailChange.objects.get(user=user)  # lint-amnesty, pylint: disable=unused-variable
        except PendingSecondaryEmailChange.DoesNotExist:
            try:
                account_recovery_obj = AccountRecovery.objects.get(user=user)  # lint-amnesty, pylint: disable=unused-variable
            except AccountRecovery.DoesNotExist:
                recovery_email_message = Text(
                    _("Add a recovery email to retain access when single-sign on is not available. "
                      "Go to {link_start}your Account Settings{link_end}.")
                ).format(link_start=HTML(
                    "<a href='{account_setting_page}'>").format(
                        account_setting_page=reverse('account_settings'), ),
                         link_end=HTML("</a>"))
        else:
            recovery_email_activation_message = Text(
                _("Recovery email is not activated yet. "
                  "Kindly visit your email and follow the instructions to activate it."
                  ))

    # Disable lookup of Enterprise consent_required_course due to ENT-727
    # Will re-enable after fixing WL-1315
    consent_required_courses = set()

    # Account activation message
    account_activation_messages = [
        message for message in messages.get_messages(request)
        if 'account-activation' in message.tags
    ]

    # Global staff can see what courses encountered an error on their dashboard
    staff_access = False
    errored_courses = {}
    if has_access(user, 'staff', 'global'):
        # Show any courses that encountered an error on load
        staff_access = True
        errored_courses = modulestore().get_errored_courses()

    show_courseware_links_for = {
        enrollment.course_id: has_access(request.user, 'load',
                                         enrollment.course_overview)
        for enrollment in course_enrollments
    }

    # Find programs associated with course runs being displayed. This information
    # is passed in the template context to allow rendering of program-related
    # information on the dashboard.
    meter = ProgramProgressMeter(request.site,
                                 user,
                                 enrollments=course_enrollments)
    ecommerce_service = EcommerceService()
    inverted_programs = meter.invert_programs()

    urls, programs_data = {}, {}
    bundles_on_dashboard_flag = WaffleFlag(
        f'{EXPERIMENTS_NAMESPACE}.bundles_on_dashboard', __name__)  # lint-amnesty, pylint: disable=toggle-missing-annotation

    # TODO: Delete this code and the relevant HTML code after testing LEARNER-3072 is complete
    if bundles_on_dashboard_flag.is_enabled() and inverted_programs and list(
            inverted_programs.items()):
        if len(course_enrollments) < 4:
            for program in inverted_programs.values():
                try:
                    program_uuid = program[0]['uuid']
                    program_data = get_programs(uuid=program_uuid)
                    program_data = ProgramDataExtender(program_data,
                                                       request.user).extend()
                    skus = program_data.get('skus')
                    checkout_page_url = ecommerce_service.get_checkout_page_url(
                        *skus)
                    program_data[
                        'completeProgramURL'] = checkout_page_url + '&bundle=' + program_data.get(
                            'uuid')
                    programs_data[program_uuid] = program_data
                except:  # pylint: disable=bare-except
                    pass

    # Construct a dictionary of course mode information
    # used to render the course list.  We re-use the course modes dict
    # we loaded earlier to avoid hitting the database.
    course_mode_info = {
        enrollment.course_id: complete_course_mode_info(
            enrollment.course_id,
            enrollment,
            modes=course_modes_by_course[enrollment.course_id])
        for enrollment in course_enrollments
    }

    # Determine the per-course verification status
    # This is a dictionary in which the keys are course locators
    # and the values are one of:
    #
    # VERIFY_STATUS_NEED_TO_VERIFY
    # VERIFY_STATUS_SUBMITTED
    # VERIFY_STATUS_APPROVED
    # VERIFY_STATUS_MISSED_DEADLINE
    #
    # Each of which correspond to a particular message to display
    # next to the course on the dashboard.
    #
    # If a course is not included in this dictionary,
    # there is no verification messaging to display.
    verify_status_by_course = check_verify_status_by_course(
        user, course_enrollments)
    cert_statuses = {
        enrollment.course_id: cert_info(request.user, enrollment)
        for enrollment in course_enrollments
    }

    # only show email settings for Mongo course and when bulk email is turned on
    show_email_settings_for = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if (is_bulk_email_feature_enabled(enrollment.course_id)))

    # Verification Attempts
    # Used to generate the "you must reverify for course x" banner
    verification_status = IDVerificationService.user_status(user)
    verification_errors = get_verification_error_reasons_for_display(
        verification_status['error'])

    # Gets data for midcourse reverifications, if any are necessary or have failed
    statuses = ["approved", "denied", "pending", "must_reverify"]
    reverifications = reverification_info(statuses)

    enrolled_courses_either_paid = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.is_paid_course())

    # Checks if a course enrollment redeemed using a voucher is refundable
    enrolled_courses_voucher_refundable = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.is_order_voucher_refundable())

    # If there are *any* denied reverifications that have not been toggled off,
    # we'll display the banner
    denied_banner = any(item.display for item in reverifications["denied"])

    # get list of courses having pre-requisites yet to be completed
    courses_having_prerequisites = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.course_overview.pre_requisite_courses)
    courses_requirements_not_met = get_pre_requisite_courses_not_completed(
        user, courses_having_prerequisites)

    if 'notlive' in request.GET:
        redirect_message = _(
            "The course you are looking for does not start until {date}."
        ).format(date=request.GET['notlive'])
    elif 'course_closed' in request.GET:
        redirect_message = _(
            "The course you are looking for is closed for enrollment as of {date}."
        ).format(date=request.GET['course_closed'])
    elif 'access_response_error' in request.GET:
        # This can be populated in a generalized way with fields from access response errors
        redirect_message = request.GET['access_response_error']
    else:
        redirect_message = ''

    # Filter out any course enrollment course cards that are associated with fulfilled entitlements
    for entitlement in [
            e for e in course_entitlements
            if e.enrollment_course_run is not None
    ]:
        course_enrollments = [
            enr for enr in course_enrollments
            if entitlement.enrollment_course_run.course_id != enr.course_id
        ]

    show_account_activation_popup = request.COOKIES.get(
        settings.SHOW_ACTIVATE_CTA_POPUP_COOKIE_NAME, None)

    context = {
        'urls':
        urls,
        'programs_data':
        programs_data,
        'enterprise_message':
        enterprise_message,
        'consent_required_courses':
        consent_required_courses,
        'enrollment_message':
        enrollment_message,
        'redirect_message':
        Text(redirect_message),
        'account_activation_messages':
        account_activation_messages,
        'activate_account_message':
        activate_account_message,
        'course_enrollments':
        course_enrollments,
        'course_entitlements':
        course_entitlements,
        'course_entitlement_available_sessions':
        course_entitlement_available_sessions,
        'unfulfilled_entitlement_pseudo_sessions':
        unfulfilled_entitlement_pseudo_sessions,
        'course_optouts':
        course_optouts,
        'staff_access':
        staff_access,
        'errored_courses':
        errored_courses,
        'show_courseware_links_for':
        show_courseware_links_for,
        'all_course_modes':
        course_mode_info,
        'cert_statuses':
        cert_statuses,
        'credit_statuses':
        _credit_statuses(user, course_enrollments),
        'show_email_settings_for':
        show_email_settings_for,
        'reverifications':
        reverifications,
        'verification_display':
        verification_status['should_display'],
        'verification_status':
        verification_status['status'],
        'verification_expiry':
        verification_status['verification_expiry'],
        'verification_status_by_course':
        verify_status_by_course,
        'verification_errors':
        verification_errors,
        'denied_banner':
        denied_banner,
        'billing_email':
        settings.PAYMENT_SUPPORT_EMAIL,
        'show_account_activation_popup':
        show_account_activation_popup,
        'user':
        user,
        'logout_url':
        reverse('logout'),
        'platform_name':
        platform_name,
        'enrolled_courses_either_paid':
        enrolled_courses_either_paid,
        'enrolled_courses_voucher_refundable':
        enrolled_courses_voucher_refundable,
        'provider_states': [],
        'courses_requirements_not_met':
        courses_requirements_not_met,
        'nav_hidden':
        True,
        'inverted_programs':
        inverted_programs,
        'show_program_listing':
        ProgramsApiConfig.is_enabled(),
        'show_dashboard_tabs':
        True,
        'disable_courseware_js':
        True,
        'display_course_modes_on_dashboard':
        enable_verified_certificates and display_course_modes_on_dashboard,
        'display_sidebar_account_activation_message':
        not (user.is_active or hide_dashboard_courses_until_activated),
        'display_dashboard_courses':
        (user.is_active or not hide_dashboard_courses_until_activated),
        'empty_dashboard_message':
        empty_dashboard_message,
        'recovery_email_message':
        recovery_email_message,
        'recovery_email_activation_message':
        recovery_email_activation_message,
        'show_load_all_courses_link':
        show_load_all_courses_link(user, course_limit, course_enrollments),
        # TODO START: clean up as part of REVEM-199 (START)
        'course_info':
        get_dashboard_course_info(user, course_enrollments),
        # TODO START: clean up as part of REVEM-199 (END)
        'disable_unenrollment':
        disable_unenrollment,
    }

    # Include enterprise learner portal metadata and messaging
    enterprise_learner_portal_context = get_enterprise_learner_portal_context(
        request)
    context.update(enterprise_learner_portal_context)

    context_from_plugins = get_plugins_view_context(
        ProjectType.LMS, COURSE_DASHBOARD_PLUGIN_VIEW_NAME, context)
    context.update(context_from_plugins)

    notice_url = check_for_unacknowledged_notices(context)
    if notice_url:
        return redirect(notice_url)

    course = None
    context.update(get_experiment_user_metadata_context(
        course,
        user,
    ))
    if ecommerce_service.is_enabled(request.user):
        context.update({
            'use_ecommerce_payment_flow':
            True,
            'ecommerce_payment_page':
            ecommerce_service.payment_page_url(),
        })

    # Gather urls for course card resume buttons.
    resume_button_urls = ['' for entitlement in course_entitlements]
    for url in get_resume_urls_for_enrollments(user,
                                               course_enrollments).values():
        resume_button_urls.append(url)
    # There must be enough urls for dashboard.html. Template creates course
    # cards for "enrollments + entitlements".
    context.update({'resume_button_urls': resume_button_urls})

    dashboard_template = 'dashboard.html'
    try:
        # .. filter_implemented_name: DashboardRenderStarted
        # .. filter_type: org.openedx.learning.dashboard.render.started.v1
        context, dashboard_template = DashboardRenderStarted.run_filter(
            context=context,
            template_name=dashboard_template,
        )
    except DashboardRenderStarted.RenderInvalidDashboard as exc:
        response = render_to_response(exc.dashboard_template,
                                      exc.template_context)
    except DashboardRenderStarted.RedirectToPage as exc:
        response = HttpResponseRedirect(exc.redirect_to
                                        or reverse('account_settings'))
    except DashboardRenderStarted.RenderCustomResponse as exc:
        response = exc.response
    else:
        response = render_to_response(dashboard_template, context)

    if show_account_activation_popup:
        response.delete_cookie(
            settings.SHOW_ACTIVATE_CTA_POPUP_COOKIE_NAME,
            domain=settings.SESSION_COOKIE_DOMAIN,
            path='/',
        )

    return response
Example #54
0
def _third_party_auth_context(request, redirect_to, tpa_hint=None):
    """Context for third party auth providers and the currently running pipeline.

    Arguments:
        request (HttpRequest): The request, used to determine if a pipeline
            is currently running.
        redirect_to: The URL to send the user to following successful
            authentication.
        tpa_hint (string): An override flag that will return a matching provider
            as long as its configuration has been enabled

    Returns:
        dict

    """
    context = {
        "currentProvider": None,
        "providers": [],
        "secondaryProviders": [],
        "finishAuthUrl": None,
        "errorMessage": None,
        "registerFormSubmitButtonText": _("Create Account"),
        "syncLearnerProfileData": False,
        "pipeline_user_details": None
    }

    if third_party_auth.is_enabled():
        for enabled in third_party_auth.provider.Registry.displayed_for_login(tpa_hint=tpa_hint):
            info = {
                "id": enabled.provider_id,
                "name": enabled.name,
                "iconClass": enabled.icon_class or None,
                "iconImage": enabled.icon_image.url if enabled.icon_image else None,
                "loginUrl": pipeline.get_login_url(
                    enabled.provider_id,
                    pipeline.AUTH_ENTRY_LOGIN,
                    redirect_url=redirect_to,
                ),
                "registerUrl": pipeline.get_login_url(
                    enabled.provider_id,
                    pipeline.AUTH_ENTRY_REGISTER,
                    redirect_url=redirect_to,
                ),
            }
            context["providers" if not enabled.secondary else "secondaryProviders"].append(info)

        running_pipeline = pipeline.get(request)
        if running_pipeline is not None:
            current_provider = third_party_auth.provider.Registry.get_from_pipeline(running_pipeline)
            user_details = running_pipeline['kwargs']['details']
            if user_details:
                context['pipeline_user_details'] = user_details

            if current_provider is not None:
                context["currentProvider"] = current_provider.name
                context["finishAuthUrl"] = pipeline.get_complete_url(current_provider.backend_name)
                context["syncLearnerProfileData"] = current_provider.sync_learner_profile_data

                if current_provider.skip_registration_form:
                    # As a reliable way of "skipping" the registration form, we just submit it automatically
                    context["autoSubmitRegForm"] = True

        # Check for any error messages we may want to display:
        for msg in messages.get_messages(request):
            if msg.extra_tags.split()[0] == "social-auth":
                # msg may or may not be translated. Try translating [again] in case we are able to:
                context['errorMessage'] = _(unicode(msg))  # pylint: disable=translation-of-non-string
                break

    return context
Example #55
0
def _third_party_auth_context(request, redirect_to):
    """Context for third party auth providers and the currently running pipeline.

    Arguments:
        request (HttpRequest): The request, used to determine if a pipeline
            is currently running.
        redirect_to: The URL to send the user to following successful
            authentication.

    Returns:
        dict

    """
    context = {
        "currentProvider": None,
        "providers": [],
        "secondaryProviders": [],
        "finishAuthUrl": None,
        "errorMessage": None,
    }

    if third_party_auth.is_enabled():
        for enabled in third_party_auth.provider.Registry.displayed_for_login():
            info = {
                "id": enabled.provider_id,
                "name": enabled.name,
                "iconClass": enabled.icon_class or None,
                "iconImage": enabled.icon_image.url if enabled.icon_image else None,
                "loginUrl": pipeline.get_login_url(
                    enabled.provider_id,
                    pipeline.AUTH_ENTRY_LOGIN,
                    redirect_url=redirect_to,
                ),
                "registerUrl": pipeline.get_login_url(
                    enabled.provider_id,
                    pipeline.AUTH_ENTRY_REGISTER,
                    redirect_url=redirect_to,
                ),
            }
            context["providers" if not enabled.secondary else "secondaryProviders"].append(info)

        running_pipeline = pipeline.get(request)
        if running_pipeline is not None:
            current_provider = third_party_auth.provider.Registry.get_from_pipeline(running_pipeline)

            if current_provider is not None:
                context["currentProvider"] = current_provider.name
                context["finishAuthUrl"] = pipeline.get_complete_url(current_provider.backend_name)

                if current_provider.skip_registration_form:
                    # As a reliable way of "skipping" the registration form, we just submit it automatically
                    context["autoSubmitRegForm"] = True

        # Check for any error messages we may want to display:
        for msg in messages.get_messages(request):
            if msg.extra_tags.split()[0] == "social-auth":
                # msg may or may not be translated. Try translating [again] in case we are able to:
                context['errorMessage'] = _(unicode(msg))  # pylint: disable=translation-of-non-string
                break

    return context
Example #56
0
 def _should_update_cache(self, request, response):
     should = super(MessageAwareCacheMiddleware,
                    self)._should_update_cache(request, response)
     return should and not get_messages(request)
Example #57
0
def student_dashboard(request):
    """
    Provides the LMS dashboard view

    TODO: This is lms specific and does not belong in common code.

    Arguments:
        request: The request object.

    Returns:
        The dashboard response.

    """
    user = request.user
    if not UserProfile.objects.filter(user=user).exists():
        return redirect(reverse('account_settings'))

    platform_name = configuration_helpers.get_value("platform_name",
                                                    settings.PLATFORM_NAME)

    enable_verified_certificates = configuration_helpers.get_value(
        'ENABLE_VERIFIED_CERTIFICATES',
        settings.FEATURES.get('ENABLE_VERIFIED_CERTIFICATES'))
    display_course_modes_on_dashboard = configuration_helpers.get_value(
        'DISPLAY_COURSE_MODES_ON_DASHBOARD',
        settings.FEATURES.get('DISPLAY_COURSE_MODES_ON_DASHBOARD', True))
    activation_email_support_link = configuration_helpers.get_value(
        'ACTIVATION_EMAIL_SUPPORT_LINK',
        settings.ACTIVATION_EMAIL_SUPPORT_LINK) or settings.SUPPORT_SITE_LINK
    hide_dashboard_courses_until_activated = configuration_helpers.get_value(
        'HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED',
        settings.FEATURES.get('HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED', False))
    empty_dashboard_message = configuration_helpers.get_value(
        'EMPTY_DASHBOARD_MESSAGE', None)

    # Get the org whitelist or the org blacklist for the current site
    site_org_whitelist, site_org_blacklist = get_org_black_and_whitelist_for_site(
    )
    course_enrollments = list(
        get_course_enrollments(user, site_org_whitelist, site_org_blacklist))

    # Get the entitlements for the user and a mapping to all available sessions for that entitlement
    # If an entitlement has no available sessions, pass through a mock course overview object
    (course_entitlements, course_entitlement_available_sessions,
     unfulfilled_entitlement_pseudo_sessions
     ) = get_filtered_course_entitlements(user, site_org_whitelist,
                                          site_org_blacklist)

    # Record how many courses there are so that we can get a better
    # understanding of usage patterns on prod.
    monitoring_utils.accumulate('num_courses', len(course_enrollments))

    # Sort the enrollment pairs by the enrollment date
    course_enrollments.sort(key=lambda x: x.created, reverse=True)

    # Retrieve the course modes for each course
    enrolled_course_ids = [
        enrollment.course_id for enrollment in course_enrollments
    ]
    __, unexpired_course_modes = CourseMode.all_and_unexpired_modes_for_courses(
        enrolled_course_ids)
    course_modes_by_course = {
        course_id: {mode.slug: mode
                    for mode in modes}
        for course_id, modes in iteritems(unexpired_course_modes)
    }

    # Check to see if the student has recently enrolled in a course.
    # If so, display a notification message confirming the enrollment.
    enrollment_message = _create_recent_enrollment_message(
        course_enrollments, course_modes_by_course)
    course_optouts = Optout.objects.filter(user=user).values_list('course_id',
                                                                  flat=True)

    # Display activation message
    activate_account_message = ''
    if not user.is_active:
        activate_account_message = Text(
            _("Check your {email_start}{email}{email_end} inbox for an account activation link from {platform_name}. "
              "If you need help, contact {link_start}{platform_name} Support{link_end}."
              )
        ).format(
            platform_name=platform_name,
            email_start=HTML("<strong>"),
            email_end=HTML("</strong>"),
            email=user.email,
            link_start=HTML(
                "<a target='_blank' href='{activation_email_support_link}'>").
            format(
                activation_email_support_link=activation_email_support_link, ),
            link_end=HTML("</a>"),
        )

    enterprise_message = get_dashboard_consent_notification(
        request, user, course_enrollments)

    # Disable lookup of Enterprise consent_required_course due to ENT-727
    # Will re-enable after fixing WL-1315
    consent_required_courses = set()
    enterprise_customer_name = None

    # Account activation message
    account_activation_messages = [
        message for message in messages.get_messages(request)
        if 'account-activation' in message.tags
    ]

    # Global staff can see what courses encountered an error on their dashboard
    staff_access = False
    errored_courses = {}
    if has_access(user, 'staff', 'global'):
        # Show any courses that encountered an error on load
        staff_access = True
        errored_courses = modulestore().get_errored_courses()

    show_courseware_links_for = {
        enrollment.course_id: has_access(request.user, 'load',
                                         enrollment.course_overview)
        for enrollment in course_enrollments
    }

    # Find programs associated with course runs being displayed. This information
    # is passed in the template context to allow rendering of program-related
    # information on the dashboard.
    meter = ProgramProgressMeter(request.site,
                                 user,
                                 enrollments=course_enrollments)
    ecommerce_service = EcommerceService()
    inverted_programs = meter.invert_programs()

    urls, programs_data = {}, {}
    bundles_on_dashboard_flag = WaffleFlag(
        WaffleFlagNamespace(name=u'student.experiments'),
        u'bundles_on_dashboard')

    # TODO: Delete this code and the relevant HTML code after testing LEARNER-3072 is complete
    if bundles_on_dashboard_flag.is_enabled(
    ) and inverted_programs and inverted_programs.items():
        if len(course_enrollments) < 4:
            for program in inverted_programs.values():
                try:
                    program_uuid = program[0]['uuid']
                    program_data = get_programs(request.site,
                                                uuid=program_uuid)
                    program_data = ProgramDataExtender(program_data,
                                                       request.user).extend()
                    skus = program_data.get('skus')
                    checkout_page_url = ecommerce_service.get_checkout_page_url(
                        *skus)
                    program_data[
                        'completeProgramURL'] = checkout_page_url + '&bundle=' + program_data.get(
                            'uuid')
                    programs_data[program_uuid] = program_data
                except:  # pylint: disable=bare-except
                    pass

    # Construct a dictionary of course mode information
    # used to render the course list.  We re-use the course modes dict
    # we loaded earlier to avoid hitting the database.
    course_mode_info = {
        enrollment.course_id: complete_course_mode_info(
            enrollment.course_id,
            enrollment,
            modes=course_modes_by_course[enrollment.course_id])
        for enrollment in course_enrollments
    }

    # Determine the per-course verification status
    # This is a dictionary in which the keys are course locators
    # and the values are one of:
    #
    # VERIFY_STATUS_NEED_TO_VERIFY
    # VERIFY_STATUS_SUBMITTED
    # VERIFY_STATUS_APPROVED
    # VERIFY_STATUS_MISSED_DEADLINE
    #
    # Each of which correspond to a particular message to display
    # next to the course on the dashboard.
    #
    # If a course is not included in this dictionary,
    # there is no verification messaging to display.
    verify_status_by_course = check_verify_status_by_course(
        user, course_enrollments)
    cert_statuses = {
        enrollment.course_id: cert_info(request.user,
                                        enrollment.course_overview)
        for enrollment in course_enrollments
    }

    # only show email settings for Mongo course and when bulk email is turned on
    show_email_settings_for = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if (BulkEmailFlag.feature_enabled(enrollment.course_id)))

    # Verification Attempts
    # Used to generate the "you must reverify for course x" banner
    verification_status = IDVerificationService.user_status(user)
    verification_errors = get_verification_error_reasons_for_display(
        verification_status['error'])

    # Gets data for midcourse reverifications, if any are necessary or have failed
    statuses = ["approved", "denied", "pending", "must_reverify"]
    reverifications = reverification_info(statuses)

    block_courses = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if is_course_blocked(
            request,
            CourseRegistrationCode.objects.filter(
                course_id=enrollment.course_id,
                registrationcoderedemption__redeemed_by=request.user),
            enrollment.course_id))

    enrolled_courses_either_paid = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.is_paid_course())

    # If there are *any* denied reverifications that have not been toggled off,
    # we'll display the banner
    denied_banner = any(item.display for item in reverifications["denied"])

    # Populate the Order History for the side-bar.
    order_history_list = order_history(user,
                                       course_org_filter=site_org_whitelist,
                                       org_filter_out_set=site_org_blacklist)

    # get list of courses having pre-requisites yet to be completed
    courses_having_prerequisites = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.course_overview.pre_requisite_courses)
    courses_requirements_not_met = get_pre_requisite_courses_not_completed(
        user, courses_having_prerequisites)

    if 'notlive' in request.GET:
        redirect_message = _(
            "The course you are looking for does not start until {date}."
        ).format(date=request.GET['notlive'])
    elif 'course_closed' in request.GET:
        redirect_message = _(
            "The course you are looking for is closed for enrollment as of {date}."
        ).format(date=request.GET['course_closed'])
    elif 'access_response_error' in request.GET:
        # This can be populated in a generalized way with fields from access response errors
        redirect_message = request.GET['access_response_error']
    else:
        redirect_message = ''

    valid_verification_statuses = [
        'approved', 'must_reverify', 'pending', 'expired'
    ]
    display_sidebar_on_dashboard = (
        len(order_history_list)
        or (verification_status['status'] in valid_verification_statuses
            and verification_status['should_display']))

    # Filter out any course enrollment course cards that are associated with fulfilled entitlements
    for entitlement in [
            e for e in course_entitlements
            if e.enrollment_course_run is not None
    ]:
        course_enrollments = [
            enr for enr in course_enrollments
            if entitlement.enrollment_course_run.course_id != enr.course_id
        ]

    context = {
        'urls':
        urls,
        'programs_data':
        programs_data,
        'enterprise_message':
        enterprise_message,
        'consent_required_courses':
        consent_required_courses,
        'enterprise_customer_name':
        enterprise_customer_name,
        'enrollment_message':
        enrollment_message,
        'redirect_message':
        redirect_message,
        'account_activation_messages':
        account_activation_messages,
        'activate_account_message':
        activate_account_message,
        'course_enrollments':
        course_enrollments,
        'course_entitlements':
        course_entitlements,
        'course_entitlement_available_sessions':
        course_entitlement_available_sessions,
        'unfulfilled_entitlement_pseudo_sessions':
        unfulfilled_entitlement_pseudo_sessions,
        'course_optouts':
        course_optouts,
        'staff_access':
        staff_access,
        'errored_courses':
        errored_courses,
        'show_courseware_links_for':
        show_courseware_links_for,
        'all_course_modes':
        course_mode_info,
        'cert_statuses':
        cert_statuses,
        'credit_statuses':
        _credit_statuses(user, course_enrollments),
        'show_email_settings_for':
        show_email_settings_for,
        'reverifications':
        reverifications,
        'verification_display':
        verification_status['should_display'],
        'verification_status':
        verification_status['status'],
        'verification_status_by_course':
        verify_status_by_course,
        'verification_errors':
        verification_errors,
        'block_courses':
        block_courses,
        'denied_banner':
        denied_banner,
        'billing_email':
        settings.PAYMENT_SUPPORT_EMAIL,
        'user':
        user,
        'logout_url':
        reverse('logout'),
        'platform_name':
        platform_name,
        'enrolled_courses_either_paid':
        enrolled_courses_either_paid,
        'provider_states': [],
        'order_history_list':
        order_history_list,
        'courses_requirements_not_met':
        courses_requirements_not_met,
        'nav_hidden':
        True,
        'inverted_programs':
        inverted_programs,
        'show_program_listing':
        ProgramsApiConfig.is_enabled(),
        'show_journal_listing':
        journals_enabled(),  # TODO: Dashboard Plugin required
        'show_dashboard_tabs':
        True,
        'disable_courseware_js':
        True,
        'display_course_modes_on_dashboard':
        enable_verified_certificates and display_course_modes_on_dashboard,
        'display_sidebar_on_dashboard':
        display_sidebar_on_dashboard,
        'display_sidebar_account_activation_message':
        not (user.is_active or hide_dashboard_courses_until_activated),
        'display_dashboard_courses':
        (user.is_active or not hide_dashboard_courses_until_activated),
        'empty_dashboard_message':
        empty_dashboard_message,
    }

    if ecommerce_service.is_enabled(request.user):
        context.update({
            'use_ecommerce_payment_flow':
            True,
            'ecommerce_payment_page':
            ecommerce_service.payment_page_url(),
        })

    # Gather urls for course card resume buttons.
    resume_button_urls = ['' for entitlement in course_entitlements]
    for url in _get_urls_for_resume_buttons(user, course_enrollments):
        resume_button_urls.append(url)

    # eliteu membership
    if settings.FEATURES.get('ENABLE_MEMBERSHIP_INTEGRATION', False):
        from membership.models import VIPCourseEnrollment, VIPInfo
        vip_info = VIPInfo.objects.filter(user=user).order_by('-id').first()

        vces = VIPCourseEnrollment.objects.filter(user=user, is_active=True)
        vip_course_enrollment_ids = [v.course_id.html_id() for v in vces]

        context.update({
            'is_vip': VIPInfo.is_vip(user),
            'vip_expired_at': vip_info and vip_info.expired_at or None,
            'vip_purchase_url': reverse('membership_card'),
            'vip_course_enrollment_ids': vip_course_enrollment_ids,
            'display_sidebar_on_dashboard': True
        })

    # There must be enough urls for dashboard.html. Template creates course
    # cards for "enrollments + entitlements".
    context.update({'resume_button_urls': resume_button_urls})

    response = render_to_response('dashboard.html', context)
    set_deprecated_user_info_cookie(response, request, user)  # pylint: disable=protected-access
    return response
Example #58
0
 def create_page_context(self):
     page_context = page_contexts.FullPageContext()
     page_context.user = components.UserManager().parse_user(self.request)
     page_context.messages = messages.get_messages(self.request)
     page_context.messages.used = True
     return page_context
Example #59
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]
    try:
        user_orders = get_user_orders(user)
    except:  # pylint: disable=bare-except
        log.exception('Error fetching order history from Otto.')
        # Return empty order list as account settings page expect a list and
        # it will be broken if exception raised
        user_orders = []

    context = {
        'auth': {},
        'duplicate_provider': None,
        'nav_hidden': True,
        'fields': {
            'country': {
                'options': list(countries),
            }, 'gender': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'language': {
                'options': released_languages(),
            }, 'level_of_education': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'password': {
                'url': reverse('password_reset'),
            }, 'year_of_birth': {
                'options': year_of_birth_options,
            }, 'preferred_language': {
                'options': all_languages(),
            }, 'time_zone': {
                'options': TIME_ZONE_CHOICES,
            }
        },
        'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
        'password_reset_support_link': configuration_helpers.get_value(
            'PASSWORD_RESET_SUPPORT_LINK', settings.PASSWORD_RESET_SUPPORT_LINK
        ) or settings.SUPPORT_SITE_LINK,
        'user_accounts_api_url': reverse("accounts_api", kwargs={'username': user.username}),
        'user_preferences_api_url': reverse('preferences_api', kwargs={'username': user.username}),
        'disable_courseware_js': True,
        'show_program_listing': ProgramsApiConfig.is_enabled(),
        'show_dashboard_tabs': True,
        'order_history': user_orders,
        'extended_profile_fields': _get_extended_profile_fields(),
    }

    enterprise_customer = get_enterprise_customer_for_learner(site=request.site, user=request.user)
    update_account_settings_context_for_enterprise(context, enterprise_customer)

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context['duplicate_provider'] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context['auth']['providers'] = [{
            'id': state.provider.provider_id,
            'name': state.provider.name,  # The name of the provider e.g. Facebook
            'connected': state.has_account,  # Whether the user's edX account is connected with the provider.
            # If the user is not connected, they should be directed to this page to authenticate
            # with the particular provider, as long as the provider supports initiating a login.
            'connect_url': pipeline.get_login_url(
                state.provider.provider_id,
                pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                # The url the user should be directed to after the auth process has completed.
                redirect_url=reverse('account_settings'),
            ),
            'accepts_logins': state.provider.accepts_logins,
            # If the user is connected, sending a POST request to this url removes the connection
            # information for this provider from their edX account.
            'disconnect_url': pipeline.get_disconnect_url(state.provider.provider_id, state.association_id),
            # We only want to include providers if they are either currently available to be logged
            # in with, or if the user is already authenticated with them.
        } for state in auth_states if state.provider.display_for_login or state.has_account]

    return context
Example #60
0
def messages_view(request):
    """REST API view with Django messages."""
    return Response(
        serializers.MessageSerializer(get_messages(request), many=True).data,
        status=status.HTTP_200_OK
    )