Example #1
0
    def testAscii(self):
        """user: encode ascii password"""
        # u'MoinMoin' and 'MoinMoin' should be encoded to same result
        expected = "{SSHA}xkDIIx1I7A4gC98Vt/+UelIkTDYxMjM0NQ=="

        result = user.encodePassword("MoinMoin", salt='12345')
        assert result == expected
        result = user.encodePassword(u"MoinMoin", salt='12345')
        assert result == expected
Example #2
0
    def testAscii(self):
        """user: encode ascii password"""
        # u'MoinMoin' and 'MoinMoin' should be encoded to same result
        expected = "{SSHA256}n0JB8FCTQCpQeg0bmdgvTGwPKvxm8fVNjSRD+JGNs50xMjM0NQ=="

        result = user.encodePassword("MoinMoin", salt='12345')
        assert result == expected
        result = user.encodePassword(u"MoinMoin", salt='12345')
        assert result == expected
Example #3
0
    def testAscii(self):
        """user: encode ascii password"""
        # u'MoinMoin' and 'MoinMoin' should be encoded to same result
        expected = "{SSHA}xkDIIx1I7A4gC98Vt/+UelIkTDYxMjM0NQ=="

        result = user.encodePassword("MoinMoin", salt='12345')
        assert result == expected
        result = user.encodePassword(u"MoinMoin", salt='12345')
        assert result == expected
Example #4
0
 def testAscii(self):
     """user: encode ascii password"""
     # u'MoinMoin' and 'MoinMoin' should be encoded to same result
     expected = "{SHA}X+lk6KR7JuJEH43YnmettCwICdU="
     
     result = user.encodePassword("MoinMoin")
     self.assertEqual(result, expected,
                      'Expected "%(expected)s" but got "%(result)s"' % locals())
     result = user.encodePassword(u"MoinMoin")
     self.assertEqual(result, expected,
                      'Expected "%(expected)s" but got "%(result)s"' % locals())
 def testAscii(self):
     """user: encode ascii password"""
     # u'MoinMoin' and 'MoinMoin' should be encoded to same result
     cfg = self.request.cfg
     tests = [
         ('{PASSLIB}', '12345', "{PASSLIB}$6$rounds=1001$12345$jrPUCzPJt1yiixDbzIgSBoKED0/DlNDTHZN3lVarCtN6IM/.LoAw5pgUQH112CErU6wS8HXTZNpqb7wVjHLs/0"),
         ('{SSHA}', '12345', "{SSHA}xkDIIx1I7A4gC98Vt/+UelIkTDYxMjM0NQ=="),
     ]
     for scheme, salt, expected in tests:
         result = user.encodePassword(cfg, "MoinMoin", salt=salt, scheme=scheme)
         assert result == expected
         result = user.encodePassword(cfg, u"MoinMoin", salt=salt, scheme=scheme)
         assert result == expected
Example #6
0
    def handle_form(self):
        _ = self._
        request = self.request
        form = request.form

        if form.has_key('cancel'):
            return

        if request.request_method != 'POST':
            return

        password = form.get('password1', [''])[0]
        password2 = form.get('password2', [''])[0]

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

        pw_checker = request.cfg.password_checker
        if pw_checker:
            pw_error = pw_checker(request, request.user.name, password)
            if pw_error:
                return 'error', _("Password not acceptable: %s") % pw_error

        try:
            self.request.user.enc_password = user.encodePassword(password)
            self.request.user.save()
            return 'info', _("Your password has been changed.")
        except UnicodeError, err:
            # Should never happen
            return "Can't encode password: %s" % str(err)
Example #7
0
    def mainloop(self):
        # we don't expect non-option arguments
        if len(self.args) != 1:
            self.parser.error("no new password given")
        newpass = self.args[0]

        flags_given = self.options.uid or self.options.uname
        if not flags_given:
            self.parser.print_help()
            import sys
            sys.exit(1)

        self.init_request()
        request = self.request

        from MoinMoin import user
        if self.options.uid:
            u = user.User(request, self.options.uid)
        elif self.options.uname:
            u = user.User(request, None, self.options.uname)

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

        u.enc_password = user.encodePassword(newpass)
        u.save()
Example #8
0
    def mainloop(self):
        # we don't expect non-option arguments
        if len(self.args) != 1:
            self.parser.error("no new password given")
        newpass = self.args[0]

        flags_given = self.options.uid or self.options.uname
        if not flags_given:
            self.parser.print_help()
            import sys
            sys.exit(1)

        self.init_request()
        request = self.request

        from MoinMoin import user
        if self.options.uid:
            u = user.User(request, self.options.uid)
        elif self.options.uname:
            u = user.User(request, None, self.options.uname)

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

        u.enc_password = user.encodePassword(newpass)
        u.save()
Example #9
0
 def createUser(self, name, password, charset='utf-8'):
     """ helper to create test user 
     
     charset is used to create user with pre 1.3 password hash
     """
     global request
     
     # Hack request form to contain the password
     request.form['password'] = [password]  
     
     # Create user
     self.user = user.User(request)
     self.user.name = name
     self.user.enc_password = user.encodePassword(password, charset=charset)
     
     # Validate that we are not modifying existing user data file!
     if self.user.exists():
         self.user = None
         raise TestsSkiped("Test user exists, will not override existing"
                           " user data file!")
     
     # Save test user
     self.user.save()
     
     # Validate user creation
     if not self.user.exists():
         self.user = None
         raise TestsSkiped("Can't create test user")
Example #10
0
def deletecomment(macro, delkey, delpasswd):
    # Deletes a comment with given index and password
    
    request = Globs.macro.request
    formatter = Globs.macro.formatter
    datapagename = Globs.datapagename
    _ = request.getText
    
    if Params.encryptpass:
        from MoinMoin import user
        delpasswd = user.encodePassword(delpasswd)
    
    pg = PageEditor( request, datapagename )
    pagetext = pg.get_raw_body()
    
    regex = ur"""
(?P<comblock>
    ^[\{]{3}\n
    ^(?P<icon>[^\n]*)\n
    ^(?P<name>[^\n]*)\n
    ^(?P<date>[^\n]*)[\n]+
    ^(?P<text>
        \s*.*?
        (?=[\}]{3})
    )[\}]{3}[\n]*
    ^[#]{2}PASSWORD[ ](?P<passwd>[^\n]*)[\n]*
    ^[#]{2}LOGINUSER[ ](?P<loginuser>[^\n]*)[\n$]*
)"""

    pattern = re.compile(regex, re.UNICODE + re.MULTILINE + re.VERBOSE + re.DOTALL)
    commentitems = pattern.findall(pagetext)
    
    for item in commentitems:
        
        if delkey == item[3].strip():
            comauthor = item[2]
            if Globs.admin or (request.user.valid and request.user.name == comauthor) or delpasswd == item[5]:
                newpagetext = pagetext.replace(item[0], '', 1)
                
                action = 'SAVE'
                comment = 'Deleted comment by "%s"' % comauthor
                trivial = 1
                pg._write_file(newpagetext, action, u'PageComment modification at %s' % Globs.curpagename)
                addLogEntry(request, 'COMDEL', Globs.curpagename, comment)
                
                msg = _('The comment is deleted.')
                
                # send notification mails
                if Params.notify:
                    msg = msg + commentNotify(comment, trivial)
                
                message(msg)
                
                return
            else:
                message(_('Sorry, wrong password.'))
                return
                
    message(_('No such comment'))
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 #12
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))
 def testUnicode(self):
     """ user: encode unicode password """
     cfg = self.request.cfg
     tests = [
         ('{PASSLIB}', '12345', "{PASSLIB}$6$rounds=1001$12345$5srFB66ZCu2JgGwPgdfb1lHRmqkjnKC/RxdsFlWn2WzoQh3btIjH6Ai1LJV9iYLDa9kLP/VQYa4DHLkRnaBw8."),
         ('{SSHA}', '12345', "{SSHA}YiwfeVWdVW9luqyVn8t2JivlzmUxMjM0NQ=="),
         ]
     for scheme, salt, expected in tests:
         result = user.encodePassword(cfg, u'סיסמה סודית בהחלט', salt=salt, scheme=scheme) # Hebrew
         assert result == expected
Example #14
0
 def testAscii(self):
     """user: encode ascii password"""
     # u'MoinMoin' and 'MoinMoin' should be encoded to same result
     cfg = self.request.cfg
     tests = [
         ('{PASSLIB}', '12345',
          "{PASSLIB}$6$rounds=1001$12345$jrPUCzPJt1yiixDbzIgSBoKED0/DlNDTHZN3lVarCtN6IM/.LoAw5pgUQH112CErU6wS8HXTZNpqb7wVjHLs/0"
          ),
         ('{SSHA}', '12345', "{SSHA}xkDIIx1I7A4gC98Vt/+UelIkTDYxMjM0NQ=="),
     ]
     for scheme, salt, expected in tests:
         result = user.encodePassword(cfg,
                                      "MoinMoin",
                                      salt=salt,
                                      scheme=scheme)
         assert result == expected
         result = user.encodePassword(cfg,
                                      u"MoinMoin",
                                      salt=salt,
                                      scheme=scheme)
         assert result == expected
Example #15
0
 def testUnicode(self):
     """ user: encode unicode password """
     cfg = self.request.cfg
     tests = [
         ('{PASSLIB}', '12345',
          "{PASSLIB}$6$rounds=1001$12345$5srFB66ZCu2JgGwPgdfb1lHRmqkjnKC/RxdsFlWn2WzoQh3btIjH6Ai1LJV9iYLDa9kLP/VQYa4DHLkRnaBw8."
          ),
         ('{SSHA}', '12345', "{SSHA}YiwfeVWdVW9luqyVn8t2JivlzmUxMjM0NQ=="),
     ]
     for scheme, salt, expected in tests:
         result = user.encodePassword(cfg,
                                      u'סיסמה סודית בהחלט',
                                      salt=salt,
                                      scheme=scheme)  # Hebrew
         assert result == expected
Example #16
0
 def testReplaceOldNonAsciiPassword(self):
     """ user: login replace old non-ascii password in pre 1.3 user file
     
     When trying to login with an old non-ascii password in the user 
     file, the password hash should be replaced with new utf-8 hash.
     """
     # Create test user
     # Use iso charset to create user with old enc_password, as if
     # the user file was migrated from pre 1.3 wiki.
     name = u'__Jürgen Herman__'
     password = name
     self.createUser(name, password, charset='iso-8859-1')
     
     # Login - this should replace the old password in the user file         
     theUser = user.User(request, name=name, password=password)
     # Login again - the password should be new unicode password
     expected = user.encodePassword(password)
     theUser = user.User(request, name=name, password=password)
     self.assertEqual(theUser.enc_password, expected, "User password was not replaced with new")
Example #17
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.'
Example #18
0
    def createUser(self, name, password, pwencoded=False):
        """ helper to create test user
        """
        # Create user
        self.user = user.User(self.request)
        self.user.name = name
        if not pwencoded:
            password = user.encodePassword(password)
        self.user.enc_password = password

        # Validate that we are not modifying existing user data file!
        if self.user.exists():
            self.user = None
            py.test.skip("Test user exists, will not override existing user data file!")

        # Save test user
        self.user.save()

        # Validate user creation
        if not self.user.exists():
            self.user = None
            py.test.skip("Can't create test user")
Example #19
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

        password = form.get('password1', '')
        password2 = form.get('password2', '')

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

        pw_checker = request.cfg.password_checker
        if pw_checker:
            pw_error = pw_checker(request, request.user.name, password)
            if pw_error:
                return 'error', _("Password not acceptable: %s") % pw_error

        try:
            self.request.user.enc_password = user.encodePassword(request.cfg, password)
            self.request.user.save()
            return 'info', _("Your password has been changed.")
        except UnicodeError, err:
            # Should never happen
            return "Can't encode password: %s" % str(err)
Example #20
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

        password = form.get("password1", "")
        password2 = form.get("password2", "")

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

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

        try:
            self.request.user.enc_password = user.encodePassword(password)
            self.request.user.save()
            return "info", _("Your password has been changed.")
        except UnicodeError, err:
            # Should never happen
            return "Can't encode password: %s" % str(err)
Example #21
0
    def createUser(self, name, password, pwencoded=False, email=None):
        """ helper to create test user
        """
        # Create user
        self.user = user.User(self.request)
        self.user.name = name
        self.user.email = email
        if not pwencoded:
            password = user.encodePassword(self.request.cfg, password)
        self.user.enc_password = password

        # Validate that we are not modifying existing user data file!
        if self.user.exists():
            self.user = None
            py.test.skip(
                "Test user exists, will not override existing user data file!")

        # Save test user
        self.user.save()

        # Validate user creation
        if not self.user.exists():
            self.user = None
            py.test.skip("Can't create test user")
Example #22
0
        return 0
    
    comtext = convertdelimeter(comtext)
    
    if request.user.valid:
        comloginuser = '******'
        comauthor = request.user.name
    else:
        comloginuser = ''
        comauthor = convertdelimeter(comauthor)
    
    orgcompasswd = compasswd
    
    if Params.encryptpass:
        from MoinMoin import user
        compasswd = user.encodePassword(compasswd)
    
    newcomment = [
        u'{{{',
        u'%s,%s' % (comicon, commarkup),
        u'%s' % comauthor,
        u'%s' % time.strftime(cfg.datetime_fmt, time.localtime(time.time())),
        u'',
        u'%s' % comtext,
        u'}}}',
        u'##PASSWORD %s' % compasswd,
        u'##LOGINUSER %s' % comloginuser,
        ]
        
    newpagetext = u'%s\n\n%s' % (pagetext, u'\n'.join(newcomment))
Example #23
0
 def testUnicode(self):
     """ user: encode unicode password """
     result = user.encodePassword(u'סיסמה סודית בהחלט',
                                  salt='12345')  # Hebrew
     expected = "{SSHA}YiwfeVWdVW9luqyVn8t2JivlzmUxMjM0NQ=="
     assert result == expected
Example #24
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 #25
0
 def testUnicode(self):
     """ user: encode unicode password """
     result = user.encodePassword(u'סיסמה סודית בהחלט') # Hebrew
     expected = "{SHA}GvvkgYzv5MoF9Ljivv2oc81FmkE="
     self.assertEqual(result, expected,
                      'Expected "%(expected)s" but got "%(result)s"' % locals())
Example #26
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 #27
0
        return 0

    comtext = convertdelimeter(comtext)

    if request.user.valid:
        comloginuser = '******'
        comauthor = request.user.name
    else:
        comloginuser = ''
        comauthor = convertdelimeter(comauthor)

    orgcompasswd = compasswd

    if Params.encryptpass:
        from MoinMoin import user
        compasswd = user.encodePassword(compasswd)

    newcomment = [
        u'{{{',
        u'%s,%s' % (comicon, commarkup),
        u'%s' % comauthor,
        u'%s' % time.time(),
        u'%s' % rating,
        u'',
        u'%s' % comtext,
        u'}}}',
        u'##PASSWORD %s' % compasswd,
        u'##LOGINUSER %s' % comloginuser,
    ]

    newpagetext = u'%s\n\n%s' % (pagetext, u'\n'.join(newcomment))
Example #28
0
def deletecomment(macro, delkey, delpasswd):
    # Deletes a comment with given index and password

    request = Globs.macro.request
    formatter = Globs.macro.formatter
    datapagename = Globs.datapagename
    _ = request.getText

    if Params.encryptpass:
        from MoinMoin import user
        delpasswd = user.encodePassword(delpasswd)

    pg = PageEditor(request, datapagename)
    pagetext = pg.get_raw_body()

    regex = ur"""
(?P<comblock>
    ^[\{]{3}\n
    ^(?P<icon>[^\n]*)\n
    ^(?P<name>[^\n]*)\n
    ^(?P<date>[^\n]*)[\n]+
    ^(?P<text>
        \s*.*?
        (?=[\}]{3})
    )[\}]{3}[\n]*
    ^[#]{2}PASSWORD[ ](?P<passwd>[^\n]*)[\n]*
    ^[#]{2}LOGINUSER[ ](?P<loginuser>[^\n]*)[\n$]*
)"""

    pattern = re.compile(regex,
                         re.UNICODE + re.MULTILINE + re.VERBOSE + re.DOTALL)
    commentitems = pattern.findall(pagetext)

    for item in commentitems:

        if delkey == item[3].strip():
            comauthor = item[2]
            if Globs.admin or (request.user.valid and request.user.name
                               == comauthor) or delpasswd == item[5]:
                newpagetext = pagetext.replace(item[0], '', 1)

                action = 'SAVE'
                comment = 'Deleted comment by "%s"' % comauthor
                trivial = 1
                pg._write_file(
                    newpagetext, action,
                    u'PageComment modification at %s' % Globs.curpagename)
                addLogEntry(request, 'COMDEL', Globs.curpagename, comment)

                msg = _('The comment is deleted.')

                # send notification mails
                if Params.notify:
                    msg = msg + commentNotify(comment, trivial)

                message(msg)

                return
            else:
                message(_('Sorry, wrong password.'))
                return

    message(_('No such comment'))
Example #29
0
 def testUnicode(self):
     """ user: encode unicode password """
     result = user.encodePassword(u'סיסמה סודית בהחלט',
                                  salt='12345')  # Hebrew
     expected = "{SSHA256}pdYvYv+4Vph259sv/HAm7zpZTv4sBKX9ITOX/m00HMsxMjM0NQ=="
     assert result == expected
Example #30
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 #31
0
 def testUnicode(self):
     """ user: encode unicode password """
     result = user.encodePassword(u'סיסמה סודית בהחלט', salt='12345') # Hebrew
     expected = "{SSHA}YiwfeVWdVW9luqyVn8t2JivlzmUxMjM0NQ=="
     assert result == expected
Example #32
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