Ejemplo n.º 1
0
    def login(self, request, user_obj, **kw):
        username = kw.get('username')
        password = kw.get('password')

        # simply continue if something else already logged in successfully
        if user_obj and user_obj.valid:
            return ContinueLogin(user_obj)

        if not username and not password:
            return ContinueLogin(user_obj)

        _ = request.getText

        logging.debug("%s: performing login action" % self.name)

        if username and not password:
            return ContinueLogin(user_obj, _('Missing password. Please enter user name and password.'))
        if not username and password:
            return ContinueLogin(user_obj, _('Missing user name. Please enter user name and password.'))

        check_surge_protect(request, action='auth-ip')
        check_surge_protect(request, action='auth-name', username=username)

        u = user.User(request, name=username, password=password, auth_method=self.name)
        if u.valid:
            logging.debug("%s: successfully authenticated user %r (valid)" % (self.name, u.name))
            log_attempt("auth/login (moin)", True, request, username)
            return ContinueLogin(u)
        else:
            logging.debug("%s: could not authenticate user %r (not valid)" % (self.name, username))
            log_attempt("auth/login (moin)", False, request, username)
            return ContinueLogin(user_obj, _("Invalid username or password."))
Ejemplo n.º 2
0
 def is_allowed(self):
     # this is not strictly necessary because the underlying storage code checks
     # as well
     _ = self._
     may = self.request.user.may
     allowed = may.write(self.pagename) and may.revert(self.pagename)
     if not allowed:
         log_attempt('revert/immutable or no permissions', False, self.request, pagename=self.pagename)
     return allowed, _('You are not allowed to revert this page!')
    def checkPermissions(self):
        """ Check write permission in form, return error msg

        @rtype: unicode
        @return: error message
        """
        _ = self.request.getText
        page = Page(self.request, self.pagename)
        if not (page.isWritable() and self.request.user.may.read(self.pagename)):
            # Same error as the edit page for localization reasons
            log_attempt('newpage/immutable or no permissions', False, self.request, pagename=self.pagename)
            return _('You are not allowed to edit this page.')
        return ''
Ejemplo n.º 4
0
    def checkPermissions(self):
        """ Check write permission in form, return error msg

        @rtype: unicode
        @return: error message
        """
        _ = self.request.getText
        page = Page(self.request, self.pagename)
        if not (page.isWritable()
                and self.request.user.may.read(self.pagename)):
            # Same error as the edit page for localization reasons
            log_attempt('newpage/immutable or no permissions',
                        False,
                        self.request,
                        pagename=self.pagename)
            return _('You are not allowed to edit this page.')
        return ''
Ejemplo n.º 5
0
def setup_setuid(request, userobj):
    """ Check for setuid conditions in the session and setup an user
    object accordingly. Returns a tuple of the new user objects.

    @param request: a moin request object
    @param userobj: a moin user object
    @rtype: boolean
    @return: (new_user, user) or (user, None)
    """
    old_user = None
    if 'setuid' in request.session and userobj and userobj.isSuperUser():
        old_user = userobj
        uid = request.session['setuid']
        userobj = user.User(request, uid, auth_method='setuid')
        userobj.valid = True
        log_attempt("auth/login (setuid from %r)" % old_user.name, True, request, userobj.name)
    logging.debug("setup_suid returns %r, %r" % (userobj, old_user))
    return (userobj, old_user)
Ejemplo n.º 6
0
    def request(self, request, user_obj, **kw):
        u = None
        _ = request.getText
        # always revalidate auth
        if user_obj and user_obj.auth_method == self.name:
            user_obj = None
        # something else authenticated before us
        if user_obj:
            logging.debug("already authenticated, doing nothing")
            return user_obj, True

        if self.user_name is not None:
            auth_username = self.user_name
        elif self.env_var is None:
            auth_username = request.remote_user
        else:
            auth_username = request.environ.get(self.env_var)

        logging.debug("auth_username = %r" % auth_username)
        if auth_username:
            auth_username = self.decode_username(auth_username)
            auth_username = self.transform_username(auth_username)
            logging.debug("auth_username (after decode/transform) = %r" %
                          auth_username)
            u = user.User(request,
                          auth_username=auth_username,
                          auth_method=self.name,
                          auth_attribs=('name', 'password'))

        logging.debug("u: %r" % u)
        if u and self.autocreate:
            logging.debug("autocreating user")
            u.create_or_update()
        if u and u.valid:
            logging.debug("returning valid user %r" % u)
            log_attempt("auth/request (given)", True, request, auth_username)
            return u, True  # True to get other methods called, too
        else:
            logging.debug("returning %r" % user_obj)
            if u and not u.valid:
                log_attempt("auth/request (given)", False, request,
                            auth_username)
            return user_obj, True
    def request(self, request, user_obj, **kw):
        u = None
        _ = request.getText
        # always revalidate auth
        if user_obj and user_obj.auth_method == self.name:
            user_obj = None
        # something else authenticated before us
        if user_obj:
            logging.debug("already authenticated, doing nothing")
            return user_obj, True

        if self.user_name is not None:
            auth_username = self.user_name
        elif self.env_var is None:
            auth_username = request.remote_user
        else:
            auth_username = request.environ.get(self.env_var)

        logging.debug("auth_username = %r" % auth_username)
        if auth_username:
            auth_username = self.decode_username(auth_username)
            auth_username = self.transform_username(auth_username)
            logging.debug("auth_username (after decode/transform) = %r" % auth_username)
            u = user.User(request, auth_username=auth_username,
                          auth_method=self.name, auth_attribs=('name', 'password'))

        logging.debug("u: %r" % u)
        if u and self.autocreate:
            logging.debug("autocreating user")
            u.create_or_update()
        if u and u.valid:
            logging.debug("returning valid user %r" % u)
            log_attempt("auth/request (given)", True, request, auth_username)
            return u, True # True to get other methods called, too
        else:
            logging.debug("returning %r" % user_obj)
            if u and not u.valid:
                log_attempt("auth/request (given)", False, request, auth_username)
            return user_obj, True
Ejemplo n.º 8
0
def handle_action(context, pagename, action_name='show'):
    """ Actual dispatcher function for non-XMLRPC actions.

    Also sets up the Page object for this request, normalizes and
    redirects to canonical pagenames and checks for non-allowed
    actions.
    """
    _ = context.getText
    cfg = context.cfg

    # pagename could be empty after normalization e.g. '///' -> ''
    # Use localized FrontPage if pagename is empty
    if not pagename:
        context.page = wikiutil.getFrontPage(context)
    else:
        context.page = Page(context, pagename)
        if '_' in pagename and not context.page.exists():
            pagename = pagename.replace('_', ' ')
            page = Page(context, pagename)
            if page.exists():
                url = page.url(context)
                return context.http_redirect(url)

    msg = None
    # Complain about unknown actions
    if not action_name in get_names(cfg):
        msg = _("Unknown action %(action_name)s.") % {
            'action_name': wikiutil.escape(action_name),
        }

    # Disallow non available actions
    elif action_name[0].isupper() and not action_name in \
            get_available_actions(cfg, context.page, context.user):
        msg = _("You are not allowed to do %(action_name)s on this page.") % {
            'action_name': wikiutil.escape(action_name),
        }
        if context.user.valid:
            log_attempt(action_name + '/action unavailable',
                        False,
                        context.request,
                        context.user.name,
                        pagename=pagename)
        else:
            log_attempt(action_name + '/action unavailable',
                        False,
                        context.request,
                        pagename=pagename)
            # Suggest non valid user to login
            msg += " " + _("Login and try again.")

    if msg:
        context.theme.add_msg(msg, "error")
        context.page.send_page()
    # Try action
    else:
        from MoinMoin import action
        handler = action.getHandler(context, action_name)
        if handler is None:
            msg = _(
                "You are not allowed to do %(action_name)s on this page.") % {
                    'action_name': wikiutil.escape(action_name),
                }
            if context.user.valid:
                log_attempt(action_name + '/no handler',
                            False,
                            context.request,
                            context.user.name,
                            pagename=pagename)
            else:
                log_attempt(action_name + '/no handler',
                            False,
                            context.request,
                            pagename=pagename)
                # Suggest non valid user to login
                msg += " " + _("Login and try again.")
            context.theme.add_msg(msg, "error")
            context.page.send_page()
        else:
            handler(context.page.page_name, context)

    return context
 def __init__(self, request, user):
     log_attempt('account/created', True, request, user.name)
     Event.__init__(self, request)
     self.user = user
Ejemplo n.º 10
0
def execute(pagename, request):
    """ edit a page """
    _ = request.getText

    if 'button_preview' in request.form and 'button_spellcheck' in request.form:
        # multiple buttons pressed at once? must be some spammer/bot
        check_surge_protect(request, kick=True) # get rid of him
        return

    if not request.user.may.write(pagename):
        log_attempt('edit/no permissions', False, request, pagename=pagename)
        page = wikiutil.getLocalizedPage(request, 'PermissionDeniedPage')
        page.body = _('You are not allowed to edit this page.')
        page.page_name = pagename
        page.send_page(send_special=True)
        return

    valideditors = ['text', 'gui', ]
    editor = ''
    if request.user.valid:
        editor = request.user.editor_default
    if editor not in valideditors:
        editor = request.cfg.editor_default

    editorparam = request.values.get('editor', editor)
    if editorparam == "guipossible":
        lasteditor = editor
    elif editorparam == "textonly":
        editor = lasteditor = 'text'
    else:
        editor = lasteditor = editorparam

    if request.cfg.editor_force:
        editor = request.cfg.editor_default

    # if it is still nothing valid, we just use the text editor
    if editor not in valideditors:
        editor = 'text'

    rev = request.rev or 0
    savetext = request.form.get('savetext')
    comment = request.form.get('comment', u'')
    category = request.form.get('category')
    rstrip = int(request.form.get('rstrip', '0'))
    trivial = int(request.form.get('trivial', '0'))

    if 'button_switch' in request.form:
        if editor == 'text':
            editor = 'gui'
        else: # 'gui'
            editor = 'text'

    # load right editor class
    if editor == 'gui':
        from MoinMoin.PageGraphicalEditor import PageGraphicalEditor
        pg = PageGraphicalEditor(request, pagename)
    else: # 'text'
        from MoinMoin.PageEditor import PageEditor
        pg = PageEditor(request, pagename)

    # is invoked without savetext start editing
    if savetext is None or 'button_load_draft' in request.form:
        pg.sendEditor()
        return

    # did user hit cancel button?
    cancelled = 'button_cancel' in request.form

    from MoinMoin.error import ConvertError
    try:
        if lasteditor == 'gui':
            # convert input from Graphical editor
            format = request.form.get('format', 'wiki')
            if format == 'wiki':
                converter_name = 'text_html_text_moin_wiki'
            else:
                converter_name = 'undefined' # XXX we don't have other converters yet
            convert = wikiutil.importPlugin(request.cfg, "converter", converter_name, 'convert')
            savetext = convert(request, pagename, savetext)

        # IMPORTANT: normalize text from the form. This should be done in
        # one place before we manipulate the text.
        savetext = pg.normalizeText(savetext, stripspaces=rstrip)
    except ConvertError:
        # we don't want to throw an exception if user cancelled anyway
        if not cancelled:
            raise

    if cancelled:
        pg.sendCancel(savetext or "", rev)
        pagedir = pg.getPagePath(check_create=0)
        import os
        if not os.listdir(pagedir):
            os.removedirs(pagedir)
        return

    comment = wikiutil.clean_input(comment)

    # Add category

    # TODO: this code does not work with extended links, and is doing
    # things behind your back, and in general not needed. Either we have
    # a full interface for categories (add, delete) or just add them by
    # markup.

    if category and category != _('<No addition>'): # opera 8.5 needs this
        # strip trailing whitespace
        savetext = savetext.rstrip()

        # Add category separator if last non-empty line contains
        # non-categories.
        lines = [line for line in savetext.splitlines() if line]
        if lines:

            #TODO: this code is broken, will not work for extended links
            #categories, e.g ["category hebrew"]
            categories = lines[-1].split()

            if categories:
                confirmed = wikiutil.filterCategoryPages(request, categories)
                if len(confirmed) < len(categories):
                    # This was not a categories line, add separator
                    savetext += u'\n----\n'

        # Add new category
        if savetext and savetext[-1] != u'\n':
            savetext += ' '
        savetext += category + u'\n' # Should end with newline!

    if (request.cfg.edit_ticketing and
        not wikiutil.checkTicket(request, request.form.get('ticket', ''))):
        request.theme.add_msg(_('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'edit' }, "error")
        pg.sendEditor(preview=savetext, comment=comment, staytop=1)

    # Preview, spellcheck or spellcheck add new words
    elif ('button_preview' in request.form or
        'button_spellcheck' in request.form or
        'button_newwords' in request.form):
        pg.sendEditor(preview=savetext, comment=comment)

    # Preview with mode switch
    elif 'button_switch' in request.form:
        pg.sendEditor(preview=savetext, comment=comment, staytop=1)

    # Save new text
    else:
        try:
            from MoinMoin.security.textcha import TextCha
            if not TextCha(request).check_answer_from_form():
                raise pg.SaveError(_('TextCha: Wrong answer! Try again below...'))
            if request.cfg.comment_required and not comment:
                raise pg.SaveError(_('Supplying a comment is mandatory. Write a comment below and try again...'))
            savemsg = pg.saveText(savetext, rev, trivial=trivial, comment=comment)
        except pg.EditConflict, e:
            msg = e.message

            # Handle conflict and send editor
            pg.set_raw_body(savetext, modified=1)

            pg.mergeEditConflict(rev)
            # We don't send preview when we do merge conflict
            pg.sendEditor(msg=msg, comment=comment)
            return

        except pg.SaveError, msg:
            # Show the error message
            request.theme.add_msg(unicode(msg), "error")
            # And show the editor again
            pg.sendEditor(preview=savetext, comment=comment, staytop=1)
            return
Ejemplo n.º 11
0
def handle_action(context, pagename, action_name="show"):
    """ Actual dispatcher function for non-XMLRPC actions.

    Also sets up the Page object for this request, normalizes and
    redirects to canonical pagenames and checks for non-allowed
    actions.
    """
    _ = context.getText
    cfg = context.cfg

    # pagename could be empty after normalization e.g. '///' -> ''
    # Use localized FrontPage if pagename is empty
    if not pagename:
        context.page = wikiutil.getFrontPage(context)
    else:
        context.page = Page(context, pagename)
        if "_" in pagename and not context.page.exists():
            pagename = pagename.replace("_", " ")
            page = Page(context, pagename)
            if page.exists():
                url = page.url(context)
                return context.http_redirect(url)

    msg = None
    # Complain about unknown actions
    if not action_name in get_names(cfg):
        msg = _("Unknown action %(action_name)s.") % {"action_name": wikiutil.escape(action_name)}

    # Disallow non available actions
    elif action_name[0].isupper() and not action_name in get_available_actions(cfg, context.page, context.user):
        msg = _("You are not allowed to do %(action_name)s on this page.") % {
            "action_name": wikiutil.escape(action_name)
        }
        if context.user.valid:
            log_attempt(
                action_name + "/action unavailable", False, context.request, context.user.name, pagename=pagename
            )
        else:
            log_attempt(action_name + "/action unavailable", False, context.request, pagename=pagename)
            # Suggest non valid user to login
            msg += " " + _("Login and try again.")

    if msg:
        context.theme.add_msg(msg, "error")
        context.page.send_page()
    # Try action
    else:
        from MoinMoin import action

        handler = action.getHandler(context, action_name)
        if handler is None:
            msg = _("You are not allowed to do %(action_name)s on this page.") % {
                "action_name": wikiutil.escape(action_name)
            }
            if context.user.valid:
                log_attempt(action_name + "/no handler", False, context.request, context.user.name, pagename=pagename)
            else:
                log_attempt(action_name + "/no handler", False, context.request, pagename=pagename)
                # Suggest non valid user to login
                msg += " " + _("Login and try again.")
            context.theme.add_msg(msg, "error")
            context.page.send_page()
        else:
            handler(context.page.page_name, context)

    return context
Ejemplo n.º 12
0
 def __init__(self, request, user):
     log_attempt('account/created', True, request, user.name)
     Event.__init__(self, request)
     self.user = user