Exemplo n.º 1
0
def edit_group(request, group_id=None):
    """Edit a Group.  This is used to create a group as well."""
    group = None
    if group_id is not None:
        group = Group.query.get(group_id)
        if group is None:
            raise NotFound()
    form = EditGroupForm(group)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/manage_groups')
        elif request.form.get('delete') and group:
            return redirect_to('admin/delete_group', group_id=group.id)
        elif form.validate(request.form):
            if group is None:
                group = form.make_group()
                msg = _(u'Group %s created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _(u'Group %s edited successfully.')
                icon = 'info'
            db.commit()
            html_group_detail = u'<a href="%s">%s</a>' % (
                escape(url_for(group)),
                escape(group.name))
            flash(msg % html_group_detail, icon)

            if request.form.get('save'):
                return form.redirect('admin/manage_groups')
            return redirect_to('admin/edit_group', group_id=group.id)

    return render_admin_response('admin/edit_group.html', 'users_groups.groups',
                                 form=form.as_widget())
Exemplo n.º 2
0
def configuration(request):
    """Advanced configuration editor.  This is useful for development or if a
    plugin doesn't ship an editor for the configuration values.  Because all
    the values are not further checked it could easily be that pyClanSphere is
    left in an unusable state if a variable is set to something bad.  Because
    of this the editor shows a warning and must be enabled by hand.
    """
    form = make_config_form()

    if request.method == 'POST':
        if request.form.get('enable_editor'):
            request.session['ace_on'] = True
        elif request.form.get('disable_editor'):
            request.session['ace_on'] = False
        elif form.validate(request.form):
            form.apply()
            flash(_(u'Configuration updated successfully.'), 'configure')
            return redirect_to('admin/configuration')
        else:
            flash(_(u'Could not save the configuration because the '
                    u'configuration is invalid.'), 'error')

    return render_admin_response('admin/configuration.html',
                                 'options.configuration',
                                 form=form.as_widget(), editor_enabled=
                                 request.session.get('ace_on', False))
Exemplo n.º 3
0
def remove_plugin(request, plugin):
    """Remove an inactive, instance installed plugin completely."""
    plugin = request.app.plugins.get(plugin)
    if plugin is None or \
       not plugin.instance_plugin or \
       plugin.active:
        raise NotFound()
    form = RemovePluginForm(plugin)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('confirm'):
            try:
                plugin.remove()
            except IOError:
                flash(_(u'Could not remove the plugin “%s” because an '
                        u'IO error occurred. Wrong permissions?') %
                      plugin.html_display_name)
            flash(_(u'The plugin “%s” was removed from the instance '
                    u'successfully.') % escape(plugin.display_name), 'remove')
        return form.redirect('admin/plugins')

    return render_admin_response('admin/remove_plugin.html', 'options.plugins',
        plugin=plugin,
        form=form.as_widget()
    )
Exemplo n.º 4
0
def edit_level(request, level_id=None):
    """Edit an existing level or create a new one."""

    level = None
    if level_id is not None:
        level = Level.query.get(level_id)
        if level is None:
            raise NotFound()
    form = EditLevelForm(level)

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/levels')
        elif request.form.get('delete') and level:
            return redirect_to('admin/levels/delete', level_id=level_id)
        elif form.validate(request.form):
            if level is None:
                level = form.make_level()
                msg = _('The level %s was created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _('The level %s was updated successfully.')
                icon = 'info'
            admin_flash(msg % (escape(level.name)), icon)

            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('admin/levels/edit', level_id=level.id)
            return redirect_to('admin/levels')
    return render_admin_response('admin/level_edit.html', 'levelsquad.levels',
                                 form=form.as_widget())
Exemplo n.º 5
0
def gameaccount_edit(request, account_id=None):
    """Edit an existing game account or create a new one."""

    gameaccount = None
    if account_id is not None:
        gameaccount = GameAccount.query.get(account_id)
        if gameaccount is None:
            raise NotFound()
    form = EditGameAccountForm(request.user, gameaccount)

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('account/gameaccounts')
        elif request.form.get('delete') and gameaccount:
            return redirect_to('account/gameaccounts/delete', account_id=account_id)
        elif form.validate(request.form):
            if gameaccount is None:
                gameaccount = form.make_gameaccount()
                msg = _('The game account %s was registered successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _('The game account %s was updated successfully.')
                icon = 'info'
            account_flash(msg % (escape(gameaccount.account)), icon)

            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('account/gameaccounts/edit', account_id=gameaccount.id)
            return redirect_to('account/gameaccounts')
    return render_account_response('account/gameaccount_edit.html', 'gameaccounts',
                                    form=form.as_widget())
Exemplo n.º 6
0
def edit_squad(request, squad_id=None):
    """Edit an existing squad or create a new one."""

    squad = None
    if squad_id is not None:
        squad = Squad.query.get(squad_id)
        if squad is None:
            raise NotFound()
    form = EditSquadForm(squad)

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/squads')
        elif request.form.get('delete') and squad:
            return redirect_to('admin/squads/delete', squad_id=squad.id)
        elif form.validate(request.form):
            if squad is None:
                squad = form.make_squad()
                msg = _('The squad %s was created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _('The squad %s was updated successfully.')
                icon = 'info'
            admin_flash(msg % (escape(squad.name)), icon)

            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('admin/squads/edit', squad_id=squad.id)
            return redirect_to('admin/squads')
    return render_admin_response('admin/squad_edit.html', 'gamesquad.squads',
                                 form=form.as_widget())
Exemplo n.º 7
0
def edit_game(request, game_id=None):
    """Edit an existing game or create a new one."""

    game = None
    if game_id is not None:
        game = Game.query.get(game_id)
        if game is None:
            raise NotFound()
    form = EditGameForm(game)

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/games')
        elif request.form.get('delete') and game:
            return redirect_to('admin/games/delete', game_id=game.id)
        elif form.validate(request.form):
            if game is None:
                game = form.make_game()
                msg = _('The game %s was created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _('The game %s was updated successfully.')
                icon = 'info'
            admin_flash(msg % (escape(game.name)), icon)

            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('admin/game_edit', game_id=game.id)
            return redirect_to('admin/games')
    return render_admin_response('admin/game_edit.html', 'gamesquad.games',
                                 form=form.as_widget())
Exemplo n.º 8
0
 def context_validate(self, data):
     if data["cache_system"] == "memcached":
         if not data["memcached_servers"]:
             raise ValidationError(_(u"You have to provide at least one " u"server to use memcached."))
     elif data["cache_system"] == "filesystem":
         if not data["filesystem_cache_path"]:
             raise ValidationError(_(u"You have to provide cache folder to " u"use filesystem cache."))
Exemplo n.º 9
0
def imaccount_edit(request, account_id=None):
    """Edit an existing game account or create a new one."""

    imaccount = None
    if account_id is not None:
        imaccount = IMAccount.query.get(account_id)
        if imaccount is None:
            raise NotFound()
        elif imaccount.user != request.user:
            raise Forbidden()
    form = EditIMAccountForm(request.user, imaccount)

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('account/imaccount_list')
        elif request.form.get('delete') and imaccount:
            return redirect_to('account/imaccount_delete', account_id=account_id)
        elif form.validate(request.form):
            if imaccount is None:
                imaccount = form.make_imaccount()
                msg = _('IM account %s was added successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _('IM account %s was updated successfully.')
                icon = 'info'
            flash(msg % (escape(imaccount.account)), icon)

            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('account/imaccount_edit', account_id=imaccount.id)
            return form.redirect('account/imaccount_list')
    return render_account_response('account/imaccount_edit.html', 'imaccounts',
                                    form=form.as_widget())
Exemplo n.º 10
0
 def validator(form, value):
     items = value.split()
     if len(items) > 1:
         raise ValidationError(_(u'You have to enter a valid net address.'))
     items = items[0].split(':')
     if len(items) not in (1, 2):
         raise ValidationError(_(u'You have to enter a valid net address.'))
     elif len(items) == 2 and not items[1].isdigit():
         raise ValidationError(_(u'The port has to be numeric'))
Exemplo n.º 11
0
 def validator(form, value):
     if '<' in value or '>' in value:
         raise ValidationError(_(u'Invalid character, < or > are not allowed.'))
     if value == '/':
         raise ValidationError(_(u'URL prefix must not be a sole slash.'))
     if value:
         if value[:1] != '/':
             raise ValidationError(_(u'URL prefix must start with a slash.'))
         if value[-1:] == '/':
             raise ValidationError(_(u'URL prefix must not end with a slash.'))
Exemplo n.º 12
0
def edit_user(request, user_id=None):
    """Edit a user.  This can also create a user.  If a new user is created
    the dialog is simplified, some unimportant details are left out.
    """
    user = None
    if user_id is not None:
        user = User.query.get(user_id)
        if user is None:
            raise NotFound()
    form = EditUserForm(user)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/manage_users')
        elif request.form.get('delete') and user:
            return redirect_to('admin/delete_user', user_id=user.id)
        elif form.validate(request.form):
            picfile = request.files.get('picfile')
            if user is None:
                user = form.make_user()
                if picfile and form['userpictype'] == 'Upload':
                    picture.place_file(picfile)
                msg = _(u'User %s created successfully.')
                icon = 'add'
            else:
                picture = UserPicture(request.user)
                if picfile:
                    form.save_changes()
                    if form['userpictype'] == 'Upload':
                        picture.place_file(picfile)
                else:
                    pictype = user.userpictype
                    if not form['userpictype']:
                        form.data['userpictype'] = pictype
                    if form['userpictype'] != pictype:
                       picture.remove()
                    form.save_changes()
                msg = _(u'User %s edited successfully.')
                icon = 'info'
            db.commit()
            html_user_detail = u'<a href="%s">%s</a>' % (
                escape(url_for(user)),
                escape(user.username)
            )
            flash(msg % html_user_detail, icon)
            if request.form.get('save'):
                return form.redirect('admin/manage_users')
            return redirect_to('admin/edit_user', user_id=user.id)

    return render_admin_response('admin/edit_user.html', 'users_groups.users',
                                 form=form.as_widget())
Exemplo n.º 13
0
def profile(request):
    form = EditProfileForm(request.user)
    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('account/index')
        elif 'delete' in request.form:
            return redirect_to('account/delete')
        elif form.validate(request.form):
            picfile = request.files.get('picfile')
            picture = UserPicture(request.user)
            if picfile:
                form.save_changes()
                picture.place_file(picfile)
            else:
                pictype = request.user.userpictype
                if not form['userpictype']:
                    form.data['userpictype'] = pictype
                if form['userpictype'] != pictype:
                   picture.remove()
                form.save_changes()
            db.commit()
            flash(_(u'Your profile was updated successfully.'), 'info')
            return form.redirect('account/index')
    return render_account_response('account/edit_profile.html', 'profile.profile',
                                   form=form.as_widget())
Exemplo n.º 14
0
 def validate_password(self, value):
     if "password_confirm" in self.data:
         password_confirm = self.data["password_confirm"]
     else:
         password_confirm = self.request.values.get("password_confirm", "")
     if (not value == password_confirm) or (value and not password_confirm) or (password_confirm and not value):
         raise ValidationError(_("Passwords do not match"))
Exemplo n.º 15
0
 def validator(form, value):
     if '<' in value or '>' in value or '\\' in value:
         raise ValidationError(_(u'Invalid character, <, > or \\ are not '
         'allowed.'))
     if value:
         if value.startswith('/'):
             raise ValidationError(_(u'URL format cannot start with a slash.'))
         if value.find('//') >= 0:
             raise ValidationError(_(u'URL cannot contain //.'))
         if value.find('/../') >= 0 or value.startswith('../'):
             raise ValidationError(_(u'URL cannot contain a reference to'
             'parent path.'))
         for match in _placeholder_re.finditer(value):
             if match.group(1) not in _slug_parts:
                 raise ValidationError(_(u'Unknown format code %s.') %
                                       match.group())
Exemplo n.º 16
0
def cache(request):
    """Configure the cache."""
    form = CacheOptionsForm()

    if request.method == 'POST':
        if 'clear_cache' in request.form:
            request.app.cache.clear()
            flash(_(u'The cache was cleared successfully.'), 'configure')
            return redirect_to('admin/cache')
        elif form.validate(request.form):
            form.apply()
            flash(_(u'Cache settings were changed successfully.'), 'configure')
            return redirect_to('admin/cache')

    return render_admin_response('admin/cache.html', 'options.cache',
                                 form=form.as_widget())
Exemplo n.º 17
0
def log(request, page):
    page = request.app.log.view().get_page(page)
    form = LogOptionsForm()
    if request.method == 'POST' and form.validate(request.form):
        form.apply()
        flash(_('Log changes saved.'), 'configure')
        return redirect_to('admin/log', page=page.number)
    return render_admin_response('admin/log.html', 'system.log',
                                 page=page, form=form.as_widget())
Exemplo n.º 18
0
def flash(msg, type='info'):
    """Add a message to the message flash buffer.

    The default message type is "info", other possible values are
    "add", "remove", "error", "ok" and "configure". The message type affects
    the icon and visual appearance.

    The flashes messages appear only in the admin interface!
    """
    assert type in \
        ('info', 'add', 'remove', 'error', 'ok', 'configure', 'warning')
    if type == 'error':
        msg = (u'<strong>%s:</strong> ' % _('Error')) + msg
    if type == 'warning':
        msg = (u'<strong>%s:</strong> ' % _('Warning')) + msg

    local.request.session.setdefault('admin/flashed_messages', []).\
            append((type, Markup(msg)))
Exemplo n.º 19
0
 def __init__(self, message_or_exception):
     if isinstance(message_or_exception, basestring):
         message = message_or_exception
         error = None
     else:
         message = _(u'Could not save configuration file: %s') % \
                   str(message_or_exception).decode('utf-8', 'ignore')
         error = message_or_exception
     InternalError.__init__(self, message)
     self.original_exception = error
Exemplo n.º 20
0
def plugins(request):
    """Load and unload plugins and reload pyClanSphere if required."""
    form = PluginForm()

    if request.method == 'POST' and form.validate(request.form):
        form.apply()
        flash(_('Plugin configuration changed'), 'configure')

        new_plugin = request.files.get('new_plugin')
        if new_plugin:
            try:
                plugin = install_package(request.app, new_plugin)
            except InstallationError, e:
                flash(e.message, 'error')
            else:
                flash(_(u'Plugin “%s” added successfully. You can now '
                        u'enable it in the plugin list.') %
                      plugin.html_display_name, 'add')

        return redirect_to('admin/plugins')
Exemplo n.º 21
0
def list_documented_plugins(app):
    """Return a list of all documented plugins."""
    plugins = []
    for plugin in app.plugins.itervalues():
        if plugin.is_documented:
            plugins.append('<li><a href="%s">%s</a></li>' % (
                url_for('admin/help', page='plugins/%s/' % plugin.name),
                escape(plugin.display_name)
            ))
    if not plugins:
        return u'<ul><li>%s</li></ul>' % _('no documented plugins installed.')
    return '<ul>%s</ul>' % '\n'.join(plugins)
Exemplo n.º 22
0
def recaptcha(request):
    """Configure reCAPTCHA form protection."""
    form = RecaptchaOptionsForm()

    if request.method == 'POST':
        if form.validate(request.form):
            form.apply()
            flash(_(u'reCAPTCHA settings were changed successfully.'), 'configure')
            return redirect_to('admin/recaptcha')

    return render_admin_response('admin/recaptcha.html', 'options.recaptcha',
                                 form=form.as_widget())
Exemplo n.º 23
0
 def __init__(self, user, initial=None):
     if user is not None:
         initial = forms.fill_dict(
             initial,
             username=user.username,
             real_name=user.real_name,
             display_name=user._display_name,
             gender_male=user.gender_male,
             birthday=user.birthday,
             height=user.height,
             address=user.address,
             zip=user.zip,
             city=user.city,
             country=user.country,
             email=user.email,
             www=user.www,
             notes=user.notes,
             userpictype=user.userpictype,
         )
     _UserBoundForm.__init__(self, user, initial)
     self.user = user
     self.display_name.choices = [
         (u"$username", user and user.username or _("Username")),
         (u"$real_name", user and user.real_name or _("Realname")),
     ]
     self.gender_male.choices = [(1, _("Male")), (0, _("Female"))]
     self.country.choices = sorted(get_application().locale.territories.iteritems(), key=itemgetter(1))
     self.country.choices.insert(0, ("", ""))
     self.userpictype.choices = [(u"", _("No change")), (u"None", _("No Picture")), (u"Gravatar", _("Gravatar.com"))]
Exemplo n.º 24
0
def edit_squadmember(request, squad_id=None, user_id=None):
    """Edit Squadmemberships"""

    if squad_id is None:
        raise NotFound()
    squad = Squad.query.get(squad_id)
    if squad is None:
        raise NotFound()

    squadmember = None
    if user_id is not None:
        squadmember = SquadMember.query.get((user_id,squad_id))
        if squadmember is None:
            raise NotFound()
    form = EditSquadMemberForm(squad, squadmember)

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/squadmembers', squad_id=squad_id)
        elif request.form.get('delete') and user_id is not None:
            return redirect_to('admin/squadmembers/delete', squad_id=squad_id, user_id=user_id)
        elif form.validate(request.form):
            if squadmember is None:
                squadmember = form.make_squadmember()
                msg = _('The squadmember %s was created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _('The squadmember %s was updated successfully.')
                icon = 'info'

            admin_flash(msg % (escape(squadmember.user.display_name)),icon)
            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('admin/squadmembers/edit', squad_id=squad_id,
                                   user_id=squadmember.user.id)
            return redirect_to('admin/squadmembers', squad_id=squad_id)
    return render_admin_response('admin/squad_editmember.html', 'gamesquad.squads',
                                 form=form.as_widget(), squad=squad, squadmember=squadmember)
Exemplo n.º 25
0
def urls(request):
    """A config page for URL depending settings."""
    form = URLOptionsForm()

    if request.method == 'POST' and form.validate(request.form):
        form.apply()
        db.commit()
        flash(_(u'URL configuration changed.'), 'configure')
        # because the next request could reload the application and move
        # the admin interface we construct the URL to this page by hand.
        return redirect(form['admin_url_prefix'][1:] + '/options/urls')

    return render_admin_response('admin/url_options.html', 'options.urls',
                                 form=form.as_widget())
Exemplo n.º 26
0
def make_setup_error(exc_info=None):
    """Create a new SetupError for the last exception and log it."""
    if exc_info is None:
        exc_info = sys.exc_info()

    # log the exception
    log.exception(_(u'Plugin setup error'), 'pluginsystem', exc_info)
    exc_type, exc_value, tb = exc_info

    # if the exception is already a SetupError we only
    # have to return it unchanged.
    if isinstance(exc_value, SetupError):
        return exc_value

    # otherwise create an error message for it and return a new
    # exception.
    error, (filename, line) = summarize_exception(exc_info)
    return SetupError(_(u'Exception happend on setup: '
                        u'%(error)s (%(file)s, line %(line)d)') % {
        'error':    escape(error),
        'file':     filename,
        'line':     line
    })
Exemplo n.º 27
0
def edit_news(request, news_id=None):
    """Edit an existing entry or create a new one."""

    newsitem = None
    if news_id is not None:
        newsitem = News.query.get(news_id)
        if newsitem is None:
            raise NotFound()
    form = NewsForm(newsitem)

    if newsitem is None:
        assert_privilege(privileges.NEWS_CREATE)
    else:
        if not newsitem.can_edit(request.user):
            raise Forbidden()

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/news')
        elif 'delete' in request.form:
            return redirect_to('admin/news/delete', news_id=news_id)
        elif form.validate(request.form):
            if newsitem is None:
                newsitem = form.make_news(request.user)
                msg = _('The entry %s was created successfully.')
            else:
                form.save_changes()
                msg = _('The entry %s was updated successfully.')

            admin_flash(msg % (escape(newsitem.title)))

            db.commit()
            if 'save_and_continue' in request.form:
                return redirect_to('admin/news_edit', news_id=newsitem.id)
            return redirect_to('admin/news')
    return render_admin_response('admin/news_edit.html', 'news.edit',
                                 form=form.as_widget())
Exemplo n.º 28
0
def lost_password(request):
    """Help users with forgotten passwords."""
    form = PasswordRequestForm()

    if request.method == 'POST' and form.validate(request.form):
        reset_request = form.create_request()
        db.commit()
        text = render_template('notifications/lost_password.txt',
                               req_id=reset_request.req_id,
                               user=reset_request.user,
                               siteurl=get_application().cfg['site_url'].rstrip('/'))
        send_email(_('Your lost password request'), text, reset_request.user.email)
        return render_response('account/lost_password_sent.html')

    return render_response('account/lost_password.html', form=form.as_widget())
Exemplo n.º 29
0
def delete_user(request, user_id):
    """Like all other delete screens just that it deletes a user."""
    user = User.query.get(user_id)
    if user is None:
        raise NotFound()
    form = DeleteUserForm(user)
    if user == request.user:
        flash(_(u'You cannot delete yourself.'), 'error')
        return form.redirect('admin/manage_users')

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/edit_user', user_id=user.id)
        elif 'confirm' in request.form and form.validate(request.form):
            form.add_invalid_redirect_target('admin/edit_user', user_id=user.id)
            msg = _(u'User %s removed successfully.') % escape(user.display_name)
            icon = 'remove'
            form.delete_user()
            db.commit()
            flash(msg, icon)
            return form.redirect('admin/manage_users')

    return render_admin_response('admin/delete_user.html', 'users_groups.users',
                                 form=form.as_widget())
Exemplo n.º 30
0
def change_password(request):
    """Allow the current user to change his password."""
    form = ChangePasswordForm(request.user)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('account/index')
        if form.validate(request.form):
            form.set_password()
            db.commit()
            flash(_(u'Password changed successfully.'), 'configure')
            return form.redirect('account/index')

    return render_account_response('account/change_password.html','profile.password',
        form=form.as_widget()
    )