Exemple #1
0
def finaid_download_csv(request):
    # Download financial aid application data as a .CSV file

    if not is_reviewer(request.user):
        return HttpResponseForbidden(_(u"Not authorized for this page"))

    # Fields to include
    application_field_names = ['id'] + [
        name for name in get_names_of_fields(FinancialAidApplication)
        if name not in ['id', 'review']
    ] + ['email', 'user']
    reviewdata_field_names = [
        name for name in get_names_of_fields(FinancialAidReviewData)
        if name not in ['application', 'id', 'last_update']
    ]

    # For these fields, use the get_FIELDNAME_display() method so we get
    # the name of the choice (or other custom string) instead of the internal value
    use_display_method = [
        'cash_check',
        'last_update',
        'presenting',
        'status',
        'travel_cash_check',
    ]

    def get_value(name, object):
        # Get a value from an application or review, using get_NAME_display
        # if appropriate, then forcing to a unicode string and encoding in
        # UTF-8 for CSV
        if name in use_display_method:
            display_method = getattr(object, "get_%s_display" % name)
            value = display_method()
        elif name == 'email':
            value = object.user.email
        else:
            value = getattr(object, name)
        return unicode(value).encode('utf-8')

    response = HttpResponse(content_type='text/csv')
    response[
        'Content-Disposition'] = 'attachment; filename="financial_aid.csv"'

    writer = csv.DictWriter(response,
                            fieldnames=application_field_names +
                            reviewdata_field_names)
    writer.writeheader()

    default_review_data = FinancialAidReviewData()
    apps = FinancialAidApplication.objects.all().select_related('review')
    for application in apps.order_by('pk'):
        # They won't all have review data, so use the default values if they don't
        try:
            review = application.review
        except FinancialAidReviewData.DoesNotExist:
            review = default_review_data

        # Write the data for this application.
        data = {}
        for name in application_field_names:
            data[name] = get_value(name, application)
        for name in reviewdata_field_names:
            data[name] = get_value(name, review)
        writer.writerow(data)

    return response
Exemple #2
0
def finaid_review(request, pks=None):
    """Starting view for reviewers - list the applications"""
    # On a POST the pks are in the form.
    # On a GET there might be pks in the URL.

    if not is_reviewer(request.user):
        return HttpResponseForbidden(_(u"Not authorized for this page"))

    if request.method == 'POST':
        # They want to do something to bulk applicants
        # Find the checkboxes they checked
        regex = re.compile(r'^finaid_application_(.*)$')
        pk_list = []
        for field_name in request.POST:
            m = regex.match(field_name)
            if m:
                pk_list.append(m.group(1))
        if not pk_list:
            messages.add_message(request, messages.ERROR,
                                 _(u"Please select at least one application"))
            return redirect(request.path)

        if 'email_action' in request.POST:
            # They want to email applicants
            pks = ",".join(pk_list)
            return redirect('finaid_email', pks=pks)
        elif 'message_action' in request.POST:
            # They want to attach a message to applications
            pks = ",".join(pk_list)
            return redirect('finaid_message', pks=pks)
        elif 'status_action' in request.POST:
            # They want to change applications' statuses
            applications = FinancialAidApplication.objects.filter(pk__in=pk_list)\
                .select_related('review')
            status = int(request.POST['status'])
            count = 0
            for application in applications:
                try:
                    review = application.review
                except FinancialAidReviewData.DoesNotExist:
                    review = FinancialAidReviewData(application=application)
                if review.status != status:
                    review.status = status
                    review.save()
                    count += 1
            messages.info(
                request, "Updated %d application status%s" %
                (count, "" if count == 1 else "es"))
            pks = ",".join(pk_list)
            return redirect(reverse('finaid_review', kwargs=dict(pks=pks)))
        else:
            messages.error(request, "WHAT?")
    else:
        # GET - pks are in the URL.  maybe.
        pk_list = pks.split(",") if pks else []

    return render(
        request, "finaid/application_list.html", {
            "applications":
            FinancialAidApplication.objects.all().select_related('review'),
            "status_options":
            STATUS_CHOICES,
            "pks": [int(pk) for pk in pk_list],
        })
Exemple #3
0
 def put(self, request, application_id):
     if not request.user.is_staff and not request.user.is_superuser:
         return HttpResponseForbidden()
     html = request.data["html"]
     pdf_content = self.generate_pdf(html)
     return self.create_download_response(pdf_content)
Exemple #4
0
def finaid_review_detail(request, pk):
    """Review a particular application"""
    application = get_object_or_404(FinancialAidApplication, pk=pk)

    # Redirect a a reviewer who is attempting to access FA application detail
    # page to their edit page
    if is_reviewer(request.user) and request.user == application.user:
        return redirect("finaid_edit")

    if not is_reviewer(request.user):
        # Redirect a non reviewer to their FA edit page
        if has_application(request.user):
            return redirect("finaid_edit")
        return HttpResponseForbidden(_(u"Not authorized for this page"))

    try:
        review_data = application.review
    except FinancialAidReviewData.DoesNotExist:
        review_data = FinancialAidReviewData(application=application)

    message_form = None
    review_form = None

    if request.method == 'POST':
        if 'message_submit' in request.POST:
            message = FinancialAidMessage(user=request.user,
                                          application=application)
            message_form = ReviewerMessageForm(request.POST, instance=message)
            if message_form.is_valid():
                message = message_form.save()
                # Send notice to the reviewers alias
                # If the message is visible, also send to the applicant
                context = email_context(request, application, message)
                # Notify reviewers
                send_email_message("reviewer/message",
                                   from_=request.user.email,
                                   to=[email_address()],
                                   context=context)
                # If visible to applicant, notify them as well
                if message.visible:
                    send_email_message("applicant/message",
                                       from_=request.user.email,
                                       to=[application.user.email],
                                       context=context)
                messages.add_message(
                    request, messages.INFO,
                    _(u"Message has been added to the application, "
                      u"and recipients notified by email."))
                return redirect(request.path)
        elif 'review_submit' in request.POST:
            review_form = FinancialAidReviewForm(request.POST,
                                                 instance=review_data)
            if review_form.is_valid():
                review_data = review_form.save()
                return redirect(reverse("finaid_review"))
        else:
            log.error("finaid_review_detail posted with unknown form: %r" %
                      request.POST)
            return HttpResponseForbidden("HEY WHY WAS THIS POSTED")

    # Create initial forms if needed
    message_form = message_form or ReviewerMessageForm()
    review_form = review_form or FinancialAidReviewForm(instance=review_data)

    context = {
        "application":
        application,
        "message_form":
        message_form,
        "review_form":
        review_form,
        "review_messages":
        FinancialAidMessage.objects.filter(application=application)
    }
    return render(request, "finaid/review.html", context)
Exemple #5
0
 def post(self, request, *args, **kwargs):
     if request.user.is_authenticated:
         return HttpResponseForbidden()
     return super().post(self, request, *args, **kwargs)
Exemple #6
0
 def __call__(self, request):
     auth_header = request.META.get("HTTP_AUTHORIZATION", None)
     webtoken = request.GET.get("webtoken", None)
     if auth_header or webtoken:
         try:
             if auth_header:
                 auth = auth_header.split()
                 authmethod = auth[0].lower()
             else:
                 authmethod = None
             if authmethod == "basic":
                 # Basic authentication
                 auth = base64.b64decode(
                     auth[1]).decode("iso-8859-1").partition(":")
                 user = authenticate(username=auth[0], password=auth[2])
                 if user and user.is_active:
                     # Active user
                     request.api = True  # TODO I think this is no longer used
                     login(request, user)
                     request.user = user
             elif authmethod == "bearer" or webtoken:
                 # JWT webtoken authentication
                 decoded = None
                 for secret in (
                         getattr(settings, "AUTH_SECRET_KEY", None),
                         settings.DATABASES[request.database].get(
                             "SECRET_WEBTOKEN_KEY", settings.SECRET_KEY),
                 ):
                     if secret:
                         try:
                             decoded = jwt.decode(
                                 webtoken or auth[1],
                                 secret,
                                 algorithms=["HS256"],
                             )
                         except jwt.exceptions.InvalidTokenError:
                             pass
                 if not decoded:
                     logger.error("Missing or invalid webtoken")
                     return HttpResponseForbidden(
                         "Missing or invalid webtoken")
                 try:
                     if "user" in decoded:
                         user = User.objects.get(username=decoded["user"])
                     elif "email" in decoded:
                         user = User.objects.get(email=decoded["email"])
                     else:
                         logger.error("No user or email in webtoken")
                         return HttpResponseForbidden(
                             "No user or email in webtoken")
                 except User.DoesNotExist:
                     logger.error("Invalid user in webtoken")
                     messages.add_message(request, messages.ERROR,
                                          "Unknown user")
                     return HttpResponseRedirect("/data/login/")
                 user.backend = settings.AUTHENTICATION_BACKENDS[0]
                 login(request, user)
                 MultiDBBackend.getScenarios(user)
                 request.user = user
                 if not decoded.get("navbar", True):
                     request.session["navbar"] = False
                 if decoded.get("xframe_options_exempt", True):
                     request.session["xframe_options_exempt"] = True
         except Exception as e:
             logger.warn(
                 "silently ignoring exception in http authentication: %s" %
                 e)
     response = self.get_response(request)
     return response
Exemple #7
0
    def post(self, request, *args, **kwargs):
        data = {}
        if hasattr(request, 'POST'):
            data = request.POST
        elif hasattr(request, 'DATA'):
            data = request.DATA
        allow = False

        # Check permissions
        username = data.get('username')
        client_id = data.get('clientid')
        acc = int(data.get('acc'))  # 1 == sub, 2 == pub

        # get topic and remove first '/'
        topic = data.get('topic').split('/')
        if len(topic) > 0 and topic[0] == '':
            del topic[0]

        try:

            # get user
            user = User.objects.get(username=data.get('username'),
                                    is_active=True)

            #print('topic = {}'.format(topic))
            #print('user = {}'.format(user))
            #print('user.hospitals = {}'.format(user.hospitals.all()))

            if acc == 1:

                # permission to subscribe:

                #  - settings
                if (len(topic) == 1 and topic[0] == 'settings'):

                    return HttpResponse('OK')

                #  - user/{username}/error
                #  - user/{username}/profile
                elif (len(topic) == 3 and topic[0] == 'user'
                      and topic[1] == user.username):

                    if (topic[2] == 'profile' or topic[2] == 'error'):

                        return HttpResponse('OK')

                #  - hospital/{hospital-id}/data
                #  - hospital/{hospital-id}/metadata
                #  - hospital/{hospital-id}/equipment/+/data
                elif (len(topic) >= 3 and topic[0] == 'hospital'):

                    hospital_id = int(topic[1])
                    #print('hospital_id = {}'.format(hospital_id))

                    # is user authorized?
                    try:

                        perm = user.profile.hospitals.get(hospital=hospital_id)

                        if (perm.can_read and
                            ((len(topic) == 3 and topic[2] == 'data') or
                             (len(topic) == 3 and topic[2] == 'metadata') or
                             (len(topic) == 5 and topic[2] == 'equipment'
                              and topic[4] == 'data'))):

                            return HttpResponse('OK')

                    except ObjectDoesNotExist:
                        pass

                #  - ambulance/{ambulance-id}/data
                elif (len(topic) == 3 and topic[0] == 'ambulance'
                      and topic[2] == 'data'):

                    ambulance_id = int(topic[1])
                    #print('ambulance_id = {}'.format(ambulance_id))

                    # is user authorized?
                    try:

                        perm = user.profile.ambulances.get(
                            ambulance=ambulance_id)

                        if perm.can_read:

                            return HttpResponse('OK')

                    except ObjectDoesNotExist:
                        pass

            elif acc == 2:

                # permission to publish:

                if (len(topic) >= 3 and topic[0] == 'user'
                        and topic[1] == user.username):

                    #  - user/{username}/error
                    if (len(topic) == 3 and topic[2] == 'error'):

                        return HttpResponse('OK')

                    #  - user/{username}/ambulance/{ambulance-id}/data
                    elif (len(topic) == 5 and topic[2] == 'ambulance'
                          and topic[4] == 'data'):

                        ambulance_id = int(topic[3])
                        #print('ambulance_id = {}'.format(ambulance_id))

                        # is user authorized?
                        try:

                            perm = user.profile.ambulances.get(
                                ambulance=ambulance_id)

                            if perm.can_write:

                                return HttpResponse('OK')

                        except ObjectDoesNotExist:
                            pass

                    #  - user/{username}/hospital/{hospital-id}/data
                    #  - user/{username}/hospital/{hospital-id}/equipment/+/data
                    elif (
                        (len(topic) == 5 and topic[2] == 'hospital'
                         and topic[4] == 'data') or
                        (len(topic) == 7 and topic[2] == 'hospital'
                         and topic[4] == 'equipment' and topic[6] == 'data')):

                        hospital_id = int(topic[3])
                        #print('hospital_id = {}'.format(hospital_id))

                        # is user authorized?
                        try:

                            perm = user.profile.hospitals.get(
                                hospital=hospital_id)

                            if perm.can_write:

                                return HttpResponse('OK')

                        except ObjectDoesNotExist:
                            pass

                    #  - user/{username}/client/{client-id}/status
                    elif (len(topic) == 5 and topic[2] == 'client'
                          and topic[4] == 'status' and topic[3] == client_id):

                        return HttpResponse('OK')

        except User.DoesNotExist:
            pass

        return HttpResponseForbidden()
Exemple #8
0
 def delete_detail(self, object_list, bundle):
     if not self.delete_list(object_list, bundle).filter(pk=bundle.obj.pk).exists():
         raise ImmediateHttpResponse(HttpResponseForbidden('you have no permission to delete flows'))
     return True
Exemple #9
0
def container_post(request):
    '''
    Proxies the grading result from inside container to A+
    '''
    sid = request.POST.get("sid", None)
    if not sid:
        return HttpResponseForbidden("Missing sid")

    meta = read_and_remove_submission_meta(sid)
    if meta is None:
        return HttpResponseForbidden("Invalid sid")
    #clean_submission_dir(meta["dir"])

    data = {
        "points": int(request.POST.get("points", 0)),
        "max_points": int(request.POST.get("max_points", 1)),
    }
    for key in ["error", "grading_data"]:
        if key in request.POST:
            data[key] = request.POST[key]
    if "error" in data and data["error"].lower() in ("no", "false"):
        del data["error"]

    feedback = request.POST.get("feedback", "")
    # Fetch the corresponding exercise entry from the config.
    lang = meta["lang"]
    (course, exercise) = config.exercise_entry(meta["course_key"],
                                               meta["exercise_key"],
                                               lang=lang)
    if "feedback_template" in exercise:
        # replace the feedback with a rendered feedback template if the exercise is configured to do so
        # it is not feasible to support all of the old feedback template variables that runactions.py
        # used to have since the grading actions are not configured in the exercise YAML file anymore
        required_fields = {'points', 'max_points', 'error', 'out'}
        result = MonitoredDict({
            "points": data["points"],
            "max_points": data["max_points"],
            "out": feedback,
            "error": data.get("error", False),
            "title": exercise.get("title", ""),
        })
        translation.activate(lang)
        feedback = template_to_str(course,
                                   exercise,
                                   None,
                                   exercise["feedback_template"],
                                   result=result)
        if result.accessed.isdisjoint(required_fields):
            alert = template_to_str(
                course, exercise, None,
                "access/feedback_template_did_not_use_result_alert.html")
            feedback = alert + feedback
        # Make unicode results ascii.
        feedback = feedback.encode("ascii", "xmlcharrefreplace")

    data["feedback"] = feedback

    if not post_data(meta["url"], data):
        write_submission_meta(sid, meta)
        return HttpResponse("Failed to deliver results", status=502)
    return HttpResponse("Ok")
Exemple #10
0
def dashboard_index(request):
    if not request.user.has_perm("django_sql_dashboard.execute_sql"):
        return HttpResponseForbidden(
            "You do not have permission to execute SQL")
    sql_queries = []
    too_long_so_use_post = False
    save_form = SaveDashboardForm(prefix="_save")
    if request.method == "POST":
        # Is this an export?
        if any(k for k in request.POST.keys() if k.startswith("export_")
               ) and request.user.has_perm("django_sql_dashboard.execute_sql"):
            if not getattr(settings, "DASHBOARD_ENABLE_FULL_EXPORT", None):
                return HttpResponseForbidden(
                    "The export feature is not enabled")
            return export_sql_results(request)
        sqls = [sql for sql in request.POST.getlist("sql") if sql.strip()]

        saving = False
        # How about a save?
        if request.POST.get("_save-slug"):
            save_form = SaveDashboardForm(request.POST, prefix="_save")
            saving = True
            if save_form.is_valid():
                dashboard = save_form.save(commit=False)
                dashboard.owned_by = request.user
                dashboard.save()
                for sql in sqls:
                    dashboard.queries.create(sql=sql)
                return HttpResponseRedirect(dashboard.get_absolute_url())

        # Convert ?sql= into signed values and redirect as GET
        other_pairs = [
            (key, value) for key, value in request.POST.items() if key not in (
                "sql", "csrfmiddlewaretoken") and not key.startswith("_save-")
        ]
        signed_sqls = [sign_sql(sql) for sql in sqls if sql.strip()]
        params = {
            "sql": signed_sqls,
        }
        params.update(other_pairs)
        redirect_path = request.path + "?" + urlencode(params, doseq=True)
        # Is this short enough for us to redirect?
        too_long_so_use_post = len(redirect_path) > MAX_REDIRECT_LENGTH
        if not saving and not too_long_so_use_post:
            return HttpResponseRedirect(redirect_path)
        else:
            sql_queries = sqls
    unverified_sql_queries = []
    for signed_sql in request.GET.getlist("sql"):
        sql, signature_verified = unsign_sql(signed_sql)
        if signature_verified:
            sql_queries.append(sql)
        else:
            unverified_sql_queries.append(sql)
    if getattr(settings, "DASHBOARD_UPGRADE_OLD_BASE64_LINKS", None):
        redirect_querystring = check_for_base64_upgrade(sql_queries)
        if redirect_querystring:
            return HttpResponseRedirect(request.path + redirect_querystring)
    return _dashboard_index(
        request,
        sql_queries,
        unverified_sql_queries=unverified_sql_queries,
        too_long_so_use_post=too_long_so_use_post,
        extra_context={"save_form": save_form},
    )
Exemple #11
0
    def post(self, request):
        user = request.user
        data = copy.deepcopy(request.data)
        # Now, we post the data directly to OSM.
        try:
            # Split osm and extension attribute
            osm_attr, locality_attr = split_osm_and_extension_attr(data['tag'])
            data['tag'] = osm_attr

            # Verify data uploader and owner/collector if the API is being used
            # for uploading data from other osm user.
            if request.user.is_staff and request.GET.get('review', None):
                data['osm_user'] = get_pending_review(
                    request.GET.get('review')).uploader.username

            if data.get('osm_user'):
                is_valid, message = verify_user(user, data['osm_user'])
                if not is_valid:
                    return HttpResponseForbidden(message)
                else:
                    try:
                        user = get_object_or_404(User,
                                                 username=data['osm_user'])
                    except Http404:
                        message = 'User %s is not exist.' % data['osm_user']
                        return HttpResponseForbidden(message)

            duplication_check = request.GET.get('duplication-check', True)
            if duplication_check == 'false':
                duplication_check = False
            validate_osm_data(data, duplication_check=duplication_check)

            # Map Healthsites tags to OSM tags
            mapping_file_path = ABS_PATH('api', 'fixtures', 'mapping.yml')
            data['tag'] = convert_to_osm_tag(mapping_file_path, data['tag'],
                                             'node')

            # Push data to OSM
            response = create_osm_node(user, data)

            # create pending index
            create_pending_update('node', response['id'], data['tag']['name'],
                                  user, response['version'])

            save_extensions('node', response['id'], locality_attr)

            if request.GET.get('review', None):
                delete_pending_review(request.GET.get('review', None))
            return Response(response)

        except Exception as e:
            if not request.GET.get('review', None):
                if user != request.user:
                    create_pending_review(user, request.data, '%s' % e)
            else:
                try:
                    update_pending_review(request.GET.get('review', None),
                                          request.data, '%s' % e)
                except Exception as e:
                    return HttpResponseBadRequest('%s' % e)
            output = {
                'error': '%s' % e,
                'payload': request.data,
            }
            return HttpResponseBadRequest('%s' % json.dumps(output))
Exemple #12
0
def task(request, contest_id, task_id):
    contest = get_object_or_404(models.TaskBasedContest, pk=contest_id)
    if not contest.is_visible_in_list and not request.user.is_staff:
        return HttpResponseNotFound()

    task = get_object_or_404(tasks_models.Task, pk=task_id)
    if not contest.has_task(task):
        return HttpResponseNotFound()

    if not contest.is_started() and not request.user.is_staff:
        return HttpResponseForbidden('Contest is not started')

    participant = contest.get_participant_for_user(request.user)

    if not is_task_open(contest, task,
                        participant) and not request.user.is_staff:
        return HttpResponseForbidden('Task is closed')

    if request.method == 'POST' and request.user.is_authenticated():
        form = tasks_forms.AttemptForm(data=request.POST)

        if participant is None:
            messages.warning(request, 'You are not registered to the contest')
        elif participant.is_disqualified:
            messages.error(request, 'You are disqualified from the contest')
        elif get_count_attempts_in_last_minute(
                contest, participant) >= settings.DRAPO_MAX_TRIES_IN_MINUTE:
            messages.error(request, 'Too fast, try later')
        elif contest.is_finished():
            messages.error(request,
                           'Contest is finished! You are too late, sorry')
        elif form.is_valid():
            answer = form.cleaned_data['answer']
            attempt = tasks_models.Attempt(
                contest=contest,
                task=task,
                participant=contest.get_participant_for_user(request.user),
                author=request.user,
                answer=answer)
            attempt.save()

            attempt.try_to_check()

            if not attempt.is_checked:
                messages.info(request, 'We will check you answer, thank you')
            elif attempt.is_correct:
                messages.success(request, 'Yeah! Correct answer!')
            else:
                messages.error(request, 'Wrong answer, sorry')

            return redirect(
                urlresolvers.reverse('contests:task',
                                     args=[contest.id, task.id]))
    else:
        form = tasks_forms.AttemptForm()

    statement_generator = task.statement_generator
    if request.user.is_anonymous(
    ) and not statement_generator.is_available_for_anonymous():
        messages.error(
            request, 'This task is not available for guests. Please sign in')
        return redirect(
            urlresolvers.reverse('contests:tasks', args=[contest.id]))

    statement = statement_generator.generate({
        'user': request.user,
        'participant': participant
    })

    # Files can be in statement or in task for this participant
    files = statement.files + list(
        task.files.filter(
            Q(participant__isnull=True) | Q(participant=participant)))

    participant_score = max(task.attempts.filter(contest=contest_id,
                                                 participant=participant,
                                                 is_checked=True).values_list(
                                                     'score', flat=True),
                            default=None)

    return render(
        request, 'contests/task.html', {
            'current_contest': contest,
            'contest': contest,
            'task': task,
            'statement': statement,
            'files': files,
            'attempt_form': form,
            'participant': participant,
            'participant_score': participant_score,
        })
Exemple #13
0
 def read_detail(self, object_list, bundle):
     if bundle.obj not in self.read_list(object_list, bundle):
         raise ImmediateHttpResponse(HttpResponseForbidden(
             'you have no permission to read %s' % bundle.obj.__class__.__name__
         ))
     return True
Exemple #14
0
def view_user_timesheet(request, user_id, active_tab):
    user = get_object_or_404(User, pk=user_id)
    has_perm = request.user.has_perm('entries.view_entry_summary')
    if not (has_perm or user.pk == request.user.pk):
        return HttpResponseForbidden('Forbidden')

    FormClass = UserYearMonthForm if has_perm else YearMonthForm
    form = FormClass(request.GET or None)
    if form.is_valid():
        if has_perm:
            from_date, to_date, form_user = form.save()
            if form_user and request.GET.get('yearmonth', None):
                url = reverse('view_user_timesheet', args=(form_user.pk, ))
                request_data = {
                    'month': from_date.month,
                    'year': from_date.year,
                    'user': form_user.pk,
                }
                url += '?{0}'.format(urlencode(request_data))
                return HttpResponseRedirect(url)
        else:
            from_date, to_date = form.save()
        from_date = add_timezone(from_date)
        to_date = add_timezone(to_date)
    else:
        # from_date = get_month_start()
        # to_date = from_date + relativedelta(months=1)
        from_date = Entry.objects.last().start_time
        to_date = datetime.datetime.today()

    entries_qs = Entry.objects.filter(user=user)
    if form.is_valid():
        month_qs = entries_qs.timespan(from_date, span='month')
    else:
        month_qs = entries_qs.timespan(from_date)
    extra_values = ('start_time', 'end_time', 'comments', 'seconds_paused',
                    'id', 'location__name', 'project__name', 'activity__name',
                    'status')
    month_entries = month_qs.date_trunc('month',
                                        extra_values).order_by('start_time')
    entry_ids = month_entries.values_list('id', flat=True)
    tasks = TaskList.objects.filter(entry_id__in=entry_ids).values(
        'entry_id', 'tasks').order_by('entry_id')
    task_values = [
        tasks.get(entry_id=entry_id)['tasks']
        if entry_id in tasks.values_list('entry_id', flat=True) else ''
        for entry_id in entry_ids
    ]
    first_week = get_week_start(from_date)
    month_week = first_week + relativedelta(weeks=1)
    grouped_qs = entries_qs.timespan(first_week, to_date=to_date)
    intersection = grouped_qs.filter(start_time__lt=month_week,
                                     start_time__gte=from_date)
    if not intersection and first_week.month < from_date.month:
        grouped_qs = entries_qs.timespan(from_date, to_date=to_date)
    totals = grouped_totals(grouped_qs) if month_entries else ''
    project_entries = month_qs.order_by().values('project__name').annotate(
        sum=Sum('hours')).order_by('-sum')
    summary = Entry.summary(user, from_date, to_date)

    show_approve = show_verify = False
    can_change = request.user.has_perm('entries.can_change_entry')
    can_approve = request.user.has_perm('entries.approve_timesheet')
    if can_change or can_approve or user == request.user:
        statuses = list(month_qs.values_list('status', flat=True))
        total_statuses = len(statuses)
        unverified_count = statuses.count(Entry.UNVERIFIED)
        verified_count = statuses.count(Entry.VERIFIED)
        approved_count = statuses.count(Entry.APPROVED)
    if can_change or user == request.user:
        show_verify = unverified_count != 0
    if can_approve:
        show_approve = all([
            verified_count + approved_count == total_statuses,
            verified_count > 0,
            total_statuses != 0,
        ])

        return render(
            request, 'user/timesheet_view.html', {
                'active_tab': active_tab or 'overview',
                'year_month_form': form,
                'from_date': from_date,
                'to_date': to_date - relativedelta(days=1),
                'show_verify': show_verify,
                'show_approve': show_approve,
                'timesheet_user': user,
                'entries': zip(month_entries, task_values),
                'grouped_totals': totals,
                'project_entries': project_entries,
                'summary': summary
            })
Exemple #15
0
 def form_invalid(self, form):
     return HttpResponseForbidden()
Exemple #16
0
def gym_permissions_user_edit(request, user_pk):
    """
    Edits the permissions of a gym member
    """
    member = get_object_or_404(User, pk=user_pk)
    user = request.user

    if not user.is_authenticated:
        return HttpResponseForbidden()

    if not user.has_perm('gym.manage_gyms') and not user.has_perm('gym.manage_gym'):
        return HttpResponseForbidden()

    if user.has_perm('gym.manage_gym') and user.userprofile.gym != member.userprofile.gym:
        return HttpResponseForbidden()

    # Calculate available user permissions
    form_group_permission = get_permission_list(user)

    if request.method == 'POST':
        form = GymUserPermissionForm(available_roles=form_group_permission,
                                     data=request.POST)

        if form.is_valid():

            # Remove the user from all gym permission groups
            member.groups.remove(Group.objects.get(name='gym_member'))
            member.groups.remove(Group.objects.get(name='gym_trainer'))
            member.groups.remove(Group.objects.get(name='gym_manager'))
            member.groups.remove(Group.objects.get(name='general_gym_manager'))

            # Set appropriate permission groups
            if 'user' in form.cleaned_data['role']:
                member.groups.add(Group.objects.get(name='gym_member'))
            if 'trainer' in form.cleaned_data['role']:
                member.groups.add(Group.objects.get(name='gym_trainer'))
            if 'admin' in form.cleaned_data['role']:
                member.groups.add(Group.objects.get(name='gym_manager'))
            if 'manager' in form.cleaned_data['role']:
                member.groups.add(Group.objects.get(name='general_gym_manager'))

            return HttpResponseRedirect(reverse('gym:gym:user-list',
                                                kwargs={'pk': member.userprofile.gym.pk}))
    else:
        initial_data = {}
        if member.groups.filter(name='gym_member').exists():
            initial_data['user'] = True

        if member.groups.filter(name='gym_trainer').exists():
            initial_data['trainer'] = True

        if member.groups.filter(name='gym_manager').exists():
            initial_data['admin'] = True

        if member.groups.filter(name='general_gym_manager').exists():
            initial_data['manager'] = True

        form = GymUserPermissionForm(initial={'role': initial_data},
                                     available_roles=form_group_permission)

    # Set form action to absolute path
    form.helper.form_action = request.path

    context = {'title': member.get_full_name(),
               'form': form,
               'submit_text': 'Save'}

    return render(request, 'form.html', context)
Exemple #17
0
 def dispatch(self, *args, **kwargs):
     if not self.request.user.has_perm('clips.delete_clip'):
         return HttpResponseForbidden()
     return super(ClipDeleteView, self).dispatch(*args, **kwargs)