Beispiel #1
0
def project_modify(request, application_id):

    try:
        app = ProjectApplication.objects.get(id=application_id)
    except ProjectApplication.DoesNotExist:
        raise Http404

    user = request.user
    if not (user.owns_application(app) or user.is_project_admin(app.id)):
        m = _(astakos_messages.NOT_ALLOWED)
        raise PermissionDenied(m)

    if not user.is_project_admin():
        owner = app.owner
        ok, limit = check_pending_app_quota(owner, precursor=app)
        if not ok:
            m = _(astakos_messages.PENDING_APPLICATION_LIMIT_MODIFY) % limit
            messages.error(request, m)
            next = reverse('astakos.im.views.project_list')
            next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
            return redirect(next)

    details_fields = ["name", "homepage", "description", "start_date",
                      "end_date", "comments"]
    membership_fields = ["member_join_policy", "member_leave_policy",
                         "limit_on_members_number"]
    resource_catalog, resource_groups = _resources_catalog(for_project=True)
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)
    extra_context = {
        'resource_catalog': resource_catalog,
        'resource_groups': resource_groups,
        'show_form': True,
        'details_fields': details_fields,
        'update_form': True,
        'membership_fields': membership_fields
    }

    response = None
    with ExceptionHandler(request):
        response = _update_object(
            request,
            object_id=application_id,
            template_name='im/projects/projectapplication_form.html',
            summary_template_name='im/projects/projectapplication_form_summary.html',
            extra_context=extra_context,
            post_save_redirect=reverse('project_list'),
            form_class=ProjectApplicationForm,
            msg=_("The %(verbose_name)s has been received and is under "
                  "consideration."))

    if response is not None:
        return response

    next = reverse('astakos.im.views.project_list')
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #2
0
def project_modify(request, application_id):

    try:
        app = ProjectApplication.objects.get(id=application_id)
    except ProjectApplication.DoesNotExist:
        raise Http404

    user = request.user
    if not (user.owns_application(app) or user.is_project_admin(app.id)):
        m = _(astakos_messages.NOT_ALLOWED)
        raise PermissionDenied(m)

    if not user.is_project_admin():
        owner = app.owner
        ok, limit = check_pending_app_quota(owner, precursor=app)
        if not ok:
            m = _(astakos_messages.PENDING_APPLICATION_LIMIT_MODIFY) % limit
            messages.error(request, m)
            next = reverse('astakos.im.views.project_list')
            next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
            return redirect(next)

    details_fields = ["name", "homepage", "description", "start_date",
                      "end_date", "comments"]
    membership_fields = ["member_join_policy", "member_leave_policy",
                         "limit_on_members_number"]
    resource_catalog, resource_groups = _resources_catalog(for_project=True)
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)
    extra_context = {
        'resource_catalog': resource_catalog,
        'resource_groups': resource_groups,
        'show_form': True,
        'details_fields': details_fields,
        'update_form': True,
        'membership_fields': membership_fields
    }

    response = None
    with ExceptionHandler(request):
        response = _update_object(
            request,
            object_id=application_id,
            template_name='im/projects/projectapplication_form.html',
            extra_context=extra_context,
            post_save_redirect=reverse('project_list'),
            form_class=ProjectApplicationForm,
            msg=_("The %(verbose_name)s has been received and is under "
                  "consideration."))

    if response is not None:
        return response

    next = reverse('astakos.im.views.project_list')
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #3
0
def project_add(request):
    user = request.user
    if not user.is_project_admin():
        ok, limit = check_pending_app_quota(user)
        if not ok:
            m = _(astakos_messages.PENDING_APPLICATION_LIMIT_ADD) % limit
            messages.error(request, m)
            next = reverse('astakos.im.views.project_list')
            next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
            return redirect(next)

    details_fields = ["name", "homepage", "description", "start_date",
                      "end_date", "comments"]
    membership_fields = ["member_join_policy", "member_leave_policy",
                         "limit_on_members_number"]
    resource_catalog, resource_groups = _resources_catalog(for_project=True)
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)
    extra_context = {
        'resource_catalog': resource_catalog,
        'resource_groups': resource_groups,
        'show_form': True,
        'details_fields': details_fields,
        'membership_fields': membership_fields}

    response = None
    with ExceptionHandler(request):
        response = _create_object(
            request,
            template_name='im/projects/projectapplication_form.html',
            summary_template_name='im/projects/projectapplication_form_summary.html',
            extra_context=extra_context,
            post_save_redirect=reverse('project_list'),
            form_class=ProjectApplicationForm,
            msg=_("The %(verbose_name)s has been received and "
                  "is under consideration."),
            )

    if response is not None:
        return response

    next = reverse('astakos.im.views.project_list')
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #4
0
def edit_profile(request, template_name='im/profile.html', extra_context=None):
    """
    Allows a user to edit his/her profile.

    In case of GET request renders a form for displaying the user information.
    In case of POST updates the user informantion and redirects to ``next``
    url parameter if exists.

    If the user isn't logged in, redirects to settings.LOGIN_URL.

    **Arguments**

    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``im/profile.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.

    **Template:**

    im/profile.html or ``template_name`` keyword argument.

    **Settings:**

    The view expectes the following settings are defined:

    * LOGIN_URL: login uri
    """
    extra_context = extra_context or {}
    form = ProfileForm(instance=request.user,
                       session_key=request.session.session_key)
    extra_context['next'] = request.GET.get('next')
    if request.method == 'POST':
        form = ProfileForm(request.POST,
                           instance=request.user,
                           session_key=request.session.session_key)
        if form.is_valid():
            try:
                prev_token = request.user.auth_token
                user = form.save(request=request)
                next = restrict_next(request.POST.get('next'),
                                     domain=settings.COOKIE_DOMAIN)
                msg = _(astakos_messages.PROFILE_UPDATED)
                messages.success(request, msg)

                if form.email_changed:
                    msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED)
                    messages.success(request, msg)
                if form.password_changed:
                    msg = _(astakos_messages.PASSWORD_CHANGED)
                    messages.success(request, msg)

                if next:
                    return redirect(next)
                else:
                    return redirect(reverse('edit_profile'))
            except ValueError, ve:
                messages.success(request, ve)
Beispiel #5
0
def login(request):
    """
    If there is no `next` request parameter returns 400 (BAD REQUEST).
    Otherwise, if `next` request parameter is not among the allowed schemes,
    returns 403 (Forbidden).
    If the request user is authenticated and has signed the approval terms,
    redirects to `next` request parameter. If not, redirects to approval terms
    in order to return back here after agreeing with the terms.
    Otherwise, redirects to login in order to return back here after successful
    login.
    """
    next = request.GET.get('next')
    if not next:
        return HttpResponseBadRequest('Missing next parameter')

    if not restrict_next(next, allowed_schemes=REDIRECT_ALLOWED_SCHEMES):
        return HttpResponseForbidden(_(
            astakos_messages.NOT_ALLOWED_NEXT_PARAM))
    force = request.GET.get('force', None)
    response = HttpResponse()
    if force == '' and request.user.is_authenticated():
        logout(request)

    if request.user.is_authenticated():
        # if user has not signed the approval terms
        # redirect to approval terms with next the request path
        if not request.user.signed_terms:
            # first build next parameter
            parts = list(urlsplit(request.build_absolute_uri()))
            params = dict(parse_qsl(parts[3], keep_blank_values=True))
            parts[3] = urlencode(params)
            next = urlunsplit(parts)

            # build url location
            parts[2] = reverse('latest_terms')
            params = {'next': next}
            parts[3] = urlencode(params)
            url = urlunsplit(parts)
            return WebloginHttpResponseRedirect(url)
        renew = request.GET.get('renew', None)
        if renew == '':
            request.user.renew_token(flush_sessions=True,
                                     current_key=request.session.session_key)
            try:
                request.user.save()
            except ValidationError, e:
                return WebloginHttpResponseBadRequest(e)
            # authenticate before login
            user = authenticate(username=request.user.username,
                                auth_token=request.user.auth_token)
            auth_login(request, user)
            logger.info('Token reset for %s' % user.username)
        parts = list(urlsplit(next))
        parts[3] = urlencode({
            'uuid': request.user.uuid,
            'token': request.user.auth_token
        })
        url = urlunsplit(parts)
        return WebloginHttpResponseRedirect(url)
Beispiel #6
0
def project_add(request):
    user = request.user
    if not user.is_project_admin():
        ok, limit = check_pending_app_quota(user)
        if not ok:
            m = _(astakos_messages.PENDING_APPLICATION_LIMIT_ADD) % limit
            messages.error(request, m)
            next = reverse('astakos.im.views.project_list')
            next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
            return redirect(next)

    details_fields = ["name", "homepage", "description", "start_date",
                      "end_date", "comments"]
    membership_fields = ["member_join_policy", "member_leave_policy",
                         "limit_on_members_number"]
    resource_catalog, resource_groups = _resources_catalog(for_project=True)
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)
    extra_context = {
        'resource_catalog': resource_catalog,
        'resource_groups': resource_groups,
        'show_form': True,
        'details_fields': details_fields,
        'membership_fields': membership_fields}

    response = None
    with ExceptionHandler(request):
        response = _create_object(
            request,
            template_name='im/projects/projectapplication_form.html',
            extra_context=extra_context,
            post_save_redirect=reverse('project_list'),
            form_class=ProjectApplicationForm,
            msg=_("The %(verbose_name)s has been received and "
                  "is under consideration."),
            )

    if response is not None:
        return response

    next = reverse('astakos.im.views.project_list')
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #7
0
def project_cancel_member(request, memb_id):
    next = request.GET.get('next')
    if not next:
        next = reverse('astakos.im.views.project_list')

    with ExceptionHandler(request):
        _project_cancel_member(request, memb_id)

    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #8
0
def project_join(request, chain_id):
    next = request.GET.get('next')
    if not next:
        next = reverse('astakos.im.views.project_detail', args=(chain_id, ))

    with ExceptionHandler(request):
        _project_join(request, chain_id)

    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #9
0
def project_cancel(request, chain_id):
    next = request.GET.get('next')
    if not next:
        next = reverse('astakos.im.views.project_list')

    with ExceptionHandler(request):
        _project_cancel(request, chain_id)

    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #10
0
def redirect_to_next(request, default_resolve, *args, **kwargs):
    next = kwargs.pop('next', None)
    if not next:
        default = restrict_reverse(default_resolve, *args,
                                   restrict_domain=settings.COOKIE_DOMAIN,
                                   **kwargs)
        next = request.GET.get('next', default)

    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #11
0
def redirect_to_next(request, default_resolve, *args, **kwargs):
    next = kwargs.pop('next', None)
    if not next:
        default = restrict_reverse(default_resolve, *args,
                                   restrict_domain=settings.COOKIE_DOMAIN,
                                   **kwargs)
        next = request.GET.get('next', default)

    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #12
0
def project_add(request):
    user = request.user
    if not user.is_project_admin():
        ok, limit = check_pending_app_quota(user)
        if not ok:
            m = _(astakos_messages.PENDING_APPLICATION_LIMIT_ADD) % limit
            messages.error(request, m)
            next = reverse('astakos.im.views.project_list')
            next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
            return redirect(next)

    details_fields = ["name", "homepage", "description", "start_date",
                      "end_date", "comments"]
    membership_fields = ["member_join_policy", "member_leave_policy",
                         "limit_on_members_number"]
    resource_catalog, resource_groups = _resources_catalog()
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)
    extra_context = {
        'resource_catalog': resource_catalog,
        'resource_groups': resource_groups,
        'show_form': True,
        'details_fields': details_fields,
        'membership_fields': membership_fields}

    response = None
    with ExceptionHandler(request):
        response = create_app_object(request, extra_context=extra_context)

    if response is not None:
        return response

    next = reverse('astakos.im.views.project_list')
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #13
0
def _approval_terms_post(request, template_name, terms, extra_context):
    next = restrict_next(request.POST.get('next'),
                         domain=settings.COOKIE_DOMAIN)
    if not next:
        next = reverse('index')
    form = SignApprovalTermsForm(request.POST, instance=request.user)
    if not form.is_valid():
        return render_response(template_name,
                               terms=terms,
                               approval_terms_form=form,
                               context_instance=get_context(
                                   request, extra_context))
    user = form.save()
    return HttpResponseRedirect(next)
Beispiel #14
0
def project_app_cancel(request, application_id):
    next = request.GET.get('next')
    chain_id = None

    with ExceptionHandler(request):
        chain_id = _project_app_cancel(request, application_id)

    if not next:
        if chain_id:
            next = reverse('astakos.im.views.project_detail', args=(chain_id,))
        else:
            next = reverse('astakos.im.views.project_list')

    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
    return redirect(next)
Beispiel #15
0
def _approval_terms_post(request, template_name, terms, extra_context):
    next = restrict_next(
        request.POST.get('next'),
        domain=settings.COOKIE_DOMAIN
    )
    if not next:
        next = reverse('index')
    form = SignApprovalTermsForm(request.POST, instance=request.user)
    if not form.is_valid():
        return render_response(template_name,
                               terms=terms,
                               approval_terms_form=form,
                               context_instance=get_context(request,
                                                            extra_context))
    user = form.save()
    return HttpResponseRedirect(next)
Beispiel #16
0
def logout(request, template='registration/logged_out.html',
           extra_context=None):
    """
    Wraps `django.contrib.auth.logout`.
    """
    extra_context = extra_context or {}
    response = HttpResponse()
    if request.user.is_authenticated():
        email = request.user.email
        auth_logout(request)
    else:
        response['Location'] = reverse('index')
        response.status_code = 301
        return response

    next = restrict_next(
        request.GET.get('next'),
        domain=settings.COOKIE_DOMAIN
    )

    if next:
        response['Location'] = next
        response.status_code = 302
    elif settings.LOGOUT_NEXT:
        response['Location'] = settings.LOGOUT_NEXT
        response.status_code = 301
    else:
        last_provider = request.COOKIES.get(
            'astakos_last_login_method', 'local')
        try:
            provider = auth.get_provider(last_provider)
        except auth.InvalidProvider:
            provider = auth.get_provider('local')

        message = provider.get_logout_success_msg
        extra = provider.get_logout_success_extra_msg

        if extra:
            message += "<br />" + extra
        messages.success(request, message)
        response['Location'] = reverse('index')
        response.status_code = 301
    return response
Beispiel #17
0
def logout(request, template='registration/logged_out.html',
           extra_context=None):
    """
    Wraps `django.contrib.auth.logout`.
    """
    extra_context = extra_context or {}
    response = HttpResponse()
    if request.user.is_authenticated():
        email = request.user.email
        auth_logout(request)
    else:
        response['Location'] = reverse('index')
        response.status_code = 301
        return response

    next = restrict_next(
        request.GET.get('next'),
        domain=settings.COOKIE_DOMAIN
    )

    if next:
        response['Location'] = next
        response.status_code = 302
    elif settings.LOGOUT_NEXT:
        response['Location'] = settings.LOGOUT_NEXT
        response.status_code = 301
    else:
        last_provider = request.COOKIES.get(
            'astakos_last_login_method', 'local')
        try:
            provider = auth.get_provider(last_provider)
        except auth.InvalidProvider:
            provider = auth.get_provider('local')

        message = provider.get_logout_success_msg
        extra = provider.get_logout_success_extra_msg

        if extra:
            message += "<br />" + extra
        messages.success(request, message)
        response['Location'] = reverse('index')
        response.status_code = 301
    return response
Beispiel #18
0
def login(request):
    """
    If there is no ``next`` request parameter redirects to astakos index page
    displaying an error message.
    If the request user is authenticated and has signed the approval terms,
    redirects to `next` request parameter. If not, redirects to approval terms
    in order to return back here after agreeing with the terms.
    Otherwise, redirects to login in order to return back here after successful
    login.
    """
    next = request.GET.get('next')
    if not next:
        next = reverse('index')

    if not restrict_next(next, allowed_schemes=REDIRECT_ALLOWED_SCHEMES):
        return HttpResponseForbidden(_(
            astakos_messages.NOT_ALLOWED_NEXT_PARAM))
    force = request.GET.get('force', None)
    response = HttpResponse()
    if force == '' and request.user.is_authenticated():
        logout(request)

    if request.user.is_authenticated():
        # if user has not signed the approval terms
        # redirect to approval terms with next the request path
        if not request.user.signed_terms:
            # first build next parameter
            parts = list(urlsplit(request.build_absolute_uri()))
            params = dict(parse_qsl(parts[3], keep_blank_values=True))
            parts[3] = urlencode(params)
            next = urlunsplit(parts)

            # build url location
            parts[2] = reverse('latest_terms')
            params = {'next': next}
            parts[3] = urlencode(params)
            url = urlunsplit(parts)
            response['Location'] = url
            response.status_code = 302
            return response
        renew = request.GET.get('renew', None)
        if renew == '':
            request.user.renew_token(
                flush_sessions=True,
                current_key=request.session.session_key
            )
            try:
                request.user.save()
            except ValidationError, e:
                return HttpResponseBadRequest(e)
            # authenticate before login
            user = authenticate(
                username=request.user.username,
                auth_token=request.user.auth_token
            )
            auth_login(request, user)
            logger.info('Token reset for %s' % user.username)
        parts = list(urlsplit(next))
        parts[3] = urlencode({
            'uuid': request.user.uuid,
            'token': request.user.auth_token
        })
        url = urlunsplit(parts)
        response['Location'] = url
        response.status_code = 302
        return response
Beispiel #19
0
    if not term:
        messages.error(request, _(astakos_messages.NO_APPROVAL_TERMS))
        return HttpResponseRedirect(reverse('index'))
    try:
        f = open(term.location, 'r')
    except IOError:
        messages.error(request, _(astakos_messages.GENERIC_ERROR))
        return render_response(
            template_name, context_instance=get_context(request,
                                                        extra_context))

    terms = f.read()

    if request.method == 'POST':
        next = restrict_next(
            request.POST.get('next'),
            domain=settings.COOKIE_DOMAIN
        )
        if not next:
            next = reverse('index')
        form = SignApprovalTermsForm(request.POST, instance=request.user)
        if not form.is_valid():
            return render_response(template_name,
                                   terms=terms,
                                   approval_terms_form=form,
                                   context_instance=get_context(request,
                                                                extra_context))
        user = form.save()
        return HttpResponseRedirect(next)
    else:
        form = None
        if request.user.is_authenticated() and not request.user.signed_terms:
Beispiel #20
0
    if not term:
        messages.error(request, _(astakos_messages.NO_APPROVAL_TERMS))
        return HttpResponseRedirect(reverse('index'))
    try:
        f = open(term.location, 'r')
    except IOError:
        messages.error(request, _(astakos_messages.GENERIC_ERROR))
        return render_response(template_name,
                               context_instance=get_context(
                                   request, extra_context))

    terms = f.read()

    if request.method == 'POST':
        next = restrict_next(request.POST.get('next'),
                             domain=settings.COOKIE_DOMAIN)
        if not next:
            next = reverse('index')
        form = SignApprovalTermsForm(request.POST, instance=request.user)
        if not form.is_valid():
            return render_response(template_name,
                                   terms=terms,
                                   approval_terms_form=form,
                                   context_instance=get_context(
                                       request, extra_context))
        user = form.save()
        return HttpResponseRedirect(next)
    else:
        form = None
        if request.user.is_authenticated() and not request.user.signed_terms:
            form = SignApprovalTermsForm(instance=request.user)
Beispiel #21
0
def edit_profile(request, template_name='im/profile.html', extra_context=None):
    """
    Allows a user to edit his/her profile.

    In case of GET request renders a form for displaying the user information.
    In case of POST updates the user informantion and redirects to ``next``
    url parameter if exists.

    If the user isn't logged in, redirects to settings.LOGIN_URL.

    **Arguments**

    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``im/profile.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.

    **Template:**

    im/profile.html or ``template_name`` keyword argument.

    **Settings:**

    The view expectes the following settings are defined:

    * LOGIN_URL: login uri
    """

    request.user = AstakosUser.objects.select_for_update().\
        get(id=request.user.id)
    extra_context = extra_context or {}
    form = ProfileForm(
        instance=request.user,
        session_key=request.session.session_key
    )
    extra_context['next'] = request.GET.get('next')
    if request.method == 'POST':
        form = ProfileForm(
            request.POST,
            instance=request.user,
            session_key=request.session.session_key
        )
        if form.is_valid():
            try:
                prev_token = request.user.auth_token
                user = form.save(request=request)
                next = restrict_next(
                    request.POST.get('next'),
                    domain=settings.COOKIE_DOMAIN
                )
                msg = _(astakos_messages.PROFILE_UPDATED)
                messages.success(request, msg)

                if form.email_changed:
                    msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED)
                    messages.success(request, msg)
                if form.password_changed:
                    msg = _(astakos_messages.PASSWORD_CHANGED)
                    messages.success(request, msg)

                if next:
                    return redirect(next)
                else:
                    return redirect(reverse('edit_profile'))
            except ValueError, ve:
                messages.success(request, ve)