示例#1
0
文件: views.py 项目: CDE-UNIBE/lokp
    def _handle_parameters(self):

        response = self.request.response

        # Make sure the _LOCATION_ cookie is correctly set: The old version GUI
        # version used to store the map center and the zoom level which is not
        # understood by new GUI (which stores the map extent as 4 coordinates)
        if '_LOCATION_' in self.request.cookies:
            c = urllib.unquote(self.request.cookies['_LOCATION_'])
            if len(c.split('|')) == 3:
                response.delete_cookie('_LOCATION_')

        # Check if language (_LOCALE_) is set
        if self.request is not None:
            if '_LOCALE_' in self.request.params:
                response.set_cookie('_LOCALE_', self.request.params.get(
                    '_LOCALE_'), timedelta(days=90))
            elif '_LOCALE_' in self.request.cookies:
                pass

        # Check if profile (_PROFILE_) is set
        if self.request is not None:
            if '_PROFILE_' in self.request.params:
                # Set the profile cookie
                profile_code = self.request.params.get('_PROFILE_')
                response.set_cookie(
                    '_PROFILE_', profile_code, timedelta(days=90))

                # Update _LOCATION_ from cookies to profile geometry bbox
                # retrieved from database
                profile_db = DBSession.query(Profile).\
                    filter(Profile.code == profile_code).\
                    first()

                if profile_db is not None:
                    # Calculate and transform bounding box
                    bbox = DBSession.scalar(geofunctions.envelope(
                        geofunctions.transform(
                            profile_db.geometry, '900913')).wkt)

                    geojson = utils.from_wkt(bbox)

                    coords = geojson['coordinates'][0]
                    p1 = coords[0]
                    p2 = coords[2]

                    l = '%s,%s' % (','.join([str(x) for x in p1]),
                        ','.join([str(x) for x in p2]))

                    response.set_cookie(
                        '_LOCATION_', urllib.quote(l), timedelta(days=90))

            elif '_PROFILE_' in self.request.cookies:
                # Profile already set, leave it
                pass
            else:
                # If no profile is set, set the default profile
                response.set_cookie('_PROFILE_', get_default_profile(
                    self.request), timedelta(days=90))
示例#2
0
文件: views.py 项目: CDE-UNIBE/lokp
def get_current_profile(request):
    """
    Return the currently selected :term:`Profile`.

    First, parameters in the request are considered. If no parameter is
    set, the profile cookie is used. As a fallback, the default profile
    is returned.

    .. seealso::
           :class:`lmkp.views.config.get_default_profile`

    Args:
        ``request`` (pyramid.request): A :term:`Pyramid` Request object
        with optional parameter ``_PROFILE_`` or a cookie ``_PROFILE_``
        set.

    Returns:
        ``str``. The name of the :term:`Profile` or the default profile.
    """
    return request.params.get(
        '_PROFILE_', request.cookies.get(
            '_PROFILE_', get_default_profile(request)))
示例#3
0
文件: user.py 项目: CDE-UNIBE/lokp
    def activate(self):
        """
        """

        activation_uuid = self.request.params.get("uuid")
        username = self.request.params.get("username")

        # Get the user
        user = Session.query(User).filter(and_(
            User.activation_uuid == activation_uuid,
            User.username == username, User.is_active == False)).first()
        # Raise a BadRequest if no user is found
        if user is None:
            raise HTTPBadRequest()

        # A timedelta of 48 hours equals 2 days
        delta = timedelta(hours=48)

        # Create a timezone info
        tz = psycopg2.tz.FixedOffsetTimezone(offset=0, name="UTC")

        # Check if the registration timestamp is not older than 48 hours
        if (datetime.now(tz) - delta) > user.registration_timestamp:
            raise HTTPBadRequest("Activation link has been expired.")

        # Set the user active and set the activation uuid to NULL
        user.is_active = True
        user.activation_uuid = None

        approval_dict = {
            "username": user.username,
            "firstname": user.firstname,
            "lastname": user.lastname,
            "email": user.email,
            "profiles": ",".join([p.code for p in user.profiles]),
            "approval_link": "http://%s/users/approve?user=%s&name=%s" % (
                self.request.environ['HTTP_HOST'], user.uuid, user.username)
        }

        # Send an email to all moderators of the profile in which the user
        # registered.
        email_text = render(
            get_customized_template_path(
                self.request, 'emails/account_approval_request.mak'),
            approval_dict, request=self.request)

        # Determine profile. Each user should only have one profile when
        # registering!
        profiles = [p.code for p in user.profiles]
        if len(profiles) == 0:
            profile = get_default_profile(self.request)
        else:
            profile = profiles[0]

        # Find moderators of this profile
        moderators = Session.query(User).\
            join(users_groups).\
            join(Group).\
            join(users_profiles).\
            join(Profile).\
            filter(Group.name == 'moderators').\
            filter(Profile.code == profile)

        # A list with email addresses the email is sent to
        email_addresses = []
        for m in moderators.all():
            email_addresses.append(m.email)

        if len(email_addresses) == 0:
            # If no moderator, try to contact the administrators
            for admin_user in Session.query(User).join(users_groups).join(
                    Group).filter(func.lower(Group.name) == 'administrators'):
                email_addresses.append(admin_user.email)
            log.debug(
                "No moderator found for profile %s. Approval emails will be "
                "sent to administrators: %s" % (profile, email_addresses))

        else:
            log.debug(
                "Approval emails will be sent to moderators of %s profile: %s"
                % (profile, email_addresses))

        # Send the email
        self._send_email(
            email_addresses,
            "User %s requests approval" % user.username,
            email_text)

        return render_to_response(
            get_customized_template_path(
                self.request, 'users/activation_successful.mak'),
            {
                'username': user.username
            }, self.request)