def get_initial_values(self,):
     """
     Return initial values for configuration.
     The only subtlety here is that we fetch the 'domain' from 
     django's Site framework.
     """
     current_site = Site.objects.get_current()
     if current_site.domain == "example.com" or True:
         # Display a more intelligent default domain
         domain = RequestSite(self.request).domain
         if 'HTTPS' in self.request.META['SERVER_PROTOCOL']:
             protocol = "https://"
         else:
             protocol = "http://"
         domain = "%s%s" % (protocol, domain)
     else:
         domain = current_site.domain
         if not domain.lower().startswith('http'):
             domain = "http://%s" % domain
     
     if not domain.endswith('/'):
         domain = "%s/" % domain
     return {
         "domain":   domain
     }
Example #2
0
 def get_current_site(self):
     """
     Checks if the sites app is installed and returns a ``RequestSite``
     instance if not.
     """
     if Site._meta.installed:
         return Site.objects.get_current()
     return RequestSite(self.request)
Example #3
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.

        """
        name, surname, email, password, type = cleaned_data['name'], cleaned_data['surname'], cleaned_data['email'], \
                                               cleaned_data['password1'], cleaned_data['type']
        bii = request.POST.get('bii')
        if bii == 'true':
            bii = bool(bii)
        language = request.LANGUAGE_CODE[0:2]
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        if bii == True:
            new_user = RegistrationProfile.objects.create_active_user(name, surname, email,
                                                                      password, language, type, site,bii=bii, send_email=False)
        else:
            new_user = RegistrationProfile.objects.create_active_user(name, surname, email,
                                                                      password, language, type, site)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        # send mail

        # server = smtplib.SMTP('smtp.gmail.com', 587)
        # server.starttls()
        # server.login("*****@*****.**", "tobuildornottobuild00")

        # msg = "Your account is created."
        # server.sendmail("*****@*****.**", '%s' % cleaned_data['email'], msg)
        # server.quit()

        # end send mail
        new_user.backend = 'chefs.backends.auth.EmailAuthBackend'
        login(request, new_user)

        return new_user
Example #4
0
    def get_feed(self,
                 obj,
                 request,
                 reverse_name,
                 feed_type=None,
                 *args,
                 **kwargs):
        """
		Returns an unpopulated :class:`django.utils.feedgenerator.DefaultFeed` object for this object.
		
		:param obj: The object for which the feed should be generated.
		:param request: The current request.
		:param reverse_name: The name which can be used to reverse the URL of the page corresponding to this feed.
		:param feed_type: The slug used to register the feed class that will be instantiated and returned.
		
		:returns: An instance of the feed class registered as ``feed_type``, falling back to :attr:`feed_type` if ``feed_type`` is ``None``.
		
		"""
        try:
            current_site = Site.objects.get_current()
        except Site.DoesNotExist:
            current_site = RequestSite(request)

        feed_type = self.get_feed_type(request, feed_type)
        node = request.node
        link = node.construct_url(self.reverse(reverse_name,
                                               args=args,
                                               kwargs=kwargs),
                                  with_domain=True,
                                  request=request,
                                  secure=request.is_secure())

        feed = 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 node.construct_url(self.reverse(
                    "%s_%s" % (reverse_name, registry.get_slug(feed_type)),
                    args=args,
                    kwargs=kwargs),
                                      with_domain=True,
                                      request=request,
                                      secure=request.is_secure()),
                request.is_secure()),
            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))
        return feed
Example #5
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 settings.ACTIVATE_AFTER_REGISTRATION == 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=settings.REGISTRATION_SEND_MAIL)

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

        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Example #6
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']
        title, first_name, last_name = cleaned_data['title'], cleaned_data[
            'first_name'], cleaned_data['last_name']
        university, department = cleaned_data['university'], cleaned_data[
            'department']
        address, country, phone = cleaned_data['address'], cleaned_data[
            'country'], cleaned_data['phone']

        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(
            username,
            email,
            password,
            title=title,
            first_name=first_name,
            last_name=last_name,
            site=site,
            university=university,
            department=department,
            address=address,
            country=country,
            phone=phone,
            send_email=self.SEND_ACTIVATION_EMAIL,
            request=request,
        )
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Example #7
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.

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

        # We are creating a user with the same email address. We have already
        # verified in ``forms.py`` that this isn't a mistake. Go ahead and pull
        # the existing user from the DB and return that user instead.
        if User.objects.filter(email__iexact=email):
            new_user = User.objects.filter(email__iexact=email)[0]
            new_user.username = username
            new_user.set_password(password)
            new_user.save()

            # Resave their profile also (updates the slug)
            new_user_profile = UserProfile.objects.get(user=new_user)
            new_user_profile.save()

            # Complete the activation email part
            registration_profile = RegistrationProfile.objects.create_profile(
                new_user)
            registration_profile.send_activation_email(site)
        else:

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

        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Example #8
0
def event_assignments_ical(request):
    cache_key = 'event_assignements_ical'
    assignee = request.GET.get('assignee')

    if assignee:
        assignee = get_object_or_404(User, email=assignee)
        cache_key += str(assignee.pk)

    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 = EventAssignment.objects.all().order_by('-event__start_time')
    if assignee:
        base_qs = base_qs.filter(users=assignee)

    title = 'Airmo'
    if assignee:
        title += ' for %s' % assignee.email
    cal.add('X-WR-CALNAME').value = title
    assignments = list(
        base_qs.filter(event__start_time__lt=now)[:settings.CALENDAR_SIZE])
    assignments += list(base_qs.filter(event__start_time__gte=now))
    base_url = '%s://%s' % (request.is_secure() and 'https'
                            or 'http', RequestSite(request).domain)
    for assignment in assignments:
        event = assignment.event
        vevent = cal.add('vevent')
        vevent.add('summary').value = "[AirMo crew] %s" % event.title
        # Adjusted start times for Event Assignment iCal feeds
        # to allow staff sufficient time for event set-up.
        vevent.add('dtstart').value = (event.start_time -
                                       datetime.timedelta(minutes=30))
        vevent.add('dtend').value = (event.start_time +
                                     datetime.timedelta(hours=1))
        vevent.add('description').value = unhtml(short_desc(event))
        vevent.add('url').value = (base_url +
                                   reverse('main:event', args=(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 = 'AirMozillaEventAssignments'
    filename += '.ics'
    response['Content-Disposition'] = ('inline; filename=%s' % filename)
    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
Example #9
0
 def get_context(self):
     if not self.is_valid():
         raise ValueError("Cannot generate Context " +
                          "from invalid contact form")
     if Site._meta.installed:
         site = Site.objects.get_current()
     else:
         site = RequestSite(self.request)
     return RequestContext(self.request, dict(self.cleaned_data, site=site))
Example #10
0
def fix_base_url(base_url):
    """because most of the functions in this file can take either a
    base_url (string) or a request, we make this easy with a quick
    fixing function."""
    if isinstance(base_url, WSGIRequest):
        request = base_url
        protocol = 'https' if request.is_secure() else 'http'
        base_url = '%s://%s' % (protocol, RequestSite(request).domain)
    return base_url
Example #11
0
def gen_shared_link(request, token, s_type):
    http_or_https = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain
    site_root = seahub.settings.SITE_ROOT

    if s_type == 'f':
        return '%s://%s%sf/%s/' % (http_or_https, domain, site_root, token)
    else:
        return '%s://%s%sd/%s/' % (http_or_https, domain, site_root, token)
Example #12
0
def sitemap(request):
    base_url = 'http://%s' % RequestSite(request).domain

    urls = []
    urls.append('<?xml version="1.0" encoding="iso-8859-1"?>')
    urls.append('<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">')

    def add(loc, lastmod=None, changefreq='monthly', priority=None):
        url = '<url><loc>%s%s</loc>' % (base_url, loc)
        if lastmod:
            url += '<lastmod>%s</lastmod>' % lastmod.strftime('%Y-%m-%d')
        if priority:
            url += '<priority>%s</priority>' % priority
        if changefreq:
            url += '<changefreq>%s</changefreq>' % changefreq
        url += '</url>'
        urls.append(url)

    now = utc_now()
    latest_blogitem, = (BlogItem.objects.filter(
        pub_date__lt=now).order_by('-pub_date')[:1])
    add('/',
        priority=1.0,
        changefreq='daily',
        lastmod=latest_blogitem.pub_date)
    add(reverse('about'), changefreq='weekly', priority=0.5)
    add(reverse('contact'), changefreq='weekly', priority=0.5)

    for blogitem in (BlogItem.objects.filter(
            pub_date__lt=now).order_by('-pub_date')[:1000]):
        if not blogitem.modify_date:
            # legacy!
            try:
                latest_comment, = (BlogComment.objects.filter(
                    approved=True,
                    blogitem=blogitem).order_by('-add_date')[:1])
                blogitem.modify_date = latest_comment.add_date
            except ValueError:
                blogitem.modify_date = blogitem.pub_date
            blogitem._modify_date_set = True
            blogitem.save()

        age = (now - blogitem.modify_date).days
        if age < 14:
            changefreq = 'daily'
        elif age < 60:
            changefreq = 'weekly'
        elif age < 100:
            changefreq = 'monthly'
        else:
            changefreq = None
        add(reverse('blog_post', args=[blogitem.oid]),
            lastmod=blogitem.modify_date,
            changefreq=changefreq)

    urls.append('</urlset>')
    return http.HttpResponse('\n'.join(urls), mimetype="text/xml")
Example #13
0
def create_welcome_email(user, request):
    # fish out all the relevant information about the user and
    # then create an unsent WelcomeEmail

    subject = u"Welcome to %s" % settings.PROJECT_NAME
    try:
        person = user.get_profile()
    except KungfuPerson.DoesNotExist:
        return None

    alu = AutoLoginKey.get_or_create(user)
    profile_url = reverse('person.view', args=(user.username, ))
    upload_photo_url = reverse('upload_profile_photo', args=(user.username, ))
    change_password_url = reverse("edit_password", args=(user.username, ))
    edit_style_url = reverse("edit_style", args=(user.username, ))
    edit_club_url = reverse("edit_club", args=(user.username, ))
    edit_profile_url = reverse("edit_profile", args=(user.username, ))

    data = locals()

    domain = RequestSite(request).domain
    base_url = 'http://%s' % domain

    # for every variable that ends with _url make it an absolute url
    # and add the _alu variable
    def aluify_url(url):
        if '?' in url:
            return url + '&alu=%s' % alu.uuid
        else:
            return url + '?alu=%s' % alu.uuid

    keys = list(data.keys())
    for key in keys:
        if key.endswith('_url'):
            url = data[key]
            if url.startswith('/'):
                url = base_url + url
            data[key] = url
            data[key + '_alu'] = aluify_url(url)

    # now the interesting thing starts. We need to find out what they haven't
    # done with their profile and pester them about that.
    response = render(request, 'welcome-email.html', data)
    html = response.content

    html = Premailer(
        html,
        base_url=base_url,
        keep_style_tags=False,
    ).transform()

    return WelcomeEmail.objects.create(
        user=user,
        subject=subject,
        body=html,
    )
Example #14
0
    def process_request(self, request):
        """
         First get the domain name of the current website :
            a : It could be a primary domain name then get the Website object
            b : It could be a secondary domain name then PermanentRedirect 
                to the primary one.
        """

        assert hasattr(request,
                       'user'), "The ProvideWebSiteMiddleware requires"
        " the AuthenticationMiddleware to be installed. Edit your"
        " MIDDLEWARE_CLASSES setting to insert"
        " 'django.contrib.auth.middleware.AuthenticationMiddleware' before it."

        # if settings.DEBUG:
        #     print "-"*25, "\nProvideWebSiteMiddleware()\n", "-"*25

        current_domain = RequestSite(request).domain
        request.website = None
        request.is_admin = False
        request.is_superuser = False

        try:
            # if settings.DEBUG:
            #     print "current_domain :", current_domain
            request.website = WebSite.objects.get(ndds__domain=current_domain)

            # if settings.DEBUG:
            #     print "REQUEST WEBSITE -----> ", request.website

            # Est-ce le domain principal
            # if settings.DEBUG:
            #     print "request.website.domain : ", request.website.domain
            if current_domain != request.website.domain.domain:
                return HttpResponsePermanentRedirect(
                    request.website.get_absolute_url())

            # Vérification des droits de l'utilisateur
            if request.user.is_authenticated():
                try:
                    owner = request.website.websites_owned.get(
                        user=request.user)
                    request.is_admin = True
                    request.is_superuser = owner.is_superuser
                except WebSiteOwner.DoesNotExist:
                    request.is_admin = request.is_superuser = request.user.is_staff

        except WebSite.DoesNotExist:
            if not request.path.startswith('/_'):
                return HttpResponseRedirect('/_install/')
            return None
        except DatabaseError:
            return render_to_response('errors/database_error.html',
                                      context_instance=RequestContext(request))

        return None
Example #15
0
def request_swap(request):
    pk = request.POST.get('pk')
    if not pk:
        raise http.Http404("No 'pk'")
    slot = get_object_or_404(Slot, pk=pk)

    user_name = get_user_name(request.user)
    slot.swap_needed = True
    slot.save()

    comment = request.POST.get('comment', u'').strip()
    swap = Swap.objects.create(
      slot=slot,
      user=None,
      type=Swap.TYPE_REQUEST,
      comment=comment,
    )
    base_url = '%s://%s' % (request.is_secure() and 'https' or 'http',
                            RequestSite(request).domain)
    accept_url = base_url + reverse('roster.accept_swap', args=[swap.uuid])
    #decline_url = base_url + reverse('roster.decline_swap', args=[swap.uuid])

    template = loader.get_template('roster/request_swap.txt')
    context = {
      'user_name': user_name,
      'slot': slot,
      'settings': settings,
      'accept_url': accept_url,
      #'decline_url': decline_url,
      'date_formatted': slot.date.strftime(settings.DEFAULT_DATE_FORMAT),
      'comment': comment,
    }
    body = template.render(Context(context)).strip()
    subject = 'Request to swap Sheriff duty'
    from_ = request.user.email
    if getattr(settings, 'MAILINGLIST_EMAIL', None):
        tos = [settings.MAILINGLIST_EMAIL]
    else:
        tos = [x[0] for x in (Slot.objects
                              .filter(date__gte=datetime.date.today())
                              .exclude(user__email=request.user.email)
                              .select_related('user')
                              .values_list('user__email')
                              )
               if x]
    worked = send_mail(subject, body, from_, tos)

    if worked:
        messages.info(request,
                      'An email as been sent to %s' %
                        ', '.join(tos))
    else:
        messages.warning(request,
                        'Email could NOT be sent to %s' %
                          ', '.join(tos))
    return redirect(reverse('cal.home'))
Example #16
0
    def register(self, request, **cleaned_data):
        """
        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.
        """
        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:
        site = RequestSite(request)

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

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

        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
def site(request):
    """
    Grabs the 'site' app's information, and makes it availile to templates
    """
    site_info = {'protocol': request.is_secure() and 'https' or 'http'}
    if Site._meta.installed:
        site_info['domain'] = Site.objects.get_current().domain
    else:
        site_info['domain'] = RequestSite(request).domain
    return site_info
Example #18
0
 def send_confirmation_email(self, profile):
     ctxt = {
         'site': RequestSite(self.request),
         'profile': profile,
     }
     body = loader.render_to_string('cloud_profiles/registration_email.txt',
                                    ctxt).strip()
     subject = 'Ibercloud account confirmation'
     send_mail(subject, body, 'ibergrid cloud <*****@*****.**>',
               [profile.email])
Example #19
0
 def send_password_reset_email(self, profile):
     ctxt = {
         'site': RequestSite(self.request),
         'profile': profile,
     }
     body = loader.render_to_string('cloud_profiles/activation_email.txt',
                                    ctxt).strip()
     subject = 'Your Ibercloud account is now active'
     send_mail(subject, body, 'ibergrid cloud <*****@*****.**>',
               [profile.email])
Example #20
0
 def get_current_site(request):
     """
     Checks if contrib.sites is installed and returns either the current
     ``Site`` object or a ``RequestSite`` object based on the request.
     """
     if Site._meta.installed:
         current_site = Site.objects.get_current()
     else:
         current_site = RequestSite(request)
     return current_site
Example #21
0
 def save(self,request):
   cleaned_data = self.cleaned_data
   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)
   signals.user_registered.send(sender=self.__class__,user=new_user,request=request)
   return new_user
Example #22
0
def view_events(request):
    if request.method == "GET":
        context = {
            'events': fetch(request),
            'site': RequestSite(request),
            'protocol': 'https' if request.is_secure() else 'http'
        }
        return render_to_response("events.html", context)
    else:
        return post_event(request)
Example #23
0
def make_absolute(context, uri):
    if '://' not in uri:
        request = context['request']
        prefix = request.is_secure() and 'https' or 'http'
        if uri.startswith('//'):
            # we only need the prefix
            uri = '%s:%s' % (prefix, uri)
        else:
            uri = '%s://%s%s' % (prefix, RequestSite(request).domain, uri)
    return uri
Example #24
0
def site(request):
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)
    context = {
        'site': site,
        'login_form': AuthenticationForm(),
    }
    return context
Example #25
0
def get_site(request=None):
    site = None
    root_url = 'http://localhost'
    if Site._meta.installed:
        site = Site.objects.get_current()
        root_url = 'http://%s' % site.domain
    else:
        if request:
            site = RequestSite(request)
    return site, root_url
Example #26
0
 def get_default_context(self, event, request):
     context = {}
     prefix = request.is_secure() and 'https' or 'http'
     root_url = '%s://%s' % (prefix, RequestSite(request).domain)
     url = reverse('main:event', kwargs={'slug': event.slug})
     context['absolute_url'] = root_url + url
     context['embedded'] = self.embedded
     context['no_warning'] = self.no_warning
     context['no_footer'] = request.GET.get('no-footer')
     return context
Example #27
0
def lugati_register(request):
    response_data = {}
    if request.method == 'POST':
        form = LugatiRegistrationForm(data=json.loads(request.body))
        if form.is_valid():
            cleaned_data = form.cleaned_data

            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.attach_alternative(message_html, "text/html")
                msg.send()
            except Exception, e:
                logger.error(str(e))
            #~mail

            signals.user_registered.send(sender="lugati_register",
                                         user=new_user,
                                         request=request)
            # return new_user
        else:
            response_data['errors'] = form.errors
Example #28
0
def widget_factory(request):  # pragma: no cover
    data = {}

    this_domain = RequestSite(request).domain
    default_options = [
      ('use_date_labels', False,
       'whether to say "Today" or "Thursday" instead of the full date'),
      ('limit', 5, 'number of items to display'),
      ('root_css', '',
       'possible extra CSS added to the root widget element (e.g. color:#ccc)'),
      ('include_footer', True,
       'include the footer link back to Mozilla Sheriffs Duty'),
      ('host_name', this_domain,
       'this default host name (unlikely to change)'),
      ('root_node_id', 'sheriffs_widget',
       'the ID name of the widget in the DOM tree (unlikely to change)'),
    ]
    default_options_javascript = []
    _longest = max(len('%s %s' % (x, y)) for (x, y, z) in default_options)
    for i, (key, value, comment) in enumerate(default_options):
        if isinstance(value, bool):
            value = str(value).lower()
        elif isinstance(value, basestring):
            value = "'%s'" % value
        comma = (i + 1) < len(default_options) and ',' or ''
        _length = len('%s %s' % (key, value))
        if i == len(default_options) - 1:
            # last option, no comma
            _length -= 1
        whitespace = ' ' * (_longest - _length + 2)
        default_options_javascript.append("%s: %s%s%s// %s" %
          (key, value, comma, whitespace, comment)
        )
    default_options_javascript = '\n'.join(
      '  ' + x for x in default_options_javascript)

    default_code = """
<script>
// all the default options (feel free to delete what you don't change)
var sheriff_options = {
%(default_options_javascript)s
};
</script>
<script src="%(widget_src_url)s"></script>
    """.strip()

    widget_src_url = '//%s' % this_domain
    widget_src_url += '/media/js/widget.js'
    data['default_code'] = default_code % {
      'widget_src_url': widget_src_url,
      'default_options_javascript': default_options_javascript,
    }
    data['count_default_code_lines'] = len(data['default_code'].splitlines())
    data['default_options'] = default_options
    return jingo.render(request, 'roster/widget_factory.html', data)
Example #29
0
def login(request,
          template_name='emailauth/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME):

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

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            from django.contrib.auth import login
            login(request, form.get_user())

            if request.get_host() == 'testserver':
                if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                    redirect_to = settings.LOGIN_REDIRECT_URL
                return HttpResponseRedirect(redirect_to)

            request.session.set_test_cookie()

            return HttpResponseRedirect(
                settings.LOGIN_URL + '?' +
                urlencode({
                    'testcookiesupport': '',
                    redirect_field_name: redirect_to,
                }))
    elif 'testcookiesupport' in request.GET:
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            return HttpResponseRedirect(redirect_to)
        else:
            form = LoginForm()
            errorlist = forms.util.ErrorList()
            errorlist.append(
                _("Your Web browser doesn't appear to "
                  "have cookies enabled. Cookies are required for logging in.")
            )
            form._errors = forms.util.ErrorDict()
            form._errors[forms.forms.NON_FIELD_ERRORS] = errorlist
    else:
        form = LoginForm()

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

    return render_to_response(template_name, {
        'form': form,
        'redirect_field_name': redirect_field_name,
        'redirect_to': redirect_to,
        'site_name': current_site.name,
    },
                              context_instance=RequestContext(request))
Example #30
0
def import_user(request):
    """ View in the admin """
    if request.method == 'POST':
        form = ImportForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                imported_user = User.import_user(form.files['file'])
                request.user.message_set.create(
                    message="The import was successfull. %i users imported." %
                    imported_user.count())
                if form.cleaned_data['require_reactivation']:
                    for user in [
                            user for user in imported_user if user.is_active
                    ]:
                        user.is_active = False
                        user.set_new_activation_key()
                        user.save()
                        if form.cleaned_data['send_reactivation_email']:
                            # Send activation email
                            t = Template(form.cleaned_data['meassagetext'])
                            c = {
                                'email':
                                user.email,
                                'domain':
                                RequestSite(request).domain,
                                'site_name':
                                settings.SITE_NAME,
                                'uid':
                                int_to_base36(user.id),
                                'user':
                                user,
                                'protocol':
                                request.is_secure() and 'https' or 'http',
                                'activation_key':
                                user.activation_key,
                                'expiration_days':
                                get_settings().acount_activation_days,
                            }
                            send_mail(
                                _("Account activation on %s") %
                                settings.SITE_NAME, t.render(Context(c)), None,
                                [user.email])
                return HttpResponseRedirect(
                    urlresolvers.reverse('admin:accounts_user_changelist'))
            except:
                raise
                from django.forms.util import ErrorList
                msg = "An Error occured. The import file was propably malformed."
                form._errors["file"] = ErrorList([msg])
    else:
        form = ImportForm()
    return render_to_response('admin/accounts/user/import.html', {
        'form': form,
        'title': "Import User"
    }, RequestContext(request))
Example #31
0
def login(request,
          template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

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

    if request.method == "POST":
        form = authentication_form(data=request.POST)
        if form.is_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

            # Okay, security checks complete. Log the user in.
            user = form.get_user()
            logged_in.send(sender=None,
                           request=request,
                           user=user,
                           is_new_user=False)
            auth.login(request, user)
            save_queued_POST(request)
            messages.add_message(request, GA_TRACK_PAGEVIEW, '/login/success')

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

            return HttpResponseRedirect(redirect_to)

    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)

    return render_to_response(template_name, {
        'login_form': form,
        'register_form': RegistrationForm(),
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    },
                              context_instance=RequestContext(request))
Example #32
0
        Instrument.objects.create(Name='ng3', instrument_class='sans')
        Instrument.objects.create(Name='ANDR', instrument_class='andr')
        Instrument.objects.create(Name='andr2', instrument_class='andr2')
        Instrument.objects.create(Name='asterix', instrument_class='asterix')
        Instrument.objects.create(Name='NCNR PBR', instrument_class='refl')

if len(Facility.objects.all()) < 1:
        Facility.objects.create(Name='NCNR')
        Facility.objects.create(Name='HFIR')
        Facility.objects.create(Name='Chalk River')
        
# There is probably a better way to set the default domain and name.
if Site._meta.installed:
        mysite = Site.objects.get_current()
else:
        mysite = RequestSite(request)
if mysite.domain == '':
        mysite.domain = 'drneutron.org'
        mysite.save()
if mysite.name == '':
        mysite.name = 'drneutron.org'
        mysite.save()
        
#if len(Template.objects.all()) == 0:
#        temp = Template.objects.create(Title='testTemplate')
#        temp.metadata.add(User.objects.get(id=1))

#to add a new model (instrument, facility, or template) manually, you can run:    
        # python manage.py shell
        # then, as done above... 
        # from apps.tracks.models import *