Beispiel #1
0
def login(request,
          template_name='login.html',
          redirect_field_name=PLONEPROXY_REDIRECT_FIELD_NAME):
    """
    Displays the login form and handles the login action.
    """

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    resDict = {}

    if request.method == "POST":

        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

        # keep user name.
        resDict['username'] = username

        # Light security check -- make sure redirect_to isn't garbage.
        if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
            resDict[
                'invalid_url'] = 'Invalid URL! Please double check your url!'
        elif username == '' or password == '':
            # all fields are required!
            resDict['invalid_fields'] = 'All fields must be filled in'
        else:
            loginurl = buildPloneLoginURL(request, redirect_to)
            user = authenticate(username=username,
                                password=password,
                                loginurl=loginurl)
            if user is None:
                resDict[
                    'invalid_cred'] = 'Please enter a correct username and password'
            else:
                from django.contrib.auth import login
                login(request, user)

                # looks like everything is fine now.
                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                return HttpResponseRedirect(redirect_to)

    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    resDict['site'] = current_site
    resDict['site_name'] = current_site.name

    # decide another available language.
    lang = get_language()
    lang_name, lang_link = prepareOtherLang(request, redirect_field_name, lang)
    resDict[settings.PLONEPROXY_LANG_FIELD_NAME] = lang
    resDict['lang_name'] = lang_name
    resDict['lang_link'] = lang_link

    resDict[redirect_field_name] = redirect_to

    # url for forgot password.
    resDict['forgot_pw_url'] = prepareForgotPasswordURL(
        request, redirect_field_name, lang)

    return render_to_response(template_name,
                              resDict,
                              context_instance=RequestContext(request))
Beispiel #2
0
    def register(self, request, **kwargs):
        """
        Given a username, email address and password, register a new
        user account, which will initially be inactive.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        email, password = kwargs['email'], kwargs['password1']
        username = email
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)

        from registration.models import RegistrationProfile
        if bool(config.ACTIVATE_AFTER_REGISTRATION) is True:
            # since user will be activated after registration,
            # so we will not use email sending, just create acitvated user
            new_user = RegistrationProfile.objects.create_active_user(username, email,
                                                                        password, site,
                                                                        send_email=False)
            # login the user
            new_user.backend=settings.AUTHENTICATION_BACKENDS[0]

            login(request, new_user)
        else:
            # create inactive user, user can be activated by admin, or through activated email
            new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                        password, site,
                                                                        send_email=config.REGISTRATION_SEND_MAIL)

        # userid = kwargs['userid']
        # if userid:
        #     ccnet_threaded_rpc.add_binding(new_user.username, userid)

        if settings.REQUIRE_DETAIL_ON_REGISTRATION:
            name = kwargs.get('name', '')
            department = kwargs.get('department', '')
            telephone = kwargs.get('telephone', '')
            note = kwargs.get('note', '')
            Profile.objects.add_or_update(new_user.username, name, note)
            DetailedProfile.objects.add_detailed_profile(new_user.username,
                                                         department,
                                                         telephone)

        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Beispiel #3
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)

    if request.method == "POST":
        login = request.REQUEST.get('login', '').strip()
        failed_attempt = get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(),
                                            redirect_to, remember_me)

        # form is invalid
        user_logged_in_failed.send(sender=None, request=request)
        failed_attempt = incr_login_failed_attempts(username=login, ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn(
                    'Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn(
                            'Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d'
                            % (login, ip, failed_attempt))
                except User.DoesNotExist:
                    logger.warn(
                        'Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    pass
                form.errors['freeze_account'] = _(
                    'This account has been frozen due to too many failed login attempts.'
                )
            else:
                # use a new form with Captcha
                logger.warn(
                    'Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()

    else:
        ### GET
        failed_attempt = get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn(
                    'Login attempt limit reached, show Captcha, ip: %s, attempts: %d'
                    % (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_krb5_login = getattr(settings, 'ENABLE_KRB5_LOGIN', False)
    enable_adfs_login = getattr(settings, 'ENABLE_ADFS_LOGIN', False)
    enable_oauth = getattr(settings, 'ENABLE_OAUTH', False)

    login_bg_image_path = get_login_bg_image_path()

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
        'enable_krb5_login': enable_krb5_login,
        'enable_adfs_login': enable_adfs_login,
        'enable_oauth': enable_oauth,
        'login_bg_image_path': login_bg_image_path,
    },
                              context_instance=RequestContext(request))
Beispiel #4
0
def send_ratealert_activation(request, signup):
    site = RequestSite(request)
    send_mail('Please activate your subscription',
                       'Please click the following link to activate %s%s%s%s%s' % ('https://', site.domain, '/signup/ratealert/activate/', signup.activation_key, '/'),
                       '*****@*****.**',
                      [signup.email], fail_silently=False)
Beispiel #5
0
def solution_list(request, task_id, user_id=None):
    if (user_id and not in_group(request.user, 'Trainer')):
        return access_denied(request)

    task = get_object_or_404(Task, pk=task_id)
    author = get_object_or_404(User, pk=user_id) if user_id else request.user
    solutions = task.solution_set.filter(author=author).order_by('-id')
    final_solution = task.final_solution(author)

    if (task.publication_date >= datetime.now()) and (not in_group(
            request.user, 'Trainer')):
        raise Http404

    if request.method == "POST":
        solution = Solution(task=task, author=author)
        formset = SolutionFormSet(request.POST,
                                  request.FILES,
                                  instance=solution)
        if formset.is_valid():
            solution.save()
            formset.save()
            run_all_checker = bool(
                User.objects.filter(id=user_id,
                                    tutorial__tutors__pk=request.user.id)
                or in_group(request.user, 'Trainer'))
            solution.check(run_all_checker)

            if solution.accepted:
                # Send submission confirmation email
                t = loader.get_template(
                    'solutions/submission_confirmation_email.html')
                c = {
                    'protocol': request.is_secure() and "https" or "http",
                    'domain': RequestSite(request).domain,
                    'site_name': settings.SITE_NAME,
                    'solution': solution,
                }
                if solution.author.email:
                    send_mail(
                        _("%s submission confirmation") % settings.SITE_NAME,
                        t.render(Context(c)), None, [solution.author.email])

            if solution.accepted or get_settings().accept_all_solutions:
                solution.final = True
                solution.save()

            return HttpResponseRedirect(
                reverse('solution_detail', args=[solution.id]))
    else:
        formset = SolutionFormSet()

    attestations = Attestation.objects.filter(
        solution__task=task, author__tutored_tutorials=request.user.tutorial)
    attestationsPublished = attestations[0].published if attestations else False

    return render_to_response("solutions/solution_list.html", {
        "formset": formset,
        "task": task,
        "solutions": solutions,
        "final_solution": final_solution,
        "attestationsPublished": attestationsPublished,
        "author": author
    },
                              context_instance=RequestContext(request))
Beispiel #6
0
def events_calendar_ical(request, privacy=None):
    cache_key = 'calendar'
    if privacy:
        cache_key += '_%s' % privacy
    if request.GET.get('location'):
        if request.GET.get('location').isdigit():
            location = get_object_or_404(Location,
                                         pk=request.GET.get('location'))
        else:
            location = get_object_or_404(Location,
                                         name=request.GET.get('location'))
        cache_key += str(location.pk)
        cached = None
    else:
        location = None
        cached = cache.get(cache_key)

    if cached:
        # additional response headers aren't remembered so add them again
        cached['Access-Control-Allow-Origin'] = '*'
        return cached
    cal = vobject.iCalendar()

    now = timezone.now()
    base_qs = Event.objects.approved()
    if privacy == 'public':
        base_qs = base_qs.filter(privacy=Event.PRIVACY_PUBLIC)
        title = 'Air Mozilla Public Events'
    elif privacy == 'private':
        base_qs = base_qs.exclude(privacy=Event.PRIVACY_PUBLIC)
        title = 'Air Mozilla Private Events'
    else:
        title = 'Air Mozilla Events'
    if location:
        base_qs = base_qs.filter(location=location)
    cal.add('X-WR-CALNAME').value = title
    events = list(
        base_qs.filter(start_time__lt=now).order_by('-start_time')
        [:settings.CALENDAR_SIZE])
    events += list(base_qs.filter(start_time__gte=now).order_by('start_time'))
    base_url = '%s://%s/' % (request.is_secure() and 'https'
                             or 'http', RequestSite(request).domain)
    for event in events:
        vevent = cal.add('vevent')
        vevent.add('summary').value = event.title
        vevent.add('dtstart').value = event.start_time
        vevent.add('dtend').value = (
            event.start_time +
            datetime.timedelta(seconds=(event.duration or 3600)))
        vevent.add('description').value = short_desc(event, strip_html=True)
        if event.location:
            vevent.add('location').value = event.location.name
        vevent.add('url').value = base_url + event.slug + '/'
    icalstream = cal.serialize()
    # response = http.HttpResponse(icalstream,
    #                           mimetype='text/plain; charset=utf-8')

    response = http.HttpResponse(icalstream,
                                 mimetype='text/calendar; charset=utf-8')
    filename = 'AirMozillaEvents%s' % (privacy and privacy or '')
    if location:
        filename += '_%s' % slugify(location.name)
    filename += '.ics'
    response['Content-Disposition'] = ('inline; filename=%s' % filename)
    if not location:
        cache.set(cache_key, response, 60 * 10)  # 10 minutes

    # https://bugzilla.mozilla.org/show_bug.cgi?id=909516
    response['Access-Control-Allow-Origin'] = '*'

    return response
Beispiel #7
0
 def setUp(self):
     class FakeRequest():
         def get_host(self):
             return 'example.test'
     self.provider = BaseProvider(RequestSite(FakeRequest()))
Beispiel #8
0
    def send_confirmation_mail(self, request):
        """
An instance method to send a confirmation mail to the new
email address.

The generation of a confirmation email will use three templates that
can be set in each project's settings:

* :py:attr:`~password_policies.conf.Settings.EMAIL_CHANGE_HTML_EMAIL_TEMPLATE`.
* :py:attr:`~password_policies.conf.Settings.EMAIL_CHANGE_SUBJECT_EMAIL_TEMPLATE`
* :py:attr:`~password_policies.conf.Settings.EMAIL_CHANGE_TXT_EMAIL_TEMPLATE`

These templates will receive the following context variables:

``date``
    The date when the email address change was requested.

``timeout_date``
    The date whe the request will expire.

``current_site``
    An object representing the current site on which the user
    is logged in.  Depending on whether ``django.contrib.sites``
    is installed, this may be an instance of either
    ``django.contrib.sites.models.Site`` (if the sites
    application is installed) or
    ``django.contrib.sites.models.RequestSite`` (if
    not). Consult the documentation for the Django sites
    framework for details regarding these objects' interfaces.

``new_email``
    The new email address.

``protocol``
    The protocol used to generate the confirmation URL, either HTTP or HTTPS.
    To use HTTPS set :py:attr:`~password_policies.conf.Settings.EMAIL_CHANGE_USE_HTTPS`
    to True.

``signature``
    The confirmation signature for the new email address.

``user``
    The user that has requested the email address change.

:arg obj request: The request object.
"""
        if Site._meta.installed:
            current_site = Site.objects.get_current()
        else:
            current_site = RequestSite(request)
        subject = settings.EMAIL_CHANGE_SUBJECT_EMAIL_TEMPLATE
        body_htm = settings.EMAIL_CHANGE_HTML_EMAIL_TEMPLATE
        body_txt = settings.EMAIL_CHANGE_TXT_EMAIL_TEMPLATE
        context = {
            'current_site': current_site,
            'date': self.date,
            'timeout_date': self.get_expiration_date(),
            'new_email': self.new_email,
            'protocol': settings.EMAIL_CHANGE_USE_HTTPS and 'https' or 'http',
            'signature': self.make_signature(),
            'user': self.user
        }
        subject = render_to_string(subject, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        text_message = render_to_string(body_txt, context)
        if settings.EMAIL_CHANGE_HTML_EMAIL:
            html_message = render_to_string(body_htm, context)
            msg = EmailMultiAlternatives(subject, text_message,
                                         settings.EMAIL_CHANGE_FROM_EMAIL,
                                         [self.new_email])
            msg.attach_alternative(html_message, "text/html")
            msg.send()
        else:
            send_mail(subject, text_message, settings.EMAIL_CHANGE_FROM_EMAIL,
                      [self.new_email])
Beispiel #9
0
 def setUp(self):
     self.request = RequestFactory().get('/accounts/signup/')
     self.site = RequestSite(self.request)
Beispiel #10
0
def registration_view(request):
    # Get the site information for sending emails.
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)
    # Round table registration for Network receptions only
    # print request.POST
    """
    Delete a Network Reception registration completely
    """
    if 'round_table_delete' in request.POST:
        event_id = request.POST.get('event_id')
        event = get_object_or_404(Event, pk=event_id)
        form = NetWorkForm(request.POST, event=event, request=request)
        if form.is_valid():
            event_id = form.cleaned_data['event_id']
            round_table_1 = form.cleaned_data['round_table_1']
            round_table_2 = form.cleaned_data['round_table_2']
            rt_1 = get_object_or_404(RoundTableRegistration,
                                     student=request.user,
                                     round_table=round_table_1)
            rt_2 = get_object_or_404(RoundTableRegistration,
                                     student=request.user,
                                     round_table=round_table_2)
            rt_1.delete()
            rt_2.delete()
            request.user.send_event_register_mail("delete", event, site,
                                                  request)
            return HttpResponsePermanentRedirect(reverse('profile-event'))
        else:
            return render(request, 'profile-event-registration.html',
                          {'form': form})

    if 'round_table_registration' in request.POST:
        event_id = request.POST.get('event_id')
        event = get_object_or_404(Event, pk=event_id)
        form = NetWorkForm(request.POST, event=event, request=request)
        # check if user has paid for event
        paid = request.user.my_round_table.all()
        if paid:
            paid = paid.filter(round_table__event_id=event_id)[0].paid
        if form.is_valid():
            event_id = form.cleaned_data['event_id']
            round_table_1 = form.cleaned_data['round_table_1']
            round_table_2 = form.cleaned_data['round_table_2']
            if not request.user.is_u_of_t and not paid and event.has_fee:
                request.session['event_id'] = event_id
                request.session['round_table_1'] = round_table_1.pk
                request.session['round_table_2'] = round_table_2.pk
                return HttpResponsePermanentRedirect(reverse('paypal:payment'))
            form.save()
            form.send_mail()
            return HttpResponsePermanentRedirect(reverse('profile-event'))
        else:
            return render(request, 'profile-event-registration.html',
                          {'form': form})

    if request.POST and request.POST.get('event_id', None):
        event_id = request.POST.get('event_id')
        event = Event.objects.get(pk=event_id)
        if event.get_round_table():
            rt1, rt2 = RoundTable.objects.get_user_rountable(
                request.user, event)
            if rt1 and rt2:
                reg1 = rt1[0]
                reg2 = rt2[0]
                initial = {
                    'event': event,
                    'event_id': event.id,
                    'round_table_1': reg1,
                    'round_table_2': reg2
                }
            else:
                initial = {'event': event, 'event_id': event.id}
            form = NetWorkForm(event=event, initial=initial)

            return render(request, 'profile-event-registration.html', {
                'form': form,
                'event': event
            })
        else:
            registration, create = Registration.objects.get_or_create(
                owner=request.user, event=Event(pk=event_id))
            if create:
                registration.save()
                request.user.send_event_register_mail("register", event, site,
                                                      request)
            else:
                registration.delete()
                request.user.send_event_register_mail("delete", event, site,
                                                      request)
        return HttpResponsePermanentRedirect(reverse('profile-event'))
    else:
        return HttpResponsePermanentRedirect(reverse('profile-event'))
Beispiel #11
0
def openid(request,
           template_name='openid.html',
           redirect_field_name=REDIRECT_FIELD_NAME):
    msg = None
    redirect_to = urlresolvers.reverse('index')
    if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
        redirect_to = settings.BASE_URL + '/'

    if not gls_openid.openid:
        return HttpResponseRedirect(redirect_to)

    if request.method == 'POST':
        form = OpenIdForm(data=request.POST, )
        if form.is_valid():
            if not form.cleaned_data['remember_me']:
                request.session.set_expiry(0)

            rs = gls_openid.start(request,
                                  form.cleaned_data['openid_identifier'])
            if 'res' in rs:
                return rs['res']
            elif 'msg' in rs:
                msg = rs['msg']
        else:
            msg = _('Invalid OpenID identifier')

    elif request.method == 'GET':

        if request.GET.get('openid.mode', None):
            rs = gls_openid.finish(request)
            if 'msg' in rs:
                msg = rs['msg']
            elif 'identity_url' in rs:
                try:
                    db = OpenId.objects.get(identity=rs['identity_url'])
                    if db:
                        user = db.user
                        user.backend = 'django.contrib.auth.backends.ModelBackend'
                        if user.is_active:
                            from django.contrib.auth import login
                            login(request, user)

                            if request.session.test_cookie_worked():
                                request.session.delete_test_cookie()
                            return HttpResponseRedirect(redirect_to)
                except OpenId.DoesNotExist:
                    pass
                msg = _('OpenID account match error')

    form = OpenIdForm(request, )
    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    page = {
        'robots': 'noindex,nofollow',
        'favicon': settings.FAVICON,
        'theme': common.get_theme(request),
        'msg': msg,
    }

    return render_to_response(template_name, {
        'page': page,
        'form': form,
        'site': current_site,
        'site_name': current_site.name,
        'is_secure': request.is_secure(),
        redirect_field_name: redirect_to
    },
                              context_instance=RequestContext(request))
Beispiel #12
0
def cd_registration(request):
    # Get the site information for sending emails.
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)
Beispiel #13
0
    def register(self, request, **cleaned_data):
        """
        Given a username, email address and password, register a new
        user account, which will initially be inactive.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        username, email, password = cleaned_data['username'], cleaned_data[
            'email'], cleaned_data['password1']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)

        new_user = RegistrationProfile.objects.create_inactive_user(
            username, email, password, site, False)

        #mail
        reg_prof = RegistrationProfile.objects.get(user=new_user)
        ctx_dict = {
            'activation_key': reg_prof.activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': site,
            'cur_domain': settings.POS_SERVER,
            'user': new_user
        }
        subject = render_to_string('registration/activation_email_subject.txt',
                                   ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())

        message = render_to_string('registration/activation_email.html',
                                   ctx_dict)

        # new_user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)

        emails = [new_user.email]
        message_html = message
        try:
            msg = EmailMultiAlternatives(subject, message_html,
                                         settings.DEFAULT_FROM_EMAIL, emails)
            #msg = EmailMultiAlternatives(subject, message_text, settings.DEFAULT_FROM_EMAIL, emails)
            msg.attach_alternative(message_html, "text/html")
            msg.send()
        except Exception, e:
            logger.error(str(e))
Beispiel #14
0
 def get_context_data(self, **kwargs):
     ctx = super(Bookmarklet, self).get_context_data(**kwargs)
     ctx['site'] = RequestSite(self.request)
     ctx['scheme'] = 'https' if self.request.is_secure() else 'http'
     return ctx
Beispiel #15
0
    def _getProvider(self):
        class FakeRequest():
            def get_host(self):
                return 'example.test'

        return AbstractExperimentProvider(RequestSite(FakeRequest()))
Beispiel #16
0
    def populate_feed(self, feed, items, request):
        """Populates a :class:`django.utils.feedgenerator.DefaultFeed` instance as is returned by :meth:`get_feed` with the passed-in ``items``."""
        if self.item_title_template:
            title_template = DjangoTemplate(self.item_title_template.code)
        else:
            title_template = None
        if self.item_description_template:
            description_template = DjangoTemplate(
                self.item_description_template.code)
        else:
            description_template = None

        node = request.node
        try:
            current_site = Site.objects.get_current()
        except Site.DoesNotExist:
            current_site = RequestSite(request)

        if self.feed_length is not None:
            items = items[:self.feed_length]

        for item in items:
            if title_template is not None:
                title = title_template.render(
                    RequestContext(request, {'obj': item}))
            else:
                title = self.__get_dynamic_attr('item_title', item)
            if description_template is not None:
                description = description_template.render(
                    RequestContext(request, {'obj': item}))
            else:
                description = self.__get_dynamic_attr('item_description', item)

            link = node.construct_url(self.reverse(obj=item),
                                      with_domain=True,
                                      request=request,
                                      secure=request.is_secure())

            enc = None
            enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
            if enc_url:
                enc = feedgenerator.Enclosure(
                    url=smart_unicode(
                        add_domain(current_site.domain, enc_url,
                                   request.is_secure())),
                    length=smart_unicode(
                        self.__get_dynamic_attr('item_enclosure_length',
                                                item)),
                    mime_type=smart_unicode(
                        self.__get_dynamic_attr('item_enclosure_mime_type',
                                                item)))
            author_name = self.__get_dynamic_attr('item_author_name', item)
            if author_name is not None:
                author_email = self.__get_dynamic_attr('item_author_email',
                                                       item)
                author_link = self.__get_dynamic_attr('item_author_link', item)
            else:
                author_email = author_link = None

            pubdate = self.__get_dynamic_attr('item_pubdate', item)
            if pubdate and not pubdate.tzinfo:
                ltz = tzinfo.LocalTimezone(pubdate)
                pubdate = pubdate.replace(tzinfo=ltz)

            feed.add_item(
                title=title,
                link=link,
                description=description,
                unique_id=self.__get_dynamic_attr('item_guid', item, link),
                enclosure=enc,
                pubdate=pubdate,
                author_name=author_name,
                author_email=author_email,
                author_link=author_link,
                categories=self.__get_dynamic_attr('item_categories', item),
                item_copyright=self.__get_dynamic_attr('item_copyright', item),
                **self.item_extra_kwargs(item))
Beispiel #17
0
def view_file(request, repo_id):
    """
    Steps to view file:
    1. Get repo id and file path.
    2. Check user's permission.
    3. Check whether this file can be viewed online.
    4.1 Get file content if file is text file.
    4.2 Prepare flash if file is document.
    4.3 Prepare or use pdfjs if file is pdf.
    4.4 Other file return it's raw path.
    """
    username = request.user.username
    # check arguments
    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    path = request.GET.get('p', '/').rstrip('/')
    obj_id = get_file_id_by_path(repo_id, path)
    if not obj_id:
        return render_error(request, _(u'File does not exist'))

    # construct some varibles
    u_filename = os.path.basename(path)
    current_commit = get_commits(repo_id, 0, 1)[0]

    # Check whether user has permission to view file and get file raw path,
    # render error page if permission deny.
    raw_path, inner_path, user_perm = get_file_view_path_and_perm(
        request, repo_id, obj_id, path)
    if not user_perm:
        return render_permission_error(request, _(u'Unable to view file'))

    # check if the user is the owner or not, for 'private share'
    is_repo_owner = seafile_api.is_repo_owner(username, repo.id)

    # get file type and extension
    filetype, fileext = get_file_type_and_ext(u_filename)

    img_prev = None
    img_next = None
    ret_dict = {
        'err': '',
        'file_content': '',
        'encoding': '',
        'file_enc': '',
        'file_encoding_list': [],
        'html_exists': False,
        'filetype': filetype
    }

    fsize = get_file_size(obj_id)

    exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype)
    if exceeds_limit:
        ret_dict['err'] = err_msg
    else:
        """Choose different approach when dealing with different type of file."""
        if is_textual_file(file_type=filetype):
            handle_textual_file(request, filetype, inner_path, ret_dict)
            if filetype == MARKDOWN:
                c = ret_dict['file_content']
                ret_dict['file_content'] = convert_md_link(
                    c, repo_id, username)
        elif filetype == DOCUMENT:
            handle_document(inner_path, obj_id, fileext, ret_dict)
        elif filetype == SPREADSHEET:
            handle_spreadsheet(inner_path, obj_id, fileext, ret_dict)
        elif filetype == OPENDOCUMENT:
            if fsize == 0:
                ret_dict['err'] = _(u'Invalid file format.')
        elif filetype == PDF:
            handle_pdf(inner_path, obj_id, fileext, ret_dict)
        elif filetype == IMAGE:
            parent_dir = os.path.dirname(path)
            dirs = seafile_api.list_dir_by_commit_and_path(
                current_commit.id, parent_dir)
            if not dirs:
                raise Http404

            img_list = []
            for dirent in dirs:
                if not stat.S_ISDIR(dirent.props.mode):
                    fltype, flext = get_file_type_and_ext(dirent.obj_name)
                    if fltype == 'Image':
                        img_list.append(dirent.obj_name)

            if len(img_list) > 1:
                img_list.sort(lambda x, y: cmp(x.lower(), y.lower()))
                cur_img_index = img_list.index(u_filename)
                if cur_img_index != 0:
                    img_prev = posixpath.join(parent_dir,
                                              img_list[cur_img_index - 1])
                if cur_img_index != len(img_list) - 1:
                    img_next = posixpath.join(parent_dir,
                                              img_list[cur_img_index + 1])
        else:
            pass

    # generate file path navigator
    zipped = gen_path_link(path, repo.name)

    # file shared link
    l = FileShare.objects.filter(repo_id=repo_id).filter(
        username=username).filter(path=path)
    fileshare = l[0] if len(l) > 0 else None
    http_or_https = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain
    if fileshare:
        file_shared_link = gen_file_share_link(fileshare.token)
    else:
        file_shared_link = ''

    # my contacts used in shared link autocomplete
    contacts = Contact.objects.filter(user_email=username)
    """List repo groups"""
    # Get groups this repo is shared.
    if request.user.org:
        org_id = request.user.org['org_id']
        repo_shared_groups = get_org_groups_by_repo(org_id, repo_id)
    else:
        repo_shared_groups = get_shared_groups_by_repo(repo_id)
    # Filter out groups that user in joined.
    groups = [x for x in repo_shared_groups if is_group_user(x.id, username)]
    if len(groups) > 1:
        ctx = {}
        ctx['groups'] = groups
        repogrp_str = render_to_string("snippets/repo_group_list.html", ctx)
    else:
        repogrp_str = ''

    file_path_hash = hashlib.md5(urllib2.quote(
        path.encode('utf-8'))).hexdigest()[:12]

    # fetch file contributors and latest contributor
    contributors, last_modified, last_commit_id = \
        FileContributors.objects.get_file_contributors(
        repo_id, path.encode('utf-8'), file_path_hash, obj_id)
    latest_contributor = contributors[0] if contributors else None

    # check whether file is starred
    is_starred = False
    org_id = -1
    if request.user.org:
        org_id = request.user.org['org_id']
    is_starred = is_file_starred(username, repo.id, path.encode('utf-8'),
                                 org_id)

    template = 'view_file_%s.html' % ret_dict['filetype'].lower()

    search_repo_id = None
    if not repo.encrypted:
        search_repo_id = repo.id
    return render_to_response(
        template, {
            'repo': repo,
            'is_repo_owner': is_repo_owner,
            'obj_id': obj_id,
            'filename': u_filename,
            'path': path,
            'zipped': zipped,
            'current_commit': current_commit,
            'fileext': fileext,
            'raw_path': raw_path,
            'fileshare': fileshare,
            'protocol': http_or_https,
            'domain': domain,
            'file_shared_link': file_shared_link,
            'contacts': contacts,
            'err': ret_dict['err'],
            'file_content': ret_dict['file_content'],
            'file_enc': ret_dict['file_enc'],
            'encoding': ret_dict['encoding'],
            'file_encoding_list': ret_dict['file_encoding_list'],
            'html_exists': ret_dict['html_exists'],
            'html_detail': ret_dict.get('html_detail', {}),
            'filetype': ret_dict['filetype'],
            "applet_root": get_ccnetapplet_root(),
            'groups': groups,
            'use_pdfjs': USE_PDFJS,
            'contributors': contributors,
            'latest_contributor': latest_contributor,
            'last_modified': last_modified,
            'last_commit_id': last_commit_id,
            'repo_group_str': repogrp_str,
            'is_starred': is_starred,
            'user_perm': user_perm,
            'img_prev': img_prev,
            'img_next': img_next,
            'search_repo_id': search_repo_id,
        },
        context_instance=RequestContext(request))
Beispiel #18
0
def home(request):
    context = {}

    all_possible_permissions = (
        Permission.objects.filter(content_type__model='')
        .order_by('name')
    )
    possible_permissions = []
    for permission in all_possible_permissions:
        if request.user.has_perm('crashstats.' + permission.codename):
            possible_permissions.append(permission)

    if request.method == 'POST':
        form = forms.GenerateTokenForm(
            request.POST,
            possible_permissions=possible_permissions
        )
        if form.is_valid():
            for permission in form.cleaned_data['permissions']:
                perm_name = 'crashstats.%s' % permission.codename
                if not request.user.has_perm(perm_name):
                    return http.HttpResponseForbidden(
                        'You do not have this permission'
                    )
            token = models.Token.objects.create(
                user=request.user,
                notes=form.cleaned_data['notes']
            )
            for permission in form.cleaned_data['permissions']:
                token.permissions.add(permission)
            return redirect('tokens:home')

    else:
        if possible_permissions:
            form = forms.GenerateTokenForm(
                possible_permissions=possible_permissions
            )
        else:
            # This is surprisingly important!
            # If you *have* permissions, you can actually create a
            # token without selecting *any* permissions. The point of
            # that is to avoid the rate limiter.
            # If you don't have any permissions attached to your user
            # account means you haven't been hand curated by any
            # administrator and if that's the case you shouldn't be able
            # avoid the rate limiter.
            form = None

    context['form'] = form
    context['your_tokens'] = (
        models.Token.objects
        .filter(user=request.user)
        .order_by('-created')
    )
    context['absolute_base_url'] = (
        '%s://%s' % (
            request.is_secure() and 'https' or 'http',
            RequestSite(request).domain
        )
    )

    return render(request, 'tokens/home.html', context)
Beispiel #19
0
def get_site(request):
    if Site._meta.installed:
        return Site.objects.get_current()
    else:
        return RequestSite(request)
Beispiel #20
0
def render_to_response(template_name,
                       context={},
                       context_instance=None,
                       response_format='html'):
    "Extended render_to_response to support different formats"

    if not response_format:
        response_format = 'html'

    if not response_format in settings.HARDTREE_RESPONSE_FORMATS:
        response_format = 'html'

    mimetype = settings.HARDTREE_RESPONSE_FORMATS[response_format]

    if 'pdf' in response_format:
        pdf_name = "report.pdf"

        while True:
            hasher = hashlib.md5()
            hasher.update(str(random.random()))
            filepath = u"pdfs/" + hasher.hexdigest()
            output = settings.MEDIA_ROOT + filepath
            if not os.path.exists(output + ".pdf"):
                break

        while True:
            hasher = hashlib.md5()
            hasher.update(str(random.random()))
            filepath = hasher.hexdigest() + ".html"
            source = getattr(settings, 'WKCWD', './') + filepath
            if not os.path.exists(source):
                break

        page_size = "A4"
        orientation = "portrait"

        rendered_string = render_to_string(template_name, context,
                                           context_instance, response_format)

        f = codecs.open(source, encoding='utf-8', mode='w')
        pdf_string = unicode(rendered_string)

        if context_instance and context_instance['request']:
            pdf_string = pdf_string.replace(
                "a href=\"/", "a href=\"http://" +
                RequestSite(context_instance['request']).domain + "/")

        pdf_string.replace("href=\"/", "href=\"")

        pattern = """Content-Type: text/html|<td>\n\W*<div class="content-list-tick">\n\W.*\n.*</div></td>|<th scope="col">Select</th>"""
        pdf_string = re.sub(pattern, "",
                            pdf_string).replace('/static/', 'static/')

        f.write(pdf_string)
        f.close()

        wkpath = getattr(settings, 'WKPATH', './bin/wkhtmltopdf-i386')
        x = subprocess.Popen(
            "%s --print-media-type --orientation %s --page-size %s %s %s" %
            (wkpath, orientation, page_size, source, output),
            shell=True,
            cwd=getattr(settings, 'WKCWD', './'))
        x.wait()

        f = open(output)
        response = HttpResponse(f.read(), mimetype='application/pdf')
        f.close()

        os.remove(output)
        os.remove(source)

        #response['Content-Disposition'] = 'attachment; filename=%s'%(pdf_name)

        return response

    if 'ajax' in response_format:
        rendered_string = render_to_ajax(template_name, context,
                                         context_instance)

    else:

        if response_format == 'html' and context_instance and context_instance[
                'request'].path[:3] == '/m/':
            context['response_format'] = response_format = 'mobile'

        if getattr(settings, 'HARDTREE_FORCE_AJAX_RENDERING', False):
            context = preprocess_context_ajax(context)

        rendered_string = render_to_string(template_name, context,
                                           context_instance, response_format)

    response = HttpResponse(rendered_string, mimetype=mimetype)

    return response
Beispiel #21
0
def login_register(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """Displays the login form and handles the login action."""

    redirect_to = request.REQUEST.get(redirect_field_name, '')

    if request.method == "POST":
        # Since this view is handeling two forms in similar ways check if either are valid
        login_form = AuthenticationForm(data=request.POST)
        login_valid = False
        if login_form.is_valid():
            login_valid = True

        register_form = UserRegisterForm(data=request.POST)
        register_valid = False
        if register_form.is_valid():
            register_valid = True

        if login_valid or register_valid:
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Heavier security check -- redirects to http://example.com should
            # not be allowed, but things like /view/?param=http://example.com
            # should be allowed. This regex checks if there is a '//' *before* a
            # question mark.
            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                redirect_to = settings.LOGIN_REDIRECT_URL

            # If they're just logining, get the user
            if login_valid:
                user = login_form.get_user()

            # If they just registered, save the user, and authenticate them
            elif register_valid:
                register_form.save()
                password = register_form.cleaned_data['password1']
                username = register_form.cleaned_data['username']
                user = authenticate(username=username, password=password)

            # Using user found in one of the above two conditionals, login
            auth_login(request, user)

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)

    else:
        login_form = AuthenticationForm(request)
        register_form = UserRegisterForm()

    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    return TemplateResponse(
        request, 'users/login_register.html', {
            'login_form': login_form,
            'register_form': register_form,
            redirect_field_name: redirect_to,
            'site': current_site,
            'site_name': current_site.name,
        })
Beispiel #22
0
def questions(request, id):
    group = QuestionGroup.objects.get(id=id)
    geometry = request.GET.get('geometry', '200x200')
    questions_qs = Question.objects.filter(group=group)
    questions = []

    base_url = '%s://%s' % (request.is_secure() and 'https'
                            or 'http', RequestSite(request).domain)

    #base_url='http://192.168.42.90'
    def absolute_url(url):
        if '://' not in url:
            url = base_url + url
        return url

    def serialize_word(word):
        data = {
            'word': word.word,
            'id': word.uuid,
        }
        if word.explanation:
            data['explanation'] = word.explanation
        if word.mp3file:
            data['mp3file'] = absolute_url(word.mp3file.url)
        if word.oggfile:
            data['oggfile'] = absolute_url(word.oggfile.url)
        return data

    words_qs = (Question.correct.through.objects.filter(
        question__in=questions_qs).filter(word__mp3file__isnull=False))

    words = defaultdict(list)
    for correct in words_qs.select_related('word', 'question'):
        word = correct.word
        if has_audio_file(word):
            words[correct.question.id].append(serialize_word(word))
        else:
            print repr(word), "lacks audio file"

    for item in questions_qs.order_by('created'):
        thumb = thumbnail(item.picture, geometry)
        question = {
            'picture': {
                'url': absolute_url(thumb.url),
                'width': thumb.width,
                'height': thumb.height
            },
            'correct': [],
            # 'incorrect': [],
        }
        question['correct'] = words[item.id]

        if question['correct']:
            questions.append(question)

    context = {
        'locale': group.locale.code,
        'group': {
            # 'locale': group.locale.code,
            'name': group.name,
            'id': group.id,
            # 'wordcount': correct_wordcount,
        },
        'questions': questions,
        # 'words': words,
    }

    return context, 200, {'Access-Control-Allow-Origin': '*'}
Beispiel #23
0
def community_admin_resend_activation(request, pk):
    # check pk is valid
    individual = get_object_or_404(IndividualProfile, pk=pk)

    # 2827
    user_profile = individual.profile
    user = user_profile.user
    registration_profile = None

    try:
        registration_profile = RegistrationProfile.objects.get(
            user__email=user.email)
    except RegistrationProfile.DoesNotExist:
        messages.error(
            request,
            _(u'{0} cannot resend activation, user has no '
              u'Registration Profile').format(individual.profile))
        return HttpResponseRedirect(
            'community_admin:profile_userprofile_changelist')

    # reset date_joined, so that existing
    # registration profile mechanism logic is retained

    # save original date if not already saved
    if user_profile.original_date_joined is None:
        user_profile.original_date_joined = user.date_joined
        user_profile.save()

    # reset date_joined, so that activation can work
    user.date_joined = datetime_now()
    user.save()

    if apps.is_installed('django.contrib.sites'):
        site = apps.get_model('sites', 'Site').objects.get_current()
    else:
        site = RequestSite(request)

    if not RegistrationProfile.objects.resend_activation_mail(
            user.email, site, request):

        if registration_profile.activated:

            messages.error(
                request,
                _(u'{0} cannot resend activation, '
                  u'user already has active Registration '
                  u'Profile').format(individual.profile))
        else:
            messages.error(
                request,
                _(u'{0} cannot resend activation, unknown '
                  u'error').format(individual.profile))

        return HttpResponseRedirect(
            'community_admin:profile_userprofile_changelist')

    # return to list view with success message
    messages.info(
        request,
        _(u'{0} activation successfully resent').format(individual.profile))

    return HttpResponseRedirect(
        'community_admin:profile_userprofile_changelist')
Beispiel #24
0
    def register(self, form):
        """
        Register a new user account, inactive user account with the specified
        username, email, and password.

        Creates a new user model object, and a new
        ``registration.models.RegistrationProfile`` tied to the new user
        and containing the activation key used for this account.

        An email will be sent to the supplied email address containing an
        activation link. The email is rendered using two templates. See the
        documentation for ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` is be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.
        """
        cleaned_data = form.cleaned_data

        username = cleaned_data['username']
        email = cleaned_data['email']
        password = cleaned_data['password1']

        # TODO: Either add some Site fixtures or remove the Sites framework
        # if Site._meta.installed:
        #     site = Site.objects.get_current()
        # else:
        request = self.request
        site = RequestSite(request)

        should_email = should_send_user_activation(
            request, username, email, password)

        user = RegistrationProfile.objects.create_inactive_user(
            site, send_email=should_email, username=username,
            email=email, password=password, request=request)

        user.first_name = cleaned_data.get('first_name', '')
        user.last_name = cleaned_data.get('last_name', '')
        user.organization = cleaned_data.get('organization', '')
        user.allow_email_contact = cleaned_data.get(
            'allow_email_contact', False)
        user.make_info_public = cleaned_data.get(
            'make_info_public', False)
        user.save_with_user(user)

        if hasattr(request, 'instance'):
            InstanceUser.objects.get_or_create(
                user=user,
                instance=request.instance,
                role=request.instance.default_role)

        signals.user_registered.send(sender=self.__class__,
                                     user=user,
                                     request=request,
                                     password=password)
        return user
Beispiel #25
0
    def get_feed(self, url=None):
        """
        Returns a feedgenerator.DefaultFeed object, fully populated, for
        this feed. Raises FeedDoesNotExist for invalid parameters.
        """
        if url:
            bits = url.split('/')
        else:
            bits = []

        try:
            obj = self.get_object(bits)
        except ObjectDoesNotExist:
            raise FeedDoesNotExist

        if Site._meta.installed:
            current_site = Site.objects.get_current()
        else:
            current_site = RequestSite(self.request)
        
        link = self.__get_dynamic_attr('link', obj)
        link = add_domain(current_site.domain, link)

        feed = self.feed_type(
            title = self.__get_dynamic_attr('title', obj),
            subtitle = self.__get_dynamic_attr('subtitle', obj),
            link = link,
            description = self.__get_dynamic_attr('description', obj),
            language = settings.LANGUAGE_CODE.decode(),
            feed_url = add_domain(current_site.domain,
                                  self.__get_dynamic_attr('feed_url', obj)),
            author_name = self.__get_dynamic_attr('author_name', obj),
            author_link = self.__get_dynamic_attr('author_link', obj),
            author_email = self.__get_dynamic_attr('author_email', obj),
            categories = self.__get_dynamic_attr('categories', obj),
            feed_copyright = self.__get_dynamic_attr('feed_copyright', obj),
            feed_guid = self.__get_dynamic_attr('feed_guid', obj),
            ttl = self.__get_dynamic_attr('ttl', obj),
            **self.feed_extra_kwargs(obj)
        )

        try:
            title_tmp = loader.get_template(self.title_template_name)
        except TemplateDoesNotExist:
            title_tmp = Template('{{ obj }}')
        try:
            description_tmp = loader.get_template(self.description_template_name)
        except TemplateDoesNotExist:
            description_tmp = Template('{{ obj }}')

        for item in self.__get_dynamic_attr('items', obj):
            link = add_domain(current_site.domain, self.__get_dynamic_attr('item_link', item))
            enc = None
            enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
            if enc_url:
                enc = feedgenerator.Enclosure(
                    url = smart_unicode(enc_url),
                    length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)),
                    mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item))
                )
            author_name = self.__get_dynamic_attr('item_author_name', item)
            if author_name is not None:
                author_email = self.__get_dynamic_attr('item_author_email', item)
                author_link = self.__get_dynamic_attr('item_author_link', item)
            else:
                author_email = author_link = None

            pubdate = self.__get_dynamic_attr('item_pubdate', item)
            if pubdate and not pubdate.tzinfo:
                now = datetime.now()
                utcnow = datetime.utcnow()

                # Must always subtract smaller time from larger time here.
                if utcnow > now:
                    sign = -1
                    tzDifference = (utcnow - now)
                else:
                    sign = 1
                    tzDifference = (now - utcnow)

                # Round the timezone offset to the nearest half hour.
                tzOffsetMinutes = sign * ((tzDifference.seconds / 60 + 15) / 30) * 30
                tzOffset = timedelta(minutes=tzOffsetMinutes)
                pubdate = pubdate.replace(tzinfo=FixedOffset(tzOffset))

            feed.add_item(
                title = title_tmp.render(RequestContext(self.request, {'obj': item, 'site': current_site})),
                link = link,
                description = description_tmp.render(RequestContext(self.request, {'obj': item, 'site': current_site})),
                unique_id = self.__get_dynamic_attr('item_guid', item, link),
                enclosure = enc,
                pubdate = pubdate,
                author_name = author_name,
                author_email = author_email,
                author_link = author_link,
                categories = self.__get_dynamic_attr('item_categories', item),
                item_copyright = self.__get_dynamic_attr('item_copyright', item),
                **self.item_extra_kwargs(item)
            )
        return feed
Beispiel #26
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)

    if request.method == "POST":
        if request.REQUEST.get('captcha_0', '') != '':
            # have captcha
            form = CaptchaAuthenticationForm(data=request.POST)
            if form.is_valid():
                # captcha & passwod is valid, log user in
                remember_me = True if request.REQUEST.get(
                    'remember_me', '') == 'on' else False
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                # show page with captcha and increase failed login attempts
                _incr_login_faied_attempts(ip=ip)
        else:
            form = authentication_form(data=request.POST)
            if form.is_valid():
                # password is valid, log user in
                remember_me = True if request.REQUEST.get(
                    'remember_me', '') == 'on' else False
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                username = urlquote(
                    request.REQUEST.get('username', '').strip())
                failed_attempt = _incr_login_faied_attempts(username=username,
                                                            ip=ip)

                if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
                    logger.warn(
                        'Login attempt limit reached, username: %s, ip: %s, attemps: %d'
                        % (username, ip, failed_attempt))
                    form = CaptchaAuthenticationForm()
                else:
                    form = authentication_form(data=request.POST)
    else:
        ### GET
        failed_attempt = _get_login_failed_attempts(ip=ip)
        if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
            logger.warn('Login attempt limit reached, ip: %s, attempts: %d' %
                        (ip, failed_attempt))
            form = CaptchaAuthenticationForm(request)
        else:
            form = authentication_form(request)

    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    enable_signup = getattr(settings, 'ENABLE_SIGNUP', False)
    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)
    if enable_signup:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': settings.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
    },
                              context_instance=RequestContext(request))
Beispiel #27
0
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page
    """
    username = request.user.username
    path = get_path_from_request(request)
    user_perm = check_repo_access_permission(repo.id, request.user)
    if user_perm is None:
        return render_error(request, _(u'Permission denied'))

    sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username)

    server_crypto = False
    if repo.encrypted:
        try:
            server_crypto = UserOptions.objects.is_server_crypto(username)
        except CryptoOptionNotSetError:
            return render_to_response('options/set_user_options.html', {},
                                      context_instance=RequestContext(request))

        if (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
                and not is_password_set(repo.id, username):
            return render_to_response('decrypt_repo_form.html', {
                'repo':
                repo,
                'next':
                get_next_url_from_request(request)
                or reverse('repo', args=[repo.id]),
                'force_server_crypto':
                FORCE_SERVER_CRYPTO,
            },
                                      context_instance=RequestContext(request))

    # query context args
    fileserver_root = get_fileserver_root()
    max_upload_file_size = get_max_upload_file_size()

    protocol = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain

    for g in request.user.joined_groups:
        g.avatar = grp_avatar(g.id, 20)

    head_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id)
    if not head_commit:
        raise Http404

    if new_merge_with_no_conflict(head_commit):
        info_commit = get_commit_before_new_merge(head_commit)
    else:
        info_commit = head_commit

    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    if is_org_context(request):
        repo_owner = seafile_api.get_org_repo_owner(repo.id)
    else:
        repo_owner = seafile_api.get_repo_owner(repo.id)
    is_repo_owner = True if repo_owner == username else False
    if is_repo_owner and not repo.is_virtual:
        show_repo_settings = True
    else:
        show_repo_settings = False

    file_list, dir_list, dirent_more = get_repo_dirents_with_perm(request,
                                                                  repo,
                                                                  head_commit,
                                                                  path,
                                                                  offset=0,
                                                                  limit=100)
    more_start = None
    if dirent_more:
        more_start = 100
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html",
                                          {'groups': repo_groups})
    else:
        repo_group_str = ''

    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_dir_share_link(fileshare)
    uploadlink = get_uploadlink(repo.id, username, path)
    dir_shared_upload_link = get_dir_shared_upload_link(uploadlink)

    for f in file_list:
        file_type, file_ext = get_file_type_and_ext(f.obj_name)
        if file_type == IMAGE:
            f.is_img = True
            file_path = posixpath.join(path, f.obj_name)
            if os.path.exists(
                    os.path.join(THUMBNAIL_ROOT, str(THUMBNAIL_DEFAULT_SIZE),
                                 f.obj_id)):
                src = get_thumbnail_src(repo.id, THUMBNAIL_DEFAULT_SIZE,
                                        file_path)
                f.encoded_thumbnail_src = urlquote(src)

    return render_to_response('repo.html', {
        'repo': repo,
        'user_perm': user_perm,
        'repo_owner': repo_owner,
        'is_repo_owner': is_repo_owner,
        'show_repo_settings': show_repo_settings,
        'current_commit': head_commit,
        'info_commit': info_commit,
        'password_set': True,
        'repo_size': repo_size,
        'dir_list': dir_list,
        'file_list': file_list,
        'dirent_more': dirent_more,
        'more_start': more_start,
        'path': path,
        'zipped': zipped,
        'groups': repo_groups,
        'repo_group_str': repo_group_str,
        'no_quota': no_quota,
        'max_upload_file_size': max_upload_file_size,
        'fileserver_root': fileserver_root,
        'protocol': protocol,
        'domain': domain,
        'fileshare': fileshare,
        'dir_shared_link': dir_shared_link,
        'uploadlink': uploadlink,
        'dir_shared_upload_link': dir_shared_upload_link,
        'ENABLE_SUB_LIBRARY': ENABLE_SUB_LIBRARY,
        'server_crypto': server_crypto,
        'sub_lib_enabled': sub_lib_enabled,
        'enable_upload_folder': ENABLE_UPLOAD_FOLDER,
        'ENABLE_THUMBNAIL': ENABLE_THUMBNAIL,
    },
                              context_instance=RequestContext(request))
Beispiel #28
0
  def get_feed(self, obj, request):
        """
        Returns a feedgenerator.DefaultFeed object, fully populated, for
        this feed. Raises FeedDoesNotExist for invalid parameters.
        """
        #print "ARGH! ",
        #print Site._meta.installed,
        #print " (" + str(Site.objects.get_current()) + "), )",
        #print ", ",
        #print RequestSite(request)
        #if Site._meta.installed:
        #    current_site = Site.objects.get_current()
        #else:
        current_site = RequestSite(request)

        link = self.__get_dynamic_attr('link', obj)
        link = add_domain(current_site.domain, link)

        feed = self.feed_type(
            title = self.__get_dynamic_attr('title', obj),
            subtitle = self.__get_dynamic_attr('subtitle', obj),
            link = link,
            description = self.__get_dynamic_attr('description', obj),
            language = settings.LANGUAGE_CODE.decode(),
            feed_url = add_domain(current_site.domain,
                    self.__get_dynamic_attr('feed_url', obj) or request.path),
            author_name = self.__get_dynamic_attr('author_name', obj),
            author_link = self.__get_dynamic_attr('author_link', obj),
            author_email = self.__get_dynamic_attr('author_email', obj),
            categories = self.__get_dynamic_attr('categories', obj),
            feed_copyright = self.__get_dynamic_attr('feed_copyright', obj),
            feed_guid = self.__get_dynamic_attr('feed_guid', obj),
            ttl = self.__get_dynamic_attr('ttl', obj),
            **self.feed_extra_kwargs(obj)
        )

        title_tmp = None
        if self.title_template is not None:
            try:
                title_tmp = loader.get_template(self.title_template)
            except TemplateDoesNotExist:
                pass

        description_tmp = None
        if self.description_template is not None:
            try:
                description_tmp = loader.get_template(self.description_template)
            except TemplateDoesNotExist:
                pass

        for item in self.__get_dynamic_attr('items', obj):
            if title_tmp is not None:
                title = title_tmp.render(RequestContext(request, {'obj': item, 'site': current_site}))
            else:
                title = self.__get_dynamic_attr('item_title', item)
            if description_tmp is not None:
                description = description_tmp.render(RequestContext(request, {'obj': item, 'site': current_site}))
            else:
                description = self.__get_dynamic_attr('item_description', item)
            link = add_domain(current_site.domain, self.__get_dynamic_attr('item_link', item))
            enc = None
            enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
            if enc_url:
                enc = feedgenerator.Enclosure(
                    url = smart_unicode(enc_url),
                    length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)),
                    mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item))
                )
            author_name = self.__get_dynamic_attr('item_author_name', item)
            if author_name is not None:
                author_email = self.__get_dynamic_attr('item_author_email', item)
                author_link = self.__get_dynamic_attr('item_author_link', item)
            else:
                author_email = author_link = None

            pubdate = self.__get_dynamic_attr('item_pubdate', item)
            if pubdate and not pubdate.tzinfo:
                ltz = tzinfo.LocalTimezone(pubdate)
                pubdate = pubdate.replace(tzinfo=ltz)

            feed.add_item(
                title = title,
                link = link,
                description = description,
                unique_id = self.__get_dynamic_attr('item_guid', item, link),
                enclosure = enc,
                pubdate = pubdate,
                author_name = author_name,
                author_email = author_email,
                author_link = author_link,
                categories = self.__get_dynamic_attr('item_categories', item),
                item_copyright = self.__get_dynamic_attr('item_copyright', item),
                **self.item_extra_kwargs(item)
            )
        return feed
Beispiel #29
0
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page
    """
    username = request.user.username
    path = get_path_from_request(request)
    user_perm = check_repo_access_permission(repo.id, request.user)
    if user_perm is None:
        return render_to_response('repo_access_deny.html', {
                'repo': repo,
                }, context_instance=RequestContext(request))

    sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username)

    server_crypto = False
    if repo.encrypted:
        try:
            server_crypto = UserOptions.objects.is_server_crypto(username)
        except CryptoOptionNotSetError:
            return render_to_response('options/set_user_options.html', {
                    }, context_instance=RequestContext(request))
            
        if (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
                and not is_password_set(repo.id, username):
            return render_to_response('decrypt_repo_form.html', {
                    'repo': repo,
                    'next': get_next_url_from_request(request) or \
                        reverse('repo', args=[repo.id]),
                    'force_server_crypto': FORCE_SERVER_CRYPTO,
                    }, context_instance=RequestContext(request))

    # query context args
    applet_root = get_ccnetapplet_root()
    httpserver_root = get_httpserver_root()
    max_upload_file_size = get_max_upload_file_size()
    
    protocol = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain

    contacts = Contact.objects.get_contacts_by_user(username)
    joined_groups = get_personal_groups_by_user(request.user.username)

    head_commit = get_commit(repo.head_cmmt_id)
    if not head_commit:
        raise Http404
    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    search_repo_id = None if repo.encrypted else repo.id
    repo_owner = seafile_api.get_repo_owner(repo.id)
    is_repo_owner = True if repo_owner == username else False
    
    more_start = None
    file_list, dir_list, dirent_more = get_repo_dirents(request, repo.id, head_commit, path, offset=0, limit=100)
    if dirent_more:
        more_start = 100
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html",
                                          {'groups': repo_groups})
    else:
        repo_group_str = ''
    upload_url = get_upload_url(request, repo.id)

    if repo.encrypted and repo.enc_version == 2 and not server_crypto:
        ajax_upload_url = get_blks_upload_url(request, repo.id)
        ajax_update_url = get_blks_update_url(request, repo.id)
    else:
        ajax_upload_url = get_ajax_upload_url(request, repo.id)
        ajax_update_url = get_ajax_update_url(request, repo.id)
    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_dir_share_link(fileshare)
    uploadlink = get_uploadlink(repo.id, username, path)
    dir_shared_upload_link = get_dir_shared_upload_link(uploadlink)

    return render_to_response('repo.html', {
            'repo': repo,
            'user_perm': user_perm,
            'repo_owner': repo_owner,
            'is_repo_owner': is_repo_owner,
            'current_commit': head_commit,
            'password_set': True,
            'repo_size': repo_size,
            'dir_list': dir_list,
            'file_list': file_list,
            'dirent_more': dirent_more,
            'more_start': more_start,
            'path': path,
            'zipped': zipped,
            'applet_root': applet_root,
            'groups': repo_groups,
            'joined_groups': joined_groups,
            'repo_group_str': repo_group_str,
            'no_quota': no_quota,
            'max_upload_file_size': max_upload_file_size,
            'upload_url': upload_url,
            'ajax_upload_url': ajax_upload_url,
            'ajax_update_url': ajax_update_url,
            'httpserver_root': httpserver_root,
            'protocol': protocol,
            'domain': domain,
            'contacts': contacts,
            'fileshare': fileshare,
            'dir_shared_link': dir_shared_link,
            'uploadlink': uploadlink,
            'dir_shared_upload_link': dir_shared_upload_link,
            'search_repo_id': search_repo_id,
            'ENABLE_SUB_LIBRARY': ENABLE_SUB_LIBRARY,
            'server_crypto': server_crypto,
            "sub_lib_enabled": sub_lib_enabled,
            }, context_instance=RequestContext(request))
Beispiel #30
0
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page
    """
    username = request.user.username
    path = get_path_from_request(request)
    user_perm = check_repo_access_permission(repo.id, username)
    if user_perm is None:
        return render_to_response('repo_access_deny.html', {
            'repo': repo,
        },
                                  context_instance=RequestContext(request))

    if repo.encrypted and not is_password_set(repo.id, username):
        return render_to_response('decrypt_repo_form.html', {
                'repo': repo,
                'next': get_next_url_from_request(request) or \
                    reverse('repo', args=[repo.id])
                }, context_instance=RequestContext(request))

    # query context args
    applet_root = get_ccnetapplet_root()
    httpserver_root = get_httpserver_root()
    max_upload_file_size = MAX_UPLOAD_FILE_SIZE

    protocol = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain

    contacts = Contact.objects.get_contacts_by_user(username)
    accessible_repos = [
        repo
    ] if repo.encrypted else get_unencry_rw_repos_by_user(username)

    head_commit = get_commit(repo.head_cmmt_id)
    if not head_commit:
        raise Http404
    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    history_limit = seaserv.get_repo_history_limit(repo.id)
    search_repo_id = None if repo.encrypted else repo.id

    is_repo_owner = seafile_api.is_repo_owner(username, repo.id)
    more_start = None
    file_list, dir_list, dirent_more = get_repo_dirents(request,
                                                        repo.id,
                                                        head_commit,
                                                        path,
                                                        offset=0,
                                                        limit=100)
    if dirent_more:
        more_start = 100
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html",
                                          {'groups': repo_groups})
    else:
        repo_group_str = ''
    upload_url = get_upload_url(request, repo.id)
    ajax_upload_url = get_ajax_upload_url(request, repo.id)
    ajax_update_url = get_ajax_update_url(request, repo.id)
    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_dir_share_link(fileshare)

    joined_groups = get_personal_groups_by_user(request.user.username)

    return render_to_response('repo.html', {
        'repo': repo,
        'user_perm': user_perm,
        'is_repo_owner': is_repo_owner,
        'current_commit': head_commit,
        'password_set': True,
        'repo_size': repo_size,
        'dir_list': dir_list,
        'file_list': file_list,
        'dirent_more': dirent_more,
        'more_start': more_start,
        'path': path,
        'zipped': zipped,
        'accessible_repos': accessible_repos,
        'applet_root': applet_root,
        'groups': repo_groups,
        'joined_groups': joined_groups,
        'repo_group_str': repo_group_str,
        'no_quota': no_quota,
        'max_upload_file_size': max_upload_file_size,
        'upload_url': upload_url,
        'ajax_upload_url': ajax_upload_url,
        'ajax_update_url': ajax_update_url,
        'httpserver_root': httpserver_root,
        'protocol': protocol,
        'domain': domain,
        'contacts': contacts,
        'fileshare': fileshare,
        'dir_shared_link': dir_shared_link,
        'history_limit': history_limit,
        'search_repo_id': search_repo_id,
        'ENABLE_SUB_LIBRARY': ENABLE_SUB_LIBRARY,
    },
                              context_instance=RequestContext(request))