Пример #1
0
 def _from_wiki_msg(self):
     """
     Print a message that says what wiki we're from
     and what our base wiki is.
     """
     wiki_name = self.from_wiki
     base_wiki_sitename = farm.getBaseWikiFullName(self.request)
     d = {'wiki_name':farm.link_to_wiki(wiki_name, self.request.formatter),
          'base_wiki_name':farm.link_to_wiki(
                                farm.getBaseWikiName(),
                                self.request.formatter),
           'base_wiki_sitename_link':farm.link_to_wiki(
                                         farm.getBaseWikiName(),
                                         self.request.formatter,
                                         text=base_wiki_sitename,
                                         no_icon=True),
           'base_wiki_sitename': base_wiki_sitename,
         }
     msg = config.wiki_farm_from_wiki_msg % d
     return msg
Пример #2
0
    def handleData(self, new_user=None):
        from Sycamore.Page import MAX_PAGENAME_LENGTH as MAX_USERNAME_LENGTH
        _ = self._
        form = self.request.form
        msg = ''
    
        isdisabled = False
        if form.get('disabled', [0])[0] == '1':
                isdisabled = True

        self.from_wiki = None
        if self.request.form.has_key('from_wiki'):
          self.from_wiki = self.request.form['from_wiki'][0].lower().strip()
          if not wikiutil.isInFarm(self.from_wiki, self.request):
            self.from_wiki = None

        new_user = int(form.get('new_user', [0])[0])
        # wiki farm authentication

        # we want them to be able to sign back in right after they
        # click the 'logout' GET link, hence this test
        is_form_logout = (form.has_key('qs') and 
                          urllib.unquote(form['qs'][0]) == 
                            'action=userform&logout=Logout')

        if (self.request.form.has_key('badlogin') and
            self.request.form['badlogin'][0]):
            _create_nologin_cookie(self.request)
            if config.wiki_farm:
                wiki_base_url = farm.getBaseFarmURL(self.request)
            else:
                wiki_base_url = '%s/' % self.request.getScriptname()
    
            return_string = ('Unknown username or wrong password.<br/><br/>'
                             'New user?  <a href="%s%s?new_user=1">Click here '
                             'to create an account!</a><br/><br/>'
                             'Forgot your password?  We\'ll email it to you.'
                             '<form action="%s" method="POST">'
                             '<input type="hidden" name="action" '
                                     'value="userform">'
                             'Email address: <input class="formfields" '
                                                    'type="text" name="email">'
                             '&nbsp;<input type="submit" class="formbutton" '
                                           'name="login_sendmail" '
                                           'value="Mail me my account data">'
                             '</form>' % (
                             wiki_base_url,
                             wikiutil.quoteWikiname(
                                config.page_user_preferences),
                             wiki_base_url))
            return return_string


        if (form.has_key('login_check') and form['login_check'][0] and
            form.has_key('backto_wiki') and form.has_key('backto_page')):
            backto_wiki = form['backto_wiki'][0]
            backto_page = form['backto_page'][0].encode(config.charset)
            if form.has_key('qs') and not is_form_logout:
                q_query_string = form['qs'][0]
            else:
                q_query_string = ''

            if self.request.user.valid:
                secret, stored_expire_time, session = \
                    self.request.user.cookie_dough
                if q_query_string:
                    url = ('%s?action=userform&backto_page=%s&qs=%s'
                           '&secret=%s&expire_time=%s&uid=%s&session=%s' % (
                            backto_page, urllib.quote(backto_page),
                            urllib.quote(q_query_string), urllib.quote(secret),
                            stored_expire_time, self.request.user.id,
                            urllib.quote(session)))
                else:
                     url = ('%s?action=userform&backto_page=%s&secret=%s'
                            '&expire_time=%s&uid=%s&session=%s' % (
                            backto_page, urllib.quote(backto_page),
                            urllib.quote(secret), stored_expire_time,
                            self.request.user.id, urllib.quote(session)))
            else:
                if q_query_string:
                    url = ('%s?action=userform&backto_page=%s&not_logged_in=1'
                           '&qs=%s' % (backto_page, urllib.quote(backto_page),
                                       urllib.quote(q_query_string)))
                else:
                     url = ('%s?action=userform&backto_page=%s&not_logged_in=1'
                            % (backto_page, urllib.quote(backto_page)))

            self.request.http_redirect(url) 
            return 

        # bounce-back wiki farm authentication
        if form.has_key('not_logged_in') and form.has_key('backto_page'):
            backto = urllib.unquote(form['backto_page'][0].encode(
                config.charset))
            if form.has_key('qs') and not is_form_logout:
                query_string = '?%s' % (urllib.unquote(form['qs'][0]
                                         ).encode(config.charset))
            else:
                query_string = ''
            url = '%s%s' % (backto, query_string)
            _create_nologin_cookie(self.request)
            self.request.http_redirect(url)
            return
        # bounce-back wiki farm authentication
        elif (form.has_key('uid') and form.has_key('secret') and
              form.has_key('session') and form.has_key('expire_time')):
            uid = form['uid'][0]
            secret = urllib.unquote(form['secret'][0])
            session = form['session'][0]
            expire_time = float(form['expire_time'][0])
            if form.has_key('backto_page'):
                backto_page = form['backto_page'][0]
            else:
                backto_page = '/' 
            if form.has_key('qs') and not is_form_logout:
                query_string = '?%s' % urllib.unquote(form['qs'][0])
            else:
                query_string = ''
            url = '%s%s' % (backto_page, query_string)
    
            self.request.http_redirect(url)
            self.request.user.sendCookie(self.request, expire=expire_time,
                                         sessionid=session, secret=secret,
                                         id=uid) 
            self.request.user.clearNologinCookie(self.request)
            return 

        if form.has_key('logout') or isdisabled:
            msg = ''
            if isdisabled:
                if not self.request.isPOST():
                    return "Use the interactive interface to change settings!"
                # disable the account
                self.request.user.disabled = 1
                # save user's profile
                self.request.user.save()
                msg = '<p>%s</p>' % _("Your account has been disabled.")

            # clear the cookie in the browser and locally
            try:
                cookie = Cookie.SimpleCookie(self.request.saved_cookie)
            except Cookie.CookieError:
                # ignore invalid cookies
                cookie = None
            else:
                if config.wiki_farm:
                    cookie_id = wikiutil.quoteCookiename(
                        config.wiki_base_domain + ',ID')
                else:
                    cookie_id = wikiutil.quoteCookiename(
                        config.sitename + ',ID')

                if cookie.has_key(cookie_id):
                    self.removeSession(cookie[cookie_id].value)
                    cookie_dir = config.web_dir
                    if not cookie_dir: cookie_dir = '/'
                    domain = wikiutil.getCookieDomain(self.request)
                    expirestr = time.strftime("%A, %d-%b-%Y %H:%M:%S GMT",
                                              time.gmtime(0))
                    self.request.setHttpHeader(('Set-Cookie',
                        ('%s="%s"; domain=%s; path=%s; '
                         'expires=%s' % (
                         (cookie_id, cookie[cookie_id].value,
                          domain, cookie_dir, expirestr)))))

            self.request.saved_cookie = ''
            self.request.auth_username = ''
            self.request.user = user.User(self.request)
            return msg + _("Cookie deleted. You are now logged out.")
    
        if form.has_key('login_sendmail'):
            if not self.request.isPOST():
                return "Use the interactive interface to change settings!"
            if not config.mail_smarthost:
                return _('This wiki is not enabled for mail processing. '
                        'Contact the owner of the wiki, who can either enable '
                        'email, or remove the "Subscribe" icon.')
            try:
                email = form['email'][0]
            except KeyError:
                return _("Please provide a valid email address!")
    
            text = ''
            uid = user.getUserIdByEmail(email, self.request)
            if uid:
                theuser = user.User(self.request, uid)
                if theuser.valid:
                    code = self.createCode(theuser.id)
                    sitename = farm.getBaseWikiFullName(self.request)
                    if config.wiki_farm:
                        url = farm.getBaseFarmURL(self.request)
                    else:
                        url = '%s/' % self.request.getBaseURL()
                    text = ("Go here to automatically log into %s: "
                            "%s%s?action=userform&uid=%s&code=%s\n"
                            "Once you're logged in, you should change your "
                            "password in your settings "
                            "(you forgot your password, right?).\n\n"
                            "(The link in this email is good for "
                            "one use only.)" % (
                            sitename, url,
                            wikiutil.quoteWikiname(
                                config.page_user_preferences),
                            theuser.id, code))

            if not text:
                return _("Found no account matching the given email address "
                         "'%(email)s'!") % {'email': email}


            mailok, msg = util.mail.sendmail(self.request, [email], 
                'Your wiki account data', text, mail_from=config.mail_from)
            return wikiutil.escape(msg)

        if form.has_key('login') or form.has_key('uid'):
            uid = None

            if form.has_key('code') and form.has_key('uid'):
               given_uid = form['uid'][0].strip()
               given_code = form['code'][0].strip()
        
               given_code
               if self.isValidCode(given_uid, given_code):
                  uid = given_uid

            if uid:
                # we were given account information so let's
                # create an account -> log them in
                theuser = user.User(self.request, id=uid)
                msg = _("You are now logged in!  "
                        "Please change your password below!")
                # send the cookie
                theuser.sendCookie(self.request)
                self.request.user = theuser
                return msg
            else:
                # we weren't given information, so let's see
                # if they gave us a login/password

                # try to get the user name
                try:
                    name = form['username'][0].replace('\t', ' ').strip()
                except KeyError:
                    name = ''

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

                # load the user data and check for validness
                if name:
                    theuser = user.User(self.request, name=name,
                                        password=password, is_login=True)
                else:
                    theuser = user.User(self.request, id=uid, name=name,
                                        password=password, is_login=True)

                if config.wiki_farm:
                    wiki_base_url = farm.getBaseFarmURL(self.request)
                else:
                    wiki_base_url = '%s/' % self.request.getScriptname()

                if not theuser.valid:
                    if (not self.request.form.has_key('backto_wiki') or not
                        self.request.form['backto_wiki'][0]):
                        return_string = ('Unknown username or wrong password.'
                                         '<br/><br/>New user?  '
                                         '<a href="%s%s?new_user=1">'
                                         'Click here to create an account!</a>'
                                         '<br/><br/>Forgot your password?  '
                                         'We\'ll email it to you.'
                                         '<form action="%s" method="POST">'
                                         '<input type="hidden" name="action" '
                                                 'value="userform">'
                                         'Email address: '
                                         '<input class="formfields" '
                                                 'type="text" name="email">'
                                         '&nbsp;'
                                         '<input type="submit" '
                                                 'class="formbutton" '
                                                 'name="login_sendmail" '
                                                 'value="Mail me my account '
                                                         'data">'
                                         '</form>' % (
                                         wiki_base_url,
                                         wikiutil.quoteWikiname(
                                            config.page_user_preferences),
                                         wiki_base_url))

                        return return_string
                    else:
                        self.request.http_redirect(
                            urllib.unquote(
                                self.request.form['backto_page'][0].encode(
                                    config.charset)) +
                            '?action=userform&badlogin=1')
                        return

            # send the cookie
            theuser.sendCookie(self.request)
            self.request.user = theuser
            send_back_home(self.request, msg="You are now logged in!")
        else:
            if not self.request.isPOST():
                return """Use the interactive interface to change settings!"""
            # save user's profile, first get user instance
            theuser = user.User(self.request)
    
            # try to get the name
            # if name is empty or missing, return an error msg
            if (form.has_key('username') and
                form['username'][0].replace('\t', '').strip()):
                theuser.propercased_name = \
                    form['username'][0].replace('\t', ' ').strip()
                theuser.name = theuser.propercased_name.lower()
            elif form.has_key('username'):
                raise BadData, (_("Please enter a user name!"), new_user)
    
            if (self.request.user.name and
                (self.request.user.name != theuser.name)):
              # they are still logged on and are trying to make a new account
              raise BadData, (_("Please log out before creating an account."),
                              new_user)
            if user.getUserId(theuser.name, self.request):
                if theuser.name != self.request.user.name:
                    raise BadData, (_("User name already exists!"), new_user)
                else:
                    new_user = False

            if form.has_key('save') and form['save'][0] == 'Change password':
                # change password setting 

                # 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:
                    raise BadData, (_("Passwords don't match!"), new_user)
                if not password and new_user:
                    raise BadData, (_("Please specify a password!"), new_user)
                if password:
                    theuser.enc_password = user.generate_hash(password)

                self._clear_all_sessions_except_current()

                msg = _("Password changed!")
            else:
                # process general settings

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

                if theuser.email:
                    email_user_id = user.getUserIdByEmail(theuser.email,
                                                          self.request)
                else:
                    email_user_id = None
                if not theuser.email or not re.match(".+@.+\..{2,}",
                                                     theuser.email):
                    raise BadData, (_("Please provide your email address - "
                                      "without that you could not "
                                      "get your login data via email just in "
                                      "case you lose it."), new_user)
                elif email_user_id and email_user_id != theuser.id:
                    raise BadData, (_("Somebody else has already registered "
                                      "with the email address \"%s\", please "
                                      "pick something else." % theuser.email),
                                    new_user)
        
                # editor size
                theuser.edit_rows = util.web.getIntegerInput(self.request,
                    'edit_rows', theuser.edit_rows, 10, 60)
                theuser.edit_cols = util.web.getIntegerInput(self.request,
                    'edit_cols', theuser.edit_cols, 30, 100)
        
                # time zone
                tz = form.get('tz', theuser.tz)[0]
                if tz not in pytz.common_timezones:
                    tz = theuser.tz
                theuser.tz = tz
        
                wiki_for_userpage = form.get('wiki_for_userpage',
                                             [''])[0].lower()
                if (wiki_for_userpage and not
                    wikiutil.isInFarm(wiki_for_userpage, self.request)):
                    raise BadData, (_('"%s" is not the name of a wiki.' % (
                                      wiki_for_userpage)), new_user)
                if wiki_for_userpage != theuser.wiki_for_userpage:
                    # they have changed the wiki! time to do
                    # something differently
                    msg = _("<p>User preferences saved!</p>"
                            "<p><strong>Note:</strong> It may take a bit for "
                            "all links to your name to point to the "
                            "new wiki.</p>")
                    theuser.wiki_for_userpage = wiki_for_userpage

                # 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
                keys = []
                for key in user_checkbox_fields:
                    value = form.get(key, [0])[0]
                    try:
                        value = int(value)
                    except ValueError:
                        pass
                    setattr(theuser, key, value)
        
            if new_user:
                # strip spaces, we don't allow them anyway
                theuser.propercased_name = theuser.propercased_name.strip() 
                theuser.name = theuser.propercased_name.lower()
                if not theuser.name.strip():
                    raise BadData, (_("Please provide a user name!"), new_user)
                elif theuser.propercased_name.find(' ') != -1:
                    raise BadData, (_("Invalid username: spaces are not "
                                      "allowed in user names"), new_user)
                elif re.search('[%s]' % re.escape(USER_NOT_ALLOWED_CHARS),
                               theuser.propercased_name):
                    raise BadData, (_("Invalid username: the characters "
                                      "%s are not allowed in usernames." % (
                                      wikiutil.escape(
                                        USER_NOT_ALLOWED_CHARS))),
                                    new_user)
                # messes up subpages. 
                # '/' isn't allowed, so we just disallow this and we're cool.
                elif theuser.name == '..' or theuser.name == '.': 
                    raise BadData, (_("Invalid username: okay, seriously, "
                                      "that's a pretty lame name.  "
                                      "Pick something better!"), new_user)
                elif len(theuser.propercased_name) > MAX_USERNAME_LENGTH:
                    raise BadData, (_("Invalid username: a username can be "
                                      "at most %s characters long." % (
                                      MAX_USERNAME_LEGNTH)), new_user)
                elif (not theuser.email or not
                      re.match(".+@.+\..{2,}", theuser.email)):
                    raise BadData, (_("Please provide your email address - "
                                      "without that you could not get your " 
                                      "login data via email just in case you "
                                      "lose it."), new_user)
                name_exists = user.getUserId(theuser.name, self.request)
                if name_exists:
                    raise BadData, (_("This user name already belongs to "
                                      "somebody else."), new_user)
                email_exists = user.getUserIdByEmail(theuser.email,
                                                     self.request)
                if email_exists:
                    raise BadData, (_("This email already belongs to somebody "
                                      "else."), new_user)

                # 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:
                    raise BadData, (_("Passwords don't match!"), new_user)
                if not password and new_user:
                    raise BadData, (_("Please specify a password!"), new_user)
                if password:
                    theuser.enc_password = user.generate_hash(password)

                theuser.anonymous = False


            # save data and send cookie
            theuser.save(new_user=new_user)
            theuser.sendCookie(self.request)
            self.request.user = theuser
    

            from Sycamore.formatter.text_html import Formatter
            formatter = Formatter(self.request)

            if not new_user:
              if not msg:
                msg = _("User preferences saved!")
              if self.from_wiki:
                go_back_to_wiki = farm.link_to_wiki(self.from_wiki, formatter)
                msg = ('%s<br/><br/>Wanna go '
                       'back to %s?' % (msg, go_back_to_wiki))
            else:
              msg = _("Account created!  You are now logged in.")
              self.request.user.valid = 1
              if (self.from_wiki and self.from_wiki.lower() !=
                                     farm.getBaseWikiName()):
                go_back_to_wiki = farm.link_to_wiki(self.from_wiki, formatter)
                msg = ('%s<br/><br/>Head back over to %s and your new account '
                      'should work there!' % (msg, go_back_to_wiki))
            if _debug:
                msg = msg + util.dumpFormData(form)
            return msg