Exemple #1
0
        def succeed():
            """
            """

            # Request all submitted values
            profile_field = self.request.POST.get("profile")
            username_field = self.request.POST.get("username")
            firstname_field = self.request.POST.get("firstname")
            lastname_field = self.request.POST.get("lastname")
            password_field = self.request.POST.get("password")
            email_field = self.request.POST.get("email")

            # Get the selected profile
            selected_profile = DBSession.query(Profile).filter(
                Profile.code == profile_field).first()

            # Get the initial user group
            user_group = DBSession.query(Group).filter(
                Group.name == "editors").first()

            # Create an activation uuid
            activation_uuid = str(uuid.uuid4())

            # Create a new user
            new_user = User(username_field,
                            password_field,
                            email_field,
                            firstname=firstname_field,
                            lastname=lastname_field,
                            activation_uuid=activation_uuid,
                            registration_timestamp=datetime.now())

            # Set the user profile
            new_user.profiles = [selected_profile]
            new_user.groups = [user_group]
            # Commit the new user
            DBSession.add(new_user)

            activation_dict = {
                "firstname":
                new_user.firstname,
                "lastname":
                new_user.lastname,
                "activation_link":
                "http://%s/users/activate?uuid=%s&username="******"%s" % (self.request.environ['HTTP_HOST'], activation_uuid,
                        new_user.username)
            }
            email_text = render(
                get_customized_template_path(self.request,
                                             'emails/account_activation.mak'),
                activation_dict, self.request)

            self._send_email([email_field], _(u"Activate your Account"),
                             email_text)

            return render_to_response(
                get_customized_template_path(self.request,
                                             'users/registration_success.mak'),
                {}, self.request)
Exemple #2
0
    def _translate_category(original, translation, TableItem, locale):
        """
        Helper function to insert or update a single translation for a
        category.
        """

        # Query the database to find the english entry of the category
        english_query = DBSession.query(TableItem). \
            filter(TableItem.name == original). \
            filter(TableItem.fk_language == 1)
        eng = english_query.all()

        if len(eng) == 0:
            return {
                'success': False,
                'msg': 'No english value found for "%s", translation "%s" not '
                       'inserted.' % (original, translation)
            }

        for e in eng:
            # Check if translation already exists
            translation_query = DBSession.query(TableItem). \
                filter(TableItem.original == e). \
                filter(TableItem.language == locale)
            translation_entry = translation_query.first()

            if translation_entry is None:
                # Insert a new translation
                new_translation = TableItem(translation)
                new_translation.language = locale
                new_translation.original = e
                DBSession.add(new_translation)
            else:
                # Update an existing translation
                translation_entry.name = translation

        return {
            'success': True,
            'msg': 'Translation "%s" inserted for value "%s".' % (
                translation, original)
        }
Exemple #3
0
 def _create_id_unique(obj):
     q = DBSession.query(obj.__mapper__).get(obj.id)
     if q is None:
         DBSession.add(obj)
         return obj, True
     return q, False
Exemple #4
0
def add_initial_values(engine, settings):
    def _create_id_unique(obj):
        q = DBSession.query(obj.__mapper__).get(obj.id)
        if q is None:
            DBSession.add(obj)
            return obj, True
        return q, False

    with transaction.manager:

        # Languages
        _create_id_unique(
            Language(id=1,
                     english_name='English',
                     local_name='English',
                     locale='en'))

        # Status
        _create_id_unique(
            Status(id=1,
                   name='pending',
                   description='Review pending. Not published yet.'))
        _create_id_unique(
            Status(id=2,
                   name='active',
                   description='Reviewed and accepted. Currently published.'))
        _create_id_unique(
            Status(id=3,
                   name='inactive',
                   description='Inactive. Previously active.'))
        _create_id_unique(
            Status(id=4,
                   name='deleted',
                   description='Deleted. Not published anymore.'))
        _create_id_unique(
            Status(id=5,
                   name='rejected',
                   description='Reviewed and rejected. Never published.'))
        _create_id_unique(
            Status(id=6,
                   name='edited',
                   description='Edited. Previously pending.'))

        # Permissions
        permission1, __ = _create_id_unique(
            Permission(
                id=1,
                name='administer',
                description='Can add key/values and do batch translations.'))
        permission2, __ = _create_id_unique(
            Permission(
                id=2,
                name='moderate',
                description='Can make review decisions on reported information.'
            ))
        permission3, __ = _create_id_unique(
            Permission(id=3,
                       name='edit',
                       description='Can report information.'))
        permission4, __ = _create_id_unique(
            Permission(id=4,
                       name='view',
                       description='Can see information. (basic permission - '
                       'granted to everyone)'))
        permission5, __ = _create_id_unique(
            Permission(id=5,
                       name='translate',
                       description='Can add and modify translations.'))

        # Groups (with Permissions)
        group1, created = _create_id_unique(Group(id=1, name='administrators'))
        if created is True:
            group1.permissions.append(permission1)
            group1.permissions.append(permission3)
            group1.permissions.append(permission4)
        group2, created = _create_id_unique(Group(id=2, name='moderators'))
        if created is True:
            group2.permissions.append(permission2)
            group2.permissions.append(permission3)
            group2.permissions.append(permission4)
        group3, created = _create_id_unique(Group(id=3, name='editors'))
        if created is True:
            group3.permissions.append(permission3)
            group3.permissions.append(permission4)
        group4, created = _create_id_unique(Group(id=4, name='translators'))
        if created is True:
            group4.permissions.append(permission5)

        # Users (Admin user)
        admin_password = settings['lokp.admin_password']
        admin_email = settings['lokp.admin_email']
        try:
            DBSession.query(User).filter(User.username == 'admin').one()
        except (NoResultFound, MultipleResultsFound) as __:
            user = User(username='******',
                        password=admin_password,
                        email=admin_email,
                        is_active=True,
                        is_approved=True,
                        registration_timestamp=datetime.datetime.now())
            user.groups = [group1, group2, group3, group4]
            DBSession.add(user)
Exemple #5
0
def handle_upload(request, filedict):
    """
    Handle the upload of a new file.
    http://code.google.com/p/file-uploader/
    """
    TEMP_FOLDER_NAME = 'temp'

    ret = {'success': False, 'msg': ''}

    filename = None
    filetype = None
    file = None

    try:
        filename = filedict['filename']
        file = filedict['fp']
        filetype = filedict['mimetype']
    except:
        ret['msg'] = _('Not all necessary values were provided.')
        valid = False

    if filename is None or file is None or filetype is None:
        ret['msg'] = 'Uploaded file not found.'

    # Check upload directory
    upload_path = upload_directory_path(request)
    if upload_path is None or not os.path.exists(upload_path):
        ret['msg'] = _('Upload directory not specified or not found.')
        return ret

    # Check filetype
    fileextension = get_valid_file_extension(request, filetype)
    if fileextension is None:
        ret['msg'] = _('File type is not valid.')
        return ret

    # Check filesize
    size = get_file_size(file)
    if size > upload_max_file_size(request):
        ret['msg'] = _('File is too big.')
        return ret

    # Do the actual file processing

    # Strip leading path from file name to avoid directory traversal
    # attacks
    old_filename = os.path.basename(filename)

    # Internet Explorer will attempt to provide full path for filename
    # fix
    old_filename = old_filename.split('\\')[-1]

    # Remove the extension and check the filename
    cleaned_filename = '.'.join(old_filename.split('.')[:-1])
    cleaned_filename = clean_filename(cleaned_filename)

    # Make sure the filename is not too long
    if len(cleaned_filename) > 500:
        cleaned_filename = cleaned_filename[:500]

    # Append the predefined file extension
    cleaned_filename = '%s%s' % (cleaned_filename, fileextension)

    # Use a randomly generated UUID as filename
    file_identifier = str(uuid.uuid4())
    new_filename = '%s%s' % (file_identifier, fileextension)

    # Check if the directories already exist. If not, create them.
    if not os.path.exists(os.path.join(upload_path, TEMP_FOLDER_NAME)):
        os.makedirs(os.path.join(upload_path, TEMP_FOLDER_NAME))

    new_filepath = os.path.join(upload_path, TEMP_FOLDER_NAME, new_filename)

    temp_file_path = new_filepath + '~'
    file.seek(0)
    with open(temp_file_path, 'wb') as output_file:
        shutil.copyfileobj(file, output_file)
    os.rename(temp_file_path, new_filepath)

    # Open the file again to get the hash
    hash = get_file_hash(new_filepath)

    # Database values
    db_file = File(identifier=file_identifier,
                   name=cleaned_filename,
                   mime=filetype,
                   size=size,
                   hash=hash)
    DBSession.add(db_file)

    log.debug('The uploaded file (%s) was saved as %s at %s' %
              (cleaned_filename, new_filename, new_filepath))

    ret['filename'] = cleaned_filename
    ret['fileidentifier'] = str(file_identifier)

    ret['msg'] = _('File was successfully uploaded')
    ret['success'] = True

    localizer = get_localizer(request)
    ret['msg'] = localizer.translate(ret['msg'])

    return ret
Exemple #6
0
    def _translate_keyvalue(
            original, translation, TableItem, isKey, locale,
            helptext_translation):
        """
        Helper function to insert or update a single translation for a key or a
        value
        """

        # Query the database to find english entry of key or value
        if isKey:
            english_query = DBSession.query(TableItem). \
                filter(TableItem.key == original). \
                filter(TableItem.fk_language == 1)
        else:
            english_query = DBSession.query(TableItem). \
                filter(TableItem.value == original). \
                filter(TableItem.fk_language == 1)
        eng = english_query.all()

        if eng is None or len(eng) == 0:
            return {
                'success': False,
                'msg': 'No english value found for "%s", translation "%s" not '
                       'inserted.' % (original, translation)}

        for e in eng:
            # Check if translation already exists for value
            if isKey:
                originalEntry = e.original
                translation_query = DBSession.query(TableItem). \
                    filter(TableItem.original == originalEntry). \
                    filter(TableItem.language == locale)
            else:
                originalEntry = e
                translation_query = DBSession.query(TableItem). \
                    filter(TableItem.original == originalEntry). \
                    filter(TableItem.language == locale)
            translation_entry = translation_query.first()

            if translation_entry is None:
                # No translation found, insert a new translation
                if isKey:
                    new_translation = TableItem(translation, e.type)
                else:
                    new_translation = TableItem(translation)
                new_translation.language = locale
                new_translation.original = originalEntry
                if helptext_translation != '':
                    new_translation.helptext = helptext_translation
                DBSession.add(new_translation)
            else:
                # There is already a translation, update it
                if isKey:
                    translation_entry.key = translation
                else:
                    translation_entry.value = translation
                if helptext_translation != '':
                    translation_entry.helptext = helptext_translation

        return {
            'success': True,
            'msg': 'Translation "%s" inserted for value "%s".' % (
                translation, original)}
Exemple #7
0
def edit_translation(request):

    _ = request.translate

    success = False
    msg = _('Translation not successful')
    if 'original' and 'translation' and 'language' and 'keyvalue' \
            and 'item_type' in request.params:
        # find language
        language = DBSession.query(Language).filter(
            Language.locale == request.params['language']).all()
        if language and len(language) == 1:
            if request.params['keyvalue'] == 'key':
                # Activity or Stakeholder?
                Key = None
                if request.params['item_type'] == 'activity':
                    Key = A_Key
                elif request.params['item_type'] == 'stakeholder':
                    Key = SH_Key
                # find original (fk_a_key empty)
                original = DBSession.query(Key).filter(
                    Key.key == request.params['original']).filter(
                    Key.original == None).all()
                if original and len(original) == 1:
                    # check if a translation of this key is already there
                    oldTranslation = DBSession.query(Key).filter(
                        Key.original == original[0]).filter(
                        Key.language == language[0]).all()
                    if oldTranslation and len(oldTranslation) == 1:
                        # translation found, just update it.
                        oldTranslation[0].key = request.params['translation']
                        success = True
                        msg = _('Updated translation')
                    else:
                        # no translation available yet, add it to DB
                        translation = Key(request.params['translation'])
                        translation.original = original[0]
                        translation.language = language[0]
                        DBSession.add(translation)
                        success = True
                        msg = _('Added translation')
                else:
                    msg = 'Original key not found'  # should never happen
            if request.params['keyvalue'] == 'value':
                # Activity or Stakeholder?
                Value = None
                if request.params['item_type'] == 'activity':
                    Value = A_Value
                elif request.params['item_type'] == 'stakeholder':
                    Value = SH_Value
                # find original (fk_a_value empty)
                original = DBSession.query(Value).filter(
                    Value.value == request.params['original']).filter(
                    Value.original == None).all()
                if original and len(original) == 1:
                    # check if a translation of this value is already there
                    oldTranslation = DBSession.query(Value).filter(
                        Value.original == original[0]).filter(
                        Value.language == language[0]).all()
                    if oldTranslation and len(oldTranslation) == 1:
                        # translation found, just update it.
                        oldTranslation[0].value = request.params['translation']
                        success = True
                        msg = _('Updated translation')
                    else:
                        # no translation available yet, add it to DB
                        translation = Value(request.params['translation'])
                        translation.original = original[0]
                        translation.language = language[0]
                        DBSession.add(translation)
                        success = True
                        msg = _('Added translation')
                else:
                    msg = 'Original value not found'  # should never happen
        else:
            msg = 'Language not unique or not found in DB'

    return {
        'success': success,
        'msg': msg
    }