Example #1
0
    def mainloop(self):
        # we don't expect non-option arguments
        self.init_request()
        request = self.request
        # Checks for a template page and sets homepage_default_text
        if self.options.template_page and Page(
                self.request, self.options.template_page).exists():
            homepage_default_text = Page(
                self.request, self.options.template_page).get_raw_body()
            # replace is needed because substitution is done for request.user
            # see option --user
            homepage_default_text = homepage_default_text.replace(
                '@ME@', "%(username)s")
            homepage_default_text = homepage_default_text.replace(
                '@EMAIL@', "<<MailTo(%(obfuscated_mail)s)>>")
        else:
            homepage_default_text = '''#acl %(username)s:read,write,delete,revert Default

== %(username)s ==

Email: <<MailTo(%(obfuscated_mail)s)>>
## You can even more obfuscate your email address by adding more uppercase letters followed by a leading and trailing blank.

----
CategoryHomepage
'''
        # Check for user
        if self.options.homepage_creator:
            uid = user.getUserId(request, self.options.homepage_creator)
            request.user = user.User(request, uid)
        # Check for Group definition
        members = []
        if self.options.user_homepage:
            members = [
                self.options.user_homepage,
            ]
        elif self.options.name_of_group_page:
            members = request.groups.get(self.options.name_of_group_page, [])
        elif self.options.all_users:
            uids = user.getUserList(request)
            members = [user.User(request, uid).name for uid in uids]

        if not members:
            print "No user selected!"
            return

        # loop through members for creating homepages
        for name in members:
            uid = user.getUserId(request, name)
            account = user.User(request, uid)
            homepage_text = homepage_default_text % {
                "username": account.name,
                "obfuscated_mail": encodeSpamSafeEmail(account.email)
            }
            self.write_homepage(account, homepage_text)
Example #2
0
    def mainloop(self):
        # we don't expect non-option arguments
        self.init_request()
        request = self.request
        # Checks for a template page and sets homepage_default_text
        if self.options.template_page and Page(self.request, self.options.template_page).exists():
            homepage_default_text = Page(self.request, self.options.template_page).get_raw_body()
            # replace is needed because substitution is done for request.user
            # see option --user
            homepage_default_text = homepage_default_text.replace('@ME@', "%(username)s")
            homepage_default_text = homepage_default_text.replace('@EMAIL@', "<<MailTo(%(obfuscated_mail)s)>>")
        else:
            homepage_default_text = '''#acl %(username)s:read,write,delete,revert Default
#format wiki

== %(username)s ==

Email: <<MailTo(%(obfuscated_mail)s)>>
## You can even more obfuscate your email address by adding more uppercase letters followed by a leading and trailing blank.

----
CategoryHomepage
'''
        # Check for user
        if self.options.homepage_creator:
            uid = user.getUserId(request, self.options.homepage_creator)
            request.user = user.User(request, uid)
        # Check for Group definition
        members = []
        if self.options.user_homepage:
            members = [self.options.user_homepage, ]
        elif self.options.name_of_group_page:
            members = request.groups.get(self.options.name_of_group_page, [])
        elif self.options.all_users:
            uids = user.getUserList(request)
            members = [user.User(request, uid).name for uid in uids]

        if not members:
            print "No user selected!"
            return

        # loop through members for creating homepages
        for name in members:
            uid = user.getUserId(request, name)
            account = user.User(request, uid)
            homepage_text = homepage_default_text % {
                                                 "username": account.name,
                                                 "obfuscated_mail": encodeSpamSafeEmail(account.email)
                                                 }
            self.write_homepage(account, homepage_text)
Example #3
0
def _do_recover(request):
    _ = request.getText
    form = request.form
    if not request.cfg.mail_enabled:
        return _("""This wiki is not enabled for mail processing.
Contact the owner of the wiki, who can enable email.""")

    try:
        email = wikiutil.clean_input(form['email'].lower())
        if not email:
            # continue if email not given
            raise KeyError

        u = user.get_by_email_address(request, email)

        return _do_email(request, u)
    except KeyError:
        pass

    try:
        username = wikiutil.clean_input(form['name'])
        if not username:
            # continue if name not given
            raise KeyError

        u = user.User(request, user.getUserId(request, username))

        return _do_email(request, u)
    except KeyError:
        pass

    # neither succeeded, give error message
    return _("Please provide a valid email address or a username!")
Example #4
0
def _do_recover(request):
    _ = request.getText
    form = request.form
    if not request.cfg.mail_enabled:
        return _("""This wiki is not enabled for mail processing.
Contact the owner of the wiki, who can enable email.""")

    try:
        email = wikiutil.clean_input(form['email'].lower())
        if not email:
            # continue if email not given
            raise KeyError

        u = user.get_by_email_address(request, email)

        return _do_email(request, u)
    except KeyError:
        pass

    try:
        username = wikiutil.clean_input(form['name'])
        if not username:
            # continue if name not given
            raise KeyError

        u = user.User(request, user.getUserId(request, username))

        return _do_email(request, u)
    except KeyError:
        pass

    # neither succeeded, give error message
    return _("Please provide a valid email address or a username!")
Example #5
0
    def run(self, name, uid):
        flaskg.unprotected_storage = app.unprotected_storage
        flags_given = name or uid
        if not flags_given:
            print 'incorrect number of arguments'
            import sys
            sys.exit()

        if uid:
            u = user.User(uid)
        elif name:
            uid = user.getUserId(name)
            u = user.User(uid)

        if not u.exists():
            print 'This user "%s" does not exists!' % u.name
            return

        print " %-20s %-25s %-35s" % (u.id, u.name, u.email),
        if not u.disabled: # only disable once
            u.disabled = 1
            u.name = "%s-%s" % (u.name, u.id)
            if u.email:
                u.email = "%s-%s" % (u.email, u.id)
            u.subscribed_items = [] # avoid using email
            u.save()
            print "- disabled."
        else:
            print "- is already disabled."
Example #6
0
    def mail_admins_about(self, request, page_name, score):
        """Send email to the AdminGroup about a suspect page."""
        return
        admin_text = Page(request, "AdminGroup").get_raw_body()
        group = Group(request, admin_text)
        emails = []
        for name in group.members():
            uid = getUserId(request, name)
            if uid is None:
                continue
            u = User(request, uid)
            emails.append(u.email)
        if score < self.spam_cutoff:
            subject = "Possible wiki spam"
            text = """\
This page as submitted to the wiki might be spam:
    %(page_name)s
If that is not the case, add the page's URL (including action=raw and the
revision number) to HamPages then revert the page to that revision.  If it
is spam, add it instead to SpamPages.
""" % locals()
        else:
            subject = "Probable wiki spam"
            text = """\
This page as submitted to the wiki is likely to be spam:
    %(page_name)s
If that is not the case, add the page's URL (including action=raw and the
revision number) to HamPages then revert the page to that revision.  If it
is spam, do nothing.
""" % locals()
        sendmail(request, emails, subject, text)
Example #7
0
    def _handle_name_continuation(self, request):
        _ = request.getText
        logging.debug('openid %s' % request.session)
        logging.debug('openid %s' % request.form.get('openid_identifier'))

        if not 'openid.id' in request.session:
            return CancelLogin(_('No OpenID found in session.'))

        newname = request.form.get('username', '')
        if not newname:
            return MultistageFormLogin(self._get_account_name)
        if not user.isValidName(request, newname):
            return MultistageFormLogin(self._get_account_name_inval_user)
        uid = None
        if newname:
            uid = user.getUserId(request, newname)
        if not uid:
            # we can create a new user with this name :)
            u = user.User(request,
                          auth_method=self.name,
                          auth_username=request.session['openid.id'],
                          auth_attribs=self.auth_attribs)
            u.name = newname
            u = self._handle_user_data(request, u)
            return ContinueLogin(u)
        # requested username already exists. if they know the password,
        # they can associate that account with the openid.
        assoc = lambda req, form: self._associate_account(req, form, newname)
        return MultistageFormLogin(assoc)
Example #8
0
    def _handle_user_data(self, request, u):
        create = not u
        if create:
            # pass in a created but unsaved user object
            u = user.User(request, auth_method=self.name, auth_username=request.session["openid.id"])
            # invalid name
            u.name = ""
            u = self._create_user(request.session["openid.info"], u)

        if u:
            self._update_user(request.session["openid.info"], u)

            # just in case the wiki admin screwed up
            if not user.isValidName(request, u.name) or (create and user.getUserId(request, u.name)):
                return None

            if not hasattr(u, "openids"):
                u.openids = []
            if not request.session["openid.id"] in u.openids:
                u.openids.append(request.session["openid.id"])

            u.save()

            del request.session["openid.id"]
            del request.session["openid.info"]

        return u
Example #9
0
    def _handle_user_data(self, request, u):
        create = not u
        if create:
            # pass in a created but unsaved user object
            u = user.User(request,
                          auth_method=self.name,
                          auth_username=request.session['openid.id'],
                          auth_attribs=self.auth_attribs)
            # invalid name
            u.name = ''
            u = self._create_user(request.session['openid.info'], u,
                                  request.cfg)

        if u:
            self._update_user(request.session['openid.info'], u, request.cfg)

            # just in case the wiki admin screwed up
            if (not user.isValidName(request, u.name)
                    or (create and user.getUserId(request, u.name))):
                return None

            if not hasattr(u, 'openids'):
                u.openids = []
            if not request.session['openid.id'] in u.openids:
                u.openids.append(request.session['openid.id'])

            u.save()

            del request.session['openid.id']
            del request.session['openid.info']

        return u
    def _handle_name_continuation(self, request):
        _ = request.getText
        if not 'openid.id' in request.session:
            return CancelLogin(_('No OpenID found in session.'))

        newname = request.form.get('username', '')
        if not newname:
            return MultistageFormLogin(self._get_account_name)
        if not user.isValidName(request, newname):
            return MultistageFormLogin(self._get_account_name_inval_user)
        uid = None
        if newname:
            uid = user.getUserId(request, newname)
        if not uid:
            # we can create a new user with this name :)
            u = user.User(request, auth_method=self.name,
                          auth_username=request.session['openid.id'],
                          auth_attribs=self.auth_attribs)
            u.name = newname
            u = self._handle_user_data(request, u)
            return ContinueLogin(u)
        # requested username already exists. if they know the password,
        # they can associate that account with the openid.
        assoc = lambda req, form: self._associate_account(req, form, newname)
        return MultistageFormLogin(assoc)
Example #11
0
def execute(pagename, request):
    """ set values in user profile """
    _ = request.getText
    cfg = request.cfg
    form = request.form

    if not request.user.isSuperUser():
        request.theme.add_msg(
            _("Only superuser is allowed to use this action."), "error")
    elif (request.method == 'POST'
          and wikiutil.checkTicket(request, form.get('ticket', ''))):
        user_name = form.get('name', '')
        key = form.get('key', '')
        val = form.get('val', '')
        if key in cfg.user_checkbox_fields:
            val = int(val)
        uid = user.getUserId(request, user_name)
        theuser = user.User(request, uid)
        oldval = getattr(theuser, key)
        setattr(theuser, key, val)
        theuser.save()
        request.theme.add_msg(
            '%s.%s: %s -> %s' %
            tuple([wikiutil.escape(s) for s in [user_name, key, oldval, val]]),
            "info")

    Page(request, pagename).send_page()
def _create_user(request):
    collab_mode = getattr(request.cfg, 'collab_mode', False)
    _ = request.getText
    form = request.form

    if request.method != 'POST':
        return

    if not wikiutil.checkTicket(request, form.get('ticket', '')):
        return

    if not TextCha(request).check_answer_from_form():
        return _('TextCha: Wrong answer! Go back and try again...')

    # Create user profile
    theuser = user.User(request, auth_method="new-user")

    # Require non-empty name
    try:
        if collab_mode:
            name = wikiutil.clean_input(form.get('email', ['']))
            theuser.name = name.strip()
        else:
            theuser.name = form['name']
    except KeyError:
        return _("Empty user name. Please enter a user name.")

    # Don't allow creating users with invalid names
    if not user.isValidName(request, theuser.name):
        return _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(theuser.name)

    # Name required to be unique. Check if name belong to another user.
    if user.getUserId(request, theuser.name):
        return _("This user name already belongs to somebody else.")

    # try to get the password and pw repeat
    password = form.get('password1', '')
    password2 = form.get('password2', '')

    # Check if password is given and matches with password repeat
    if password != password2:
        return _("Passwords don't match!")
    if not password:
        return _("Please specify a password!")

    pw_checker = request.cfg.password_checker
    if pw_checker:
        pw_error = pw_checker(request, theuser.name, password)
        if pw_error:
            return _("Password not acceptable: %s") % wikiutil.escape(pw_error)

    # Encode password
    try:
        theuser.enc_password = user.encodePassword(request.cfg, password)
    except UnicodeError, err:
        # Should never happen
        return "Can't encode password: %s" % wikiutil.escape(str(err))
Example #13
0
 def _special_Known(self, request, name, dowhat, rightsdict):
     """ check if user <name> is known to us,
         that means that there is a valid user account present.
         works for subscription emails.
     """
     if user.getUserId(request, name): # is a user with this name known?
         return rightsdict.get(dowhat)
     return None
Example #14
0
 def _special_Known(self, name, dowhat, rightsdict):
     """ check if user <name> is known to us,
         that means that there is a valid user account present.
         works for subscription emails.
     """
     if user.getUserId(name): # is a user with this name known?
         return rightsdict.get(dowhat)
     return None
def nuke_user(request, username):
    """ completely delete a user """
    user_dir = request.cfg.user_dir
    user_id = user.getUserId(request, username)
    # really get rid of the user
    fpath = os.path.join(user_dir, user_id)
    os.remove(fpath)
    user.clearLookupCaches(request)
Example #16
0
def nuke_user(request, username):
    """ completely delete a user """
    user_dir = request.cfg.user_dir
    user_id = user.getUserId(request, username)
    # really get rid of the user
    fpath = os.path.join(user_dir, user_id)
    os.remove(fpath)
    user.clearLookupCaches(request)
Example #17
0
def _create_user(request):
    _ = request.getText
    form = request.form

    if request.method != 'POST':
        return

    if not wikiutil.checkTicket(request, form.get('ticket', '')):
        return

    if not TextCha(request).check_answer_from_form():
        return _('TextCha: Wrong answer! Go back and try again...')

    # Create user profile
    theuser = user.User(request, auth_method="new-user")

    # Require non-empty name
    try:
        theuser.name = form['name']
    except KeyError:
        return _("Empty user name. Please enter a user name.")

    # Don't allow creating users with invalid names
    if not user.isValidName(request, theuser.name):
        return _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""",
                 wiki=True) % wikiutil.escape(theuser.name)

    # Name required to be unique. Check if name belong to another user.
    if user.getUserId(request, theuser.name):
        return _("This user name already belongs to somebody else.")

    # try to get the password and pw repeat
    password = form.get('password1', '')
    password2 = form.get('password2', '')

    # Check if password is given and matches with password repeat
    if password != password2:
        return _("Passwords don't match!")
    if not password:
        return _("Please specify a password!")

    pw_checker = request.cfg.password_checker
    if pw_checker:
        pw_error = pw_checker(request, theuser.name, password)
        if pw_error:
            return _("Password not acceptable: %s") % wikiutil.escape(pw_error)

    # Encode password
    if password and not password.startswith('{SHA}'):
        try:
            theuser.enc_password = user.encodePassword(password)
        except UnicodeError, err:
            # Should never happen
            return "Can't encode password: %s" % wikiutil.escape(str(err))
Example #18
0
def nuke_user(request, username):
    """ completely delete a user """
    user_dir = request.cfg.user_dir
    user_id = user.getUserId(request, username)
    # really get rid of the user
    fpath = os.path.join(user_dir, user_id)
    os.remove(fpath)
    # delete cache
    arena = 'user'
    key = 'name2id'
    caching.CacheEntry(request, arena, key, scope='wiki').remove()
 def test_for_email_attribut_by_uid(self):
     """
     checks access to the email attribute by getting the user object from the uid
     """
     name = u"__TestUser2__"
     password = u"ekERErwerwerh"
     email = "__TestUser2__@moinhost"
     self.createUser(name, password, email=email)
     uid = user.getUserId(self.request, name)
     theuser = user.User(self.request, uid)
     assert theuser.email == email
Example #20
0
def nuke_user(request, username):
    """ completely delete a user """
    user_dir = request.cfg.user_dir
    user_id = user.getUserId(request, username)
    # really get rid of the user
    fpath = os.path.join(user_dir, user_id)
    os.remove(fpath)
    # delete cache
    arena = 'user'
    key = 'name2id'
    caching.CacheEntry(request, arena, key, scope='wiki').remove()
Example #21
0
 def test_for_email_attribut_by_uid(self):
     """
     checks access to the email attribute by getting the user object from the uid
     """
     name = u"__TestUser2__"
     password = u"ekERErwerwerh"
     email = "__TestUser2__@moinhost"
     self.createUser(name, password, email=email)
     uid = user.getUserId(self.request, name)
     theuser = user.User(self.request, uid)
     assert theuser.email == email
Example #22
0
def execute(pagename, request):
    """                                                                         
    Handle action=IntraFarmCopy
    """

    if not request.user.may.read(pagename):
        Page(request, pagename).send_page()
        return

    # Which local farm wiki - assume team for now                               
    to_wiki_url = COPY_TO_WIKI_URL 
    # New page name                                               
    to_wiki_pagename = '%s%s' % (COPY_TO_PREFIX, pagename)

    # create page at local wiki if it doesn't exist                             
    to_request = ScriptContext(to_wiki_url)
    # login this user remotely
    to_uid = user.getUserId(to_request, request.user.name)
    to_user = user.User(to_request, id=to_uid, name=request.user.name, password=request.user.password, auth_method="moin")
    to_request.user = to_user

    try:
        page = Page(to_request, to_wiki_pagename)
    except:
        return action_error(u'Error accessing destination page')
    if not page.exists():
        pe = PageEditor(to_request, to_wiki_pagename)
        # make initial revision pointer to original                             
        try:
            pe.saveText(u'[[%s:%s]]' % (request.cfg.interwikiname, pagename), 0, comment="Automated IntraFarmCopy pointing to original page")
        except pe.Unchanged:
            return action_error(u'Could not save initial page')
	except pe.AccessDenied:
            return action_error(u'Could not acquire credentials')
        # make next revision content of this page
        try:
            pe.saveText(Page(request, pagename).get_raw_body(), 0, comment="Automated IntraFarmCopy importing contents from original page at [[%s:%s]]" % (request.cfg.interwikiname, pagename))
        except pe.Unchanged:
            return action_error(u'Could not save destination page text')
	# send attachments over
        attachments = AttachFile._get_files(request, pagename)
	for attachname in attachments:
	    filename = AttachFile.getFilename(request, pagename, attachname)
	    if not os.path.isfile(filename):
	        continue
	    to_filename = AttachFile.getFilename(to_request, to_wiki_pagename, attachname)
	    shutil.copyfile(filename, to_filename)
	    AttachFile._addLogEntry(to_request, 'ATTNEW', to_wiki_pagename, attachname) 
        # redirect user to view new page in other wiki                          
        request.http_redirect('%s%s' % (to_wiki_url, to_wiki_pagename))
	return
    else:
	return action_error(u'Destination page already exists!')
Example #23
0
    def run(self, name, aliasname, email, openid, password):
        flaskg.unprotected_storage = app.unprotected_storage
        msg = user.create_user(username=name,
                               password=password,
                               email=email,
                               openid=openid)

        if msg:
            print msg
        else:
            uid = user.getUserId(name)
            u = user.User(uid)
            print " %-20s %-25s %-35s - created." % (u.id, u.name, u.email),
Example #24
0
    def handle_form(self):
        _ = self._
        request = self.request
        form = request.form

        if form.has_key('cancel'):
            return

        if request.method != 'POST':
            return

        if not wikiutil.checkTicket(request, form['ticket']):
            return

        user_name = form.get('user_name', '')
        if user_name:
            uid = user.getUserId(request, user_name)
            if uid:
                theuser = user.User(request, uid, auth_method='setuid')
            else:
                # Don't allow creating users with invalid names
                if not user.isValidName(request, user_name):
                    return 'error', _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""",
                                      wiki=True) % wikiutil.escape(user_name)
                theuser = user.User(request, auth_method='setuid')
                theuser.name = user_name
        else:
            uid = form.get('selected_user', '')
            if not uid:
                return 'error', _("No user selected")
            theuser = user.User(request, uid, auth_method='setuid')
            if not theuser or not theuser.exists():
                return 'error', _("No user selected")
        # set valid to True so superusers can even switch
        # to disable accounts
        theuser.valid = True
        request._setuid_real_user = request.user
        # now continue as the other user
        request.user = theuser
        if not uid:
            # create new user
            theuser.save()
        return _(
            "You can now change the settings of the selected user account; log out to get back to your account."
        )
Example #25
0
def userprofile(user_name):
    """
    Set values in user profile
    """
    # XXX add superuser check
    uid = user.getUserId(user_name)
    u = user.User(uid)
    if request.method == 'GET':
        return _(u"User profile of %(username)s: %(email)r",
                 username=user_name,
                 email=(u.email, u.disabled))

    if request.method == 'POST':
        key = request.form.get('key', '')
        val = request.form.get('val', '')
        ok = False
        if hasattr(u, key):
            ok = True
            oldval = getattr(u, key)
            if isinstance(oldval, bool):
                val = bool(val)
            elif isinstance(oldval, int):
                val = int(val)
            elif isinstance(oldval, unicode):
                val = unicode(val)
            else:
                ok = False
        if ok:
            setattr(u, key, val)
            theuser.save()
            flash(
                '%s.%s: %s -> %s' % (
                    user_name,
                    key,
                    unicode(oldval),
                    unicode(val),
                ), "info")
        else:
            flash('modifying %s.%s failed' % (
                user_name,
                key,
            ), "error")
    return redirect(url_for('admin.userbrowser'))
Example #26
0
    def run(self, name, uid, password):
        flaskg.unprotected_storage = app.unprotected_storage
        flags_given = name or uid
        if not flags_given:
            print 'incorrect number of arguments'
            import sys
            sys.exit()

        if uid:
            u = user.User(uid)
        elif name:
            uid = user.getUserId(name)
            u = user.User(uid)

        if not u.exists():
            print 'This user "%s" does not exists!' % u.name
            return

        u.enc_password = user.encodePassword(password)
        u.save()
        print 'Password changed.'
    def mail_admins_about(self, request, page_name, score):
        """Send email to the AdminGroup about a suspect page."""

        # This does not yet work.  I've yet to figure out how to extract the
        # email addresses of the members of the AdminGroup.
        return

        admin_text = Page(request, "AdminGroup").get_raw_body()
        group = Group(request, admin_text)
        emails = []
        for name in group.members():
            uid = getUserId(request, name)
            if uid is None:
                continue
            u = User(request, uid)
            emails.append(u.email)
        if score < self.spam_cutoff:
            subject = "Possible wiki spam"
            text = """\
This page as submitted to the wiki might be spam:

    %(page_name)s

If that is not the case, add the page's URL (including action=raw and the
revision number) to HamPages then revert the page to that revision.  If it
is spam, add it instead to SpamPages.
""" % locals()
        else:
            subject = "Probable wiki spam"
            text = """\
This page as submitted to the wiki is likely to be spam:

    %(page_name)s

If that is not the case, add the page's URL (including action=raw and the
revision number) to HamPages then revert the page to that revision.  If it
is spam, do nothing.
""" % locals()
        sendmail(request, emails, subject, text)
Example #28
0
def execute(pagename, request):
    """ set values in user profile """
    _ = request.getText
    cfg = request.cfg
    form = request.form

    if not request.user.isSuperUser():
        request.theme.add_msg(_("Only superuser is allowed to use this action."), "error")
    else:
        user_name = form.get('name', [''])[0]
        key = form.get('key', [''])[0]
        val = form.get('val', [''])[0]
        if key in cfg.user_checkbox_fields:
            val = int(val)
        uid = user.getUserId(request, user_name)
        theuser = user.User(request, uid)
        oldval = getattr(theuser, key)
        setattr(theuser, key, val)
        theuser.save()
        request.theme.add_msg('%s.%s: %s -> %s' % (user_name, key, oldval, val), "info")

    Page(request, pagename).send_page()
Example #29
0
    def _handle_name_continuation(self, request):
        if not "openid.id" in request.session:
            return CancelLogin(None)

        _ = request.getText
        newname = request.form.get("username", [""])[0]
        if not newname:
            return MultistageFormLogin(self._get_account_name)
        if not user.isValidName(request, newname):
            return MultistageFormLogin(self._get_account_name_inval_user)
        uid = None
        if newname:
            uid = user.getUserId(request, newname)
        if not uid:
            # we can create a new user with this name :)
            u = user.User(request, auth_method=self.name, auth_username=request.session["openid.id"])
            u.name = newname
            u = self._handle_user_data(request, u)
            return ContinueLogin(u)
        # requested username already exists. if they know the password,
        # they can associate that account with the openid.
        assoc = lambda req, form: self._associate_account(req, form, newname)
        return MultistageFormLogin(assoc)
Example #30
0
def execute(pagename, request):
    """ set values in user profile """
    _ = request.getText
    cfg = request.cfg
    form = request.form

    if not request.user.isSuperUser():
        request.theme.add_msg(_("Only superuser is allowed to use this action."), "error")
    elif (request.method == 'POST' and
          wikiutil.checkTicket(request, form.get('ticket', ''))):
        user_name = form.get('name', '')
        key = form.get('key', '')
        val = form.get('val', '')
        if key in cfg.user_checkbox_fields:
            val = int(val)
        uid = user.getUserId(request, user_name)
        theuser = user.User(request, uid)
        oldval = getattr(theuser, key)
        setattr(theuser, key, val)
        theuser.save()
        request.theme.add_msg('%s.%s: %s -> %s' % tuple([wikiutil.escape(s) for s in [user_name, key, oldval, val]]), "info")

    Page(request, pagename).send_page()
Example #31
0
def newday (Wiki, ParentPage, TemplatePage, NewPage, Editor, UidName, GidName):

    from os import seteuid,setegid
    from pwd import getpwnam
    from grp import getgrnam

    uid = getpwnam(UidName).pw_uid
    gid = getgrnam(GidName).gr_gid

    setegid(gid)
    seteuid(uid)

    from MoinMoin.PageEditor import PageEditor
    from MoinMoin.Page import Page
    from MoinMoin.user import getUserId, User
    from MoinMoin.web.contexts import ScriptContext

    PageName = "%s/%s" % (ParentPage,NewPage)

    RequestPage = ScriptContext(Wiki, PageName)
    UserId = getUserId(RequestPage, Editor)
    RequestPage.user = User(RequestPage, UserId)

    Editor = PageEditor(RequestPage, PageName)
    Dummy, Revision, Exists = Editor.get_rev()

    if not Exists:

        RequestTemplate = ScriptContext(Wiki, TemplatePage)
        Viewer = Page(RequestTemplate, TemplatePage)

        Text = Viewer.getPageText().replace("@PAGE@", NewPage)
        Header = Viewer.getPageHeader()

        Text=Header+Text

        return Editor.saveText(Text, Revision)
Example #32
0
    if not password:
        d = Dialog('TurnKey Linux - First boot configuration')
        password = d.get_password(
            "MoinMoin Password",
            "Enter new password for the MoinMoin 'admin' account.")

    if not email:
        if 'd' not in locals():
            d = Dialog('TurnKey Linux - First boot configuration')

        email = d.get_email(
            "MoinMoin Email",
            "Enter email address for the MoinMoin 'admin' account.",
            "*****@*****.**")

    inithooks_cache.write('APP_EMAIL', email)

    sys.path.append("/etc/moin")
    request = ScriptContext()
    cfg = request.cfg

    userid = user.getUserId(request, 'admin')
    u = user.User(request, userid)
    u.email = email
    u.enc_password = user.encodePassword(cfg, password)
    u.save()


if __name__ == "__main__":
    main()
Example #33
0
    def handleData(self):
        _ = self._
        form = self.request.form
    
        if form.has_key('logout'):
            # clear the cookie in the browser and locally. Does not
            # check if we have a valid user logged, just make sure we
            # don't have one after this call.
            self.request.deleteCookie()
            return _("Cookie deleted. You are now logged out.")
    
        if form.has_key('login_sendmail'):
            if not self.cfg.mail_smarthost:
                return _("""This wiki is not enabled for mail processing.
Contact the owner of the wiki, who can enable email.""")
            try:
                email = form['email'][0].lower()
            except KeyError:
                return _("Please provide a valid email address!")
    
            text = ''
            users = user.getUserList(self.request)
            for uid in users:
                theuser = user.User(self.request, uid)
                if theuser.valid and theuser.email.lower() == email:
                    text = "%s\n\nID: %s\nName: %s\nPassword: %s\nLogin URL: %s/?action=userform&amp;uid=%s" % (
                        text, theuser.id, theuser.name, theuser.enc_password, self.request.getBaseURL(), theuser.id)
   
            if not text:
                return _("Found no account matching the given email address '%(email)s'!") % {'email': wikiutil.escape(email)}
    
            mailok, msg = util.mail.sendmail(self.request, [email], 
                'Your wiki account data', text, mail_from=self.cfg.mail_from)
            return wikiutil.escape(msg)

        if form.has_key('login'):
            # Trying to login with a user name and a password

            # Require valid user name
            name = form.get('username', [''])[0]
            if not user.isValidName(self.request, name):
                return _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""") % wikiutil.escape(name)

            # Check that user exists
            if not user.getUserId(self.request, name):
                return _('Unknown user name: {{{"%s"}}}. Please enter'
                         ' user name and password.') % name

            # Require password
            password = form.get('password',[None])[0]
            if not password:
                return _("Missing password. Please enter user name and"
                         " password.")

            # Load the user data and check for validness
            theuser = user.User(self.request, name=name, password=password)
            if not theuser.valid:
                return _("Sorry, wrong password.")
            
            # Save the user and send a cookie
            self.request.user = theuser
            self.request.setCookie()

        elif form.has_key('uid'):
            # Trying to login with the login URL, soon to be removed!
            try:
                 uid = form['uid'][0]
            except KeyError:
                 return _("Bad relogin URL.")

            # Load the user data and check for validness
            theuser = user.User(self.request, uid)
            if not theuser.valid:
                return _("Unknown user.")
            
            # Save the user and send a cookie
            self.request.user = theuser
            self.request.setCookie()           
        
        else:
            # Save user profile
            theuser = user.User(self.request)
                
            # Require non-empty name
            try:
                theuser.name = form['username'][0]
            except KeyError:
                return _("Empty user name. Please enter a user name.")

            # Don't allow users with invalid names
            if not user.isValidName(self.request, theuser.name):
                return _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""") % wikiutil.escape(theuser.name)

            # Is this an existing user trying to change information or a new user?
            # Name required to be unique. Check if name belong to another user.
            newuser = 1
            if user.getUserId(self.request, theuser.name):
                if theuser.name != self.request.user.name:
                    return _("This user name already belongs to somebody else.")
                else:
                    newuser = 0

            # try to get the password and pw repeat
            password = form.get('password', [''])[0]
            password2 = form.get('password2',[''])[0]

            # Check if password is given and matches with password repeat
            if password != password2:
                return _("Passwords don't match!")
            if not password and newuser:
                return _("Please specify a password!")
            # Encode password
            if password and not password.startswith('{SHA}'):
                try:
                    theuser.enc_password = user.encodePassword(password)
                except UnicodeError, err:
                    # Should never happen
                    return "Can't encode password: %s" % str(err)

            # try to get the (optional) email
            email = form.get('email', [''])[0]
            theuser.email = email.strip()

            # Require email if acl is enabled
            if not theuser.email and self.cfg.acl_enabled:
                return _("Please provide your email address. If you loose your"
                         " login information, you can get it by email.")

            # Email required to be unique
            # See also MoinMoin/scripts/moin_usercheck.py
            if theuser.email:
                users = user.getUserList(self.request)
                for uid in users:
                    if uid == theuser.id:
                        continue
                    thisuser = user.User(self.request, uid)
                    if thisuser.email == theuser.email:
                        return _("This email already belongs to somebody else.")

    
            # editor size
            theuser.edit_rows = util.web.getIntegerInput(self.request, 'edit_rows', theuser.edit_rows, 10, 60)
                
            # time zone
            theuser.tz_offset = util.web.getIntegerInput(self.request, 'tz_offset', theuser.tz_offset, -84600, 84600)
    
            # datetime format
            try:
                dt_d_combined = UserSettings._date_formats.get(form['datetime_fmt'][0], '')
                theuser.datetime_fmt, theuser.date_fmt = dt_d_combined.split(' & ')
            except (KeyError, ValueError):
                pass
    
            # try to get the (optional) theme
            theme_name = form.get('theme_name', [self.cfg.theme_default])[0]
            if theme_name != theuser.theme_name:
                # if the theme has changed, load the new theme
                # so the user has a direct feedback
                # WARNING: this should be refactored (i.e. theme load
                # after userform handling), cause currently the
                # already loaded theme is just replaced (works cause
                # nothing has been emitted yet)
                theuser.theme_name = theme_name
                if self.request.loadTheme(theuser.theme_name) > 0:
                    theme_name = wikiutil.escape(theme_name)
                    return _("The theme '%(theme_name)s' could not be loaded!") % locals()

            # User CSS URL
            theuser.css_url = form.get('css_url', [''])[0]
    
            # try to get the (optional) preferred language
            theuser.language = form.get('language', [''])[0]

            # checkbox options
            if not newuser:
                for key, label in user.User._checkbox_fields:
                    value = form.get(key, ["0"])[0]
                    try:
                        value = int(value)
                    except ValueError:
                        pass
                    else:
                        setattr(theuser, key, value)
    
            # quicklinks for navibar
            theuser.quicklinks = self.decodePageList('quicklinks')            
            
            # subscription for page change notification
            theuser.subscribed_pages = self.decodePageList('subscribed_pages')
                    
            # save data and send cookie
            theuser.save()            
            self.request.user = theuser
            self.request.setCookie()

            result = _("User preferences saved!")
            if _debug:
                result = result + util.dumpFormData(form)
            return result
Example #34
0
    def _save_user_prefs(self):
        _ = self._
        form = self.request.form
        request = self.request

        if not 'name' in request.user.auth_attribs:
            # Require non-empty name
            new_name = wikiutil.clean_input(form.get('name', request.user.name)).strip()

            # Don't allow changing the name to an invalid one
            if not user.isValidName(request, new_name):
                return 'error', _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(new_name)

            # Is this an existing user trying to change information or a new user?
            # Name required to be unique. Check if name belong to another user.
            existing_id = user.getUserId(request, new_name)
            if existing_id is not None and existing_id != request.user.id:
                return 'error', _("This user name already belongs to somebody else.")

            if not new_name:
                return 'error', _("Empty user name. Please enter a user name.")

            # done sanity checking the name, set it
            request.user.name = new_name


        if not 'email' in request.user.auth_attribs:
            # try to get the email
            new_email = wikiutil.clean_input(form.get('email', request.user.email)).strip()

            # Require email
            if not new_email and 'email' not in request.cfg.user_form_remove:
                return 'error', _("Please provide your email address. If you lose your"
                                  " login information, you can get it by email.")

            # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py
            if new_email and request.cfg.user_email_unique:
                other = user.get_by_email_address(request, new_email)
                if other is not None and other.id != request.user.id:
                    return 'error', _("This email already belongs to somebody else.")

            # done checking the email, set it
            request.user.email = new_email


        if not 'jid' in request.user.auth_attribs:
            # try to get the jid
            new_jid = wikiutil.clean_input(form.get('jid', '')).strip()

            jid_changed = request.user.jid != new_jid
            previous_jid = request.user.jid

            if new_jid and request.cfg.user_jid_unique:
                other = user.get_by_jabber_id(request, new_jid)
                if other is not None and other.id != request.user.id:
                    return 'error', _("This jabber id already belongs to somebody else.")

            if jid_changed:
                set_event = events.JabberIDSetEvent(request, new_jid)
                unset_event = events.JabberIDUnsetEvent(request, previous_jid)
                events.send_event(unset_event)
                events.send_event(set_event)

            # done checking the JID, set it
            request.user.jid = new_jid


        if not 'aliasname' in request.user.auth_attribs:
            # aliasname
            request.user.aliasname = wikiutil.clean_input(form.get('aliasname', '')).strip()

        # editor size
        request.user.edit_rows = util.web.getIntegerInput(request, 'edit_rows',
                                                          request.user.edit_rows, 0, 999)

        # try to get the editor
        request.user.editor_default = wikiutil.clean_input(form.get('editor_default', self.cfg.editor_default))
        request.user.editor_ui = wikiutil.clean_input(form.get('editor_ui', self.cfg.editor_ui))

        # time zone
        request.user.tz_offset = util.web.getIntegerInput(request, 'tz_offset',
                                                          request.user.tz_offset, -84600, 84600)

        # datetime format
        try:
            dt_d_combined = Settings._date_formats.get(form['datetime_fmt'], '')
            request.user.datetime_fmt, request.user.date_fmt = dt_d_combined.split(' & ')
        except (KeyError, ValueError):
            request.user.datetime_fmt = '' # default
            request.user.date_fmt = '' # default

        # try to get the (optional) theme
        theme_name = wikiutil.clean_input(form.get('theme_name', self.cfg.theme_default))
        if theme_name != request.user.theme_name:
            # if the theme has changed, load the new theme
            # so the user has a direct feedback
            # WARNING: this should be refactored (i.e. theme load
            # after userform handling), cause currently the
            # already loaded theme is just replaced (works cause
            # nothing has been emitted yet)
            request.user.theme_name = theme_name
            if load_theme_fallback(request, theme_name) > 0:
                theme_name = wikiutil.escape(theme_name)
                return 'error', _("The theme '%(theme_name)s' could not be loaded!") % locals()

        # try to get the (optional) preferred language
        request.user.language = wikiutil.clean_input(form.get('language', ''))
        if request.user.language == u'': # For language-statistics
            from MoinMoin import i18n
            request.user.real_language = i18n.get_browser_language(request)
        else:
            request.user.real_language = ''

        # I want to handle all inputs from user_form_fields, but
        # don't want to handle the cases that have already been coded
        # above.
        # This is a horribly fragile kludge that's begging to break.
        # Something that might work better would be to define a
        # handler for each form field, instead of stuffing them all in
        # one long and inextensible method.  That would allow for
        # plugins to provide methods to validate their fields as well.
        already_handled = ['name', 'email',
                           'aliasname', 'edit_rows', 'editor_default',
                           'editor_ui', 'tz_offset', 'datetime_fmt',
                           'theme_name', 'language', 'real_language', 'jid']
        for field in self.cfg.user_form_fields:
            key = field[0]
            if ((key in self.cfg.user_form_disable)
                or (key in already_handled)):
                continue
            default = self.cfg.user_form_defaults[key]
            value = form.get(key, default)
            value = wikiutil.clean_input(value)
            setattr(request.user, key, value)

        # checkbox options
        for key, label in self.cfg.user_checkbox_fields:
            if key not in self.cfg.user_checkbox_disable and key not in self.cfg.user_checkbox_remove:
                value = form.get(key, "0")
                try:
                    value = int(value)
                except ValueError:
                    # value we got is crap, do not setattr this value, just pass
                    pass
                else:
                    setattr(request.user, key, value)

        # quicklinks for navibar
        request.user.quicklinks = self._decode_pagelist('quicklinks')

        # save data
        request.user.save()
        if request.user.disabled:
            # set valid to false so the current request won't
            # show the user as logged-in any more
            request.user.valid = False

        result = _("User preferences saved!")
        return result
Example #35
0
 def validUser(self, user):
     return getUserId(self.request, user) != None
Example #36
0
    def _save_user_prefs(self):
        _ = self._
        form = self.request.form
        request = self.request

        if request.request_method != 'POST':
            return

        if not 'name' in request.user.auth_attribs:
            # Require non-empty name
            new_name = form.get('name', [request.user.name])[0]

            # Don't allow changing the name to an invalid one
            if not user.isValidName(request, new_name):
                return 'error', _("""Invalid user name {{{'%s'}}}.
Name may contain any Unicode alpha numeric character, with optional one
space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(new_name)

            # Is this an existing user trying to change information or a new user?
            # Name required to be unique. Check if name belong to another user.
            existing_id = user.getUserId(request, new_name)
            if existing_id is not None and existing_id != request.user.id:
                return 'error', _("This user name already belongs to somebody else.")

            if not new_name:
                return 'error', _("Empty user name. Please enter a user name.")

            # done sanity checking the name, set it
            request.user.name = new_name


        if not 'email' in request.user.auth_attribs:
            # try to get the email
            new_email = wikiutil.clean_input(form.get('email', [request.user.email])[0])
            new_email = new_email.strip()

            # Require email
            if not new_email and 'email' not in request.cfg.user_form_remove:
                return 'error', _("Please provide your email address. If you lose your"
                                  " login information, you can get it by email.")

            # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py
            if new_email and request.cfg.user_email_unique:
                other = user.get_by_email_address(request, new_email)
                if other is not None and other.id != request.user.id:
                    return 'error', _("This email already belongs to somebody else.")

            # done checking the email, set it
            request.user.email = new_email


        if not 'jid' in request.user.auth_attribs:
            # try to get the jid
            new_jid = wikiutil.clean_input(form.get('jid', [''])[0]).strip()

            jid_changed = request.user.jid != new_jid
            previous_jid = request.user.jid

            if new_jid and request.cfg.user_jid_unique:
                other = user.get_by_jabber_id(request, new_jid)
                if other is not None and other.id != request.user.id:
                    return 'error', _("This jabber id already belongs to somebody else.")

            if jid_changed:
                set_event = events.JabberIDSetEvent(request, new_jid)
                unset_event = events.JabberIDUnsetEvent(request, previous_jid)
                events.send_event(unset_event)
                events.send_event(set_event)

            # done checking the JID, set it
            request.user.jid = new_jid


        if not 'aliasname' in request.user.auth_attribs:
            # aliasname
            request.user.aliasname = wikiutil.clean_input(form.get('aliasname', [''])[0])

        # editor size
        request.user.edit_rows = util.web.getIntegerInput(request, 'edit_rows',
                                                          request.user.edit_rows, 10, 60)

        # try to get the editor
        request.user.editor_default = form.get('editor_default', [self.cfg.editor_default])[0]
        request.user.editor_ui = form.get('editor_ui', [self.cfg.editor_ui])[0]

        # time zone
        request.user.tz_offset = util.web.getIntegerInput(request, 'tz_offset',
                                                          request.user.tz_offset, -84600, 84600)

        # datetime format
        try:
            dt_d_combined = Settings._date_formats.get(form['datetime_fmt'][0], '')
            request.user.datetime_fmt, request.user.date_fmt = dt_d_combined.split(' & ')
        except (KeyError, ValueError):
            request.user.datetime_fmt = '' # default
            request.user.date_fmt = '' # default

        # try to get the (optional) theme
        theme_name = form.get('theme_name', [self.cfg.theme_default])[0]
        if theme_name != request.user.theme_name:
            # if the theme has changed, load the new theme
            # so the user has a direct feedback
            # WARNING: this should be refactored (i.e. theme load
            # after userform handling), cause currently the
            # already loaded theme is just replaced (works cause
            # nothing has been emitted yet)
            request.user.theme_name = theme_name
            if request.loadTheme(theme_name) > 0:
                theme_name = wikiutil.escape(theme_name)
                return 'error', _("The theme '%(theme_name)s' could not be loaded!") % locals()

        # try to get the (optional) preferred language
        request.user.language = form.get('language', [''])[0]
        if request.user.language == u'': # For language-statistics
            from MoinMoin import i18n
            request.user.real_language = i18n.get_browser_language(request)
        else:
            request.user.real_language = ''

        # I want to handle all inputs from user_form_fields, but
        # don't want to handle the cases that have already been coded
        # above.
        # This is a horribly fragile kludge that's begging to break.
        # Something that might work better would be to define a
        # handler for each form field, instead of stuffing them all in
        # one long and inextensible method.  That would allow for
        # plugins to provide methods to validate their fields as well.
        already_handled = ['name', 'email',
                           'aliasname', 'edit_rows', 'editor_default',
                           'editor_ui', 'tz_offset', 'datetime_fmt',
                           'theme_name', 'language', 'real_language', 'jid']
        for field in self.cfg.user_form_fields:
            key = field[0]
            if ((key in self.cfg.user_form_disable)
                or (key in already_handled)):
                continue
            default = self.cfg.user_form_defaults[key]
            value = form.get(key, [default])[0]
            setattr(request.user, key, value)

        # checkbox options
        for key, label in self.cfg.user_checkbox_fields:
            if key not in self.cfg.user_checkbox_disable and key not in self.cfg.user_checkbox_remove:
                value = form.get(key, ["0"])[0]
                try:
                    value = int(value)
                except ValueError:
                    pass
                else:
                    setattr(request.user, key, value)

        # quicklinks for navibar
        request.user.quicklinks = self._decode_pagelist('quicklinks')

        # save data
        request.user.save()
        if request.user.disabled:
            # set valid to false so the current request won't
            # show the user as logged-in any more
            request.user.valid = False

        result = _("User preferences saved!")
        if _debug:
            result = result + util.dumpFormData(form)
        return result
Example #37
0
def execute(pagename, request):
    found = False
    for auth in request.cfg.auth:
        if isinstance(auth, MoinAuth):
            found = True
            break

    if not found:
        # we will not have linked, so forbid access
        request.makeForbidden(403, 'No MoinAuth in auth list')
        return

    page = Page(request, pagename)
    _ = request.getText
    form = request.values # link in mail -> GET request

    if not request.cfg.mail_enabled:
        request.theme.add_msg(_("""This wiki is not enabled for mail processing.
Contact the owner of the wiki, who can enable email."""), 'warning')
        page.send_page()
        return

    submitted = form.get('account_sendmail', '')
    token = form.get('token', '')
    newpass = form.get('password', '')
    name = form.get('name', '')

    if token and name and newpass:
        newpass2 = form.get('password_repeat', '')
        msg = _("Passwords don't match!")
        msg_type = 'error'
        if newpass == newpass2:
            pw_checker = request.cfg.password_checker
            pw_error = None
            if pw_checker:
                pw_error = pw_checker(request, name, newpass)
                if pw_error:
                    msg = _("Password not acceptable: %s") % wikiutil.escape(pw_error)
            if not pw_error:
                u = user.User(request, user.getUserId(request, name))
                if u and u.valid and u.apply_recovery_token(token, newpass):
                    msg = _("Your password has been changed, you can log in now.")
                    msg_type = 'info'
                else:
                    msg = _('Your token is invalid!')
        if msg:
            request.theme.add_msg(msg, msg_type)
        if msg_type != 'error':
            page.send_page()
            return

    if token and name:
        request.theme.send_title(_("Password reset"), pagename=pagename)

        request.write(request.formatter.startContent("content"))

        request.write(_("""
== Password reset ==
Enter a new password below.""", wiki=True))
        request.write(_create_token_form(request, name=name, token=token))

        request.write(request.formatter.endContent())

        request.theme.send_footer(pagename)
        request.theme.send_closing_html()
    elif submitted: # user pressed create button
        if request.method != 'POST':
            return
        msg = _do_recover(request)
        request.theme.add_msg(msg, "dialog")
        page.send_page()
    else: # show create form
        request.theme.send_title(_("Lost password"), pagename=pagename)

        request.write(request.formatter.startContent("content"))

        request.write(_("""
== Recovering a lost password ==
If you have forgotten your password, provide your email address or
username and click on '''Mail me my account data'''.
You will receive an email containing a recovery token that can be
used to change your password. The email will also contain further
instructions.""", wiki=True))

        request.write(_create_form(request))

        request.write(request.formatter.rule())

        request.write(_("""
=== Password reset ===
If you already have received the email with the recovery token, enter your
username, the recovery token and a new password (twice) below.""", wiki=True))

        request.write(_create_token_form(request))

        request.write(request.formatter.endContent())

        request.theme.send_footer(pagename)
        request.theme.send_closing_html()
Example #38
0
        elif opt == '--email':
            email = val

    if not password:
        d = Dialog('TurnKey Linux - First boot configuration')
        password = d.get_password(
            "MoinMoin Password",
            "Enter new password for the MoinMoin 'admin' account.")

    if not email:
        if 'd' not in locals():
            d = Dialog('TurnKey Linux - First boot configuration')

        email = d.get_email(
            "MoinMoin Email",
            "Enter email address for the MoinMoin 'admin' account.",
            "*****@*****.**")

    sys.path.append("/etc/moin")
    request = ScriptContext()

    userid = user.getUserId(request, 'admin')
    u = user.User(request, userid)
    u.email = email
    u.enc_password = user.encodePassword(password)
    u.save()

if __name__ == "__main__":
    main()

Example #39
0
def execute(pagename, request):
    """                                                                         
    Handle action=IntraFarmCopy
    """

    if not request.user.may.read(pagename):
        Page(request, pagename).send_page()
        return

    # Which local farm wiki - assume team for now
    to_wiki_url = COPY_TO_WIKI_URL
    # New page name
    to_wiki_pagename = '%s%s' % (COPY_TO_PREFIX, pagename)

    # create page at local wiki if it doesn't exist
    to_request = ScriptContext(to_wiki_url)
    # login this user remotely
    to_uid = user.getUserId(to_request, request.user.name)
    to_user = user.User(to_request,
                        id=to_uid,
                        name=request.user.name,
                        password=request.user.password,
                        auth_method="moin")
    to_request.user = to_user

    try:
        page = Page(to_request, to_wiki_pagename)
    except:
        return action_error(u'Error accessing destination page')
    if not page.exists():
        pe = PageEditor(to_request, to_wiki_pagename)
        # make initial revision pointer to original
        try:
            pe.saveText(
                u'[[%s:%s]]' % (request.cfg.interwikiname, pagename),
                0,
                comment="Automated IntraFarmCopy pointing to original page")
        except pe.Unchanged:
            return action_error(u'Could not save initial page')
        except pe.AccessDenied:
            return action_error(u'Could not acquire credentials')
        # make next revision content of this page
        try:
            pe.saveText(
                Page(request, pagename).get_raw_body(),
                0,
                comment=
                "Automated IntraFarmCopy importing contents from original page at [[%s:%s]]"
                % (request.cfg.interwikiname, pagename))
        except pe.Unchanged:
            return action_error(u'Could not save destination page text')

# send attachments over
        attachments = AttachFile._get_files(request, pagename)
        for attachname in attachments:
            filename = AttachFile.getFilename(request, pagename, attachname)
            if not os.path.isfile(filename):
                continue
            to_filename = AttachFile.getFilename(to_request, to_wiki_pagename,
                                                 attachname)
            shutil.copyfile(filename, to_filename)
            AttachFile._addLogEntry(to_request, 'ATTNEW', to_wiki_pagename,
                                    attachname)
        # redirect user to view new page in other wiki
        request.http_redirect('%s%s' % (to_wiki_url, to_wiki_pagename))
        return
    else:
        return action_error(u'Destination page already exists!')
Example #40
0
def execute(pagename, request):
    found = False
    for auth in request.cfg.auth:
        if isinstance(auth, MoinAuth):
            found = True
            break

    if not found:
        # we will not have linked, so forbid access
        request.makeForbidden(403, 'No MoinAuth in auth list')
        return

    page = Page(request, pagename)
    _ = request.getText
    form = request.values  # link in mail -> GET request

    if not request.cfg.mail_enabled:
        request.theme.add_msg(
            _("""This wiki is not enabled for mail processing.
Contact the owner of the wiki, who can enable email."""), 'warning')
        page.send_page()
        return

    submitted = form.get('account_sendmail', '')
    token = form.get('token', '')
    newpass = form.get('password', '')
    name = form.get('name', '')

    if token and name and newpass:
        newpass2 = form.get('password_repeat', '')
        msg = _("Passwords don't match!")
        msg_type = 'error'
        if newpass == newpass2:
            pw_checker = request.cfg.password_checker
            pw_error = None
            if pw_checker:
                pw_error = pw_checker(request, name, newpass)
                if pw_error:
                    msg = _("Password not acceptable: %s") % wikiutil.escape(
                        pw_error)
            if not pw_error:
                u = user.User(request, user.getUserId(request, name))
                if u and u.valid and u.apply_recovery_token(token, newpass):
                    msg = _(
                        "Your password has been changed, you can log in now.")
                    msg_type = 'info'
                else:
                    msg = _('Your token is invalid!')
        if msg:
            request.theme.add_msg(msg, msg_type)
        if msg_type != 'error':
            page.send_page()
            return

    if token and name:
        request.theme.send_title(_("Password reset"), pagename=pagename)

        request.write(request.formatter.startContent("content"))

        request.write(
            _("""
== Password reset ==
Enter a new password below.""",
              wiki=True))
        request.write(_create_token_form(request, name=name, token=token))

        request.write(request.formatter.endContent())

        request.theme.send_footer(pagename)
        request.theme.send_closing_html()
    elif submitted:  # user pressed create button
        if request.method != 'POST':
            return
        msg = _do_recover(request)
        request.theme.add_msg(msg, "dialog")
        page.send_page()
    else:  # show create form
        request.theme.send_title(_("Lost password"), pagename=pagename)

        request.write(request.formatter.startContent("content"))

        request.write(
            _("""
== Recovering a lost password ==
If you have forgotten your password, provide your email address or
username and click on '''Mail me my account data'''.
You will receive an email containing a recovery token that can be
used to change your password. The email will also contain further
instructions.""",
              wiki=True))

        request.write(_create_form(request))

        request.write(request.formatter.rule())

        request.write(
            _("""
=== Password reset ===
If you already have received the email with the recovery token, enter your
username, the recovery token and a new password (twice) below.""",
              wiki=True))

        request.write(_create_token_form(request))

        request.write(request.formatter.endContent())

        request.theme.send_footer(pagename)
        request.theme.send_closing_html()