Пример #1
0
    def post_newpost():
        title = bottle.request.forms.get("subject")
        post = bottle.request.forms.get("body")
        tags = bottle.request.forms.get("tags")

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        if title == "" or post == "":
            errors = "Post must contain a title and blog entry"
            return bottle.template("newpost_template", dict(subject=cgi.escape(title, quote=True), username=username,
                                                            body=cgi.escape(post, quote=True), tags=tags, errors=errors))

        # extract tags
        tags = cgi.escape(tags)
        tags_array = extract_tags(tags)

        # looks like a good entry, insert it escaped
        escaped_post = cgi.escape(post, quote=True)

        # substitute some <p> for the paragraph breaks
        newline = re.compile('\r?\n')
        formatted_post = newline.sub("<p>", escaped_post)

        permalink = posts.insert_entry(title, formatted_post, tags_array, username)

        # now bottle.redirect to the blog permalink
        bottle.redirect("/post/" + permalink)
Пример #2
0
    def process_login():

        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")

        print "user submitted ", username, "pass ", password

        user_record = users.validate_login(username, password)
        if user_record:
            # username is stored in the user collection in the _id key
            session_id = sessions.start_session(user_record['_id'])

            if session_id is None:
                bottle.redirect("/internal_error")

            cookie = session_id

            # Warning, if you are running into a problem whereby the cookie being set here is
            # not getting set on the redirect, you are probably using the experimental version of bottle (.12).
            # revert to .11 to solve the problem.
            bottle.response.set_cookie("session", cookie)

            bottle.redirect("/welcome")

        else:
            return bottle.template(
                "login",
                dict(username=cgi.escape(username),
                     password="",
                     login_error="Invalid Login"))
Пример #3
0
    def post_new_comment():
        name = bottle.request.forms.get("commentName")
        email = bottle.request.forms.get("commentEmail")
        body = bottle.request.forms.get("commentBody")
        permalink = bottle.request.forms.get("permalink")

        post = posts.get_post_by_permalink(permalink)
        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)

        # if post not found, redirect to post not found error
        if post is None:
            bottle.redirect("/post_not_found")
            return

        # if values not good, redirect to view with errors

        if name == "" or body == "":
            # user did not fill in enough information

            # init comment for web form
            comment = {'name': name, 'email': email, 'body': body}

            errors = "Post must contain your name and an actual comment."
            return bottle.template("entry_template", dict(post=post, username=username, errors=errors, comment=comment))

        else:

            # it all looks good, insert the comment into the blog post and redirect back to the post viewer
            posts.add_comment(permalink, name, email, body)

            bottle.redirect("/post/" + permalink)
Пример #4
0
    def process_login():

        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")

        print "user submitted ", username, "pass ", password

        user_record = users.validate_login(username, password)
        if user_record:
            # username is stored in the user collection in the _id key
            session_id = sessions.start_session(user_record['_id'])

            if session_id is None:
                bottle.redirect("/internal_error")

            cookie = session_id

            # Warning, if you are running into a problem whereby the cookie being set here is
            # not getting set on the redirect, you are probably using the experimental version of bottle (.12).
            # revert to .11 to solve the problem.
            bottle.response.set_cookie("session", cookie)

            bottle.redirect("/welcome")

        else:
            return bottle.template("login",
                                   dict(username=cgi.escape(username), password="",
                                        login_error="Invalid Login"))
Пример #5
0
    def get_newpost():

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        return bottle.template("newpost_template", dict(subject="", body="", errors="", tags="", username=username))
Пример #6
0
    def get_newpost():

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        return bottle.template(
            "newpost_template",
            dict(subject="", body="", errors="", tags="", username=username))
Пример #7
0
 def present_signup():
     return bottle.template(
         "signup",
         dict(username="",
              password="",
              password_error="",
              email="",
              username_error="",
              email_error="",
              verify_error=""))
Пример #8
0
    def present_welcome():
        # check for a cookie, if present, then extract value

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            print "welcome: can't identify user...redirecting to signup"
            bottle.redirect("/signup")

        return bottle.template("welcome", {'username': username})
Пример #9
0
    def present_welcome():
        # check for a cookie, if present, then extract value

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            print "welcome: can't identify user...redirecting to signup"
            bottle.redirect("/signup")

        return bottle.template("welcome", {'username': username})
Пример #10
0
def formhandler():
    ''' Handle form submission '''
    tm = time.perf_counter()
    if 'REMOTE_ADDR' in bottle.request.environ:
        ip = bottle.request.environ.get('REMOTE_ADDR')
    else:
        ip = None

    logger.info("==== menu handler from %s =====:\n%s" %
                (ip, bottle.request.body.read()))
    selqs = bottle.request.forms.getall('quantities')
    src = bottle.request.forms.get('source')
    tbcknm = bottle.request.forms.get('tmback')
    cursXpos = bottle.request.forms.get('cursorPos')
    jdtill = bottle.request.forms.get('jdtill')
    evtDescr = bottle.request.forms.get('evtDescr')
    evtData = bottle.request.forms.get('evtData')
    try:
        ndays = next(tb for tb, tup in tmBACKs.items() if tbcknm in tup[0])
    except StopIteration:
        ndays = 5

    jdofs = (plXMARG + plWIDTH -
             int(cursXpos)) / plWIDTH * ndays  # cursor pos giving time offset
    if jdtill:
        jdtill = float(jdtill)  # preserve actual time frame
    else:
        jdtill = julianday()
    jdcursor = jdtill - jdofs
    if evtDescr and evtDescr != 'comment':  # define event at cursor
        root = sys.modules['__main__'].__file__
        logger.info('received event descr %s at jd:%s' % (evtDescr, jdcursor))

        dbStore.setEvtDescription(jdcursor, evtDescr, root=root)
    else:  # place right side at cursor
        jdtill = jdcursor

    if abs(jdtill - julianday()) < ndays / 5.0:
        jdtill = julianday()  # adjust to now when close
    else:
        logger.info("adjusting jd %f with ofs:%f evt:%s" %
                    (jdtill, jdofs, evtDescr))
    statbar = bottle.request.forms.get('statbar')
    logger.info("statbar=%s" % statbar)

    logger.info(
        "menu response(t:%s):qtt=%s src=%s jd=%s ndys=%s cPos=%s evtData=%s" %
        (time.perf_counter() - tm, selqs, src, prettydate(jdtill), tbcknm,
         cursXpos, evtData))
    bottle.response.set_cookie(COOKIE,
                               json.dumps((src, selqs, ndays)),
                               max_age=AN1)
    return bottle.template(TPL, redraw(src, selqs, jdtill, ndays))
Пример #11
0
    def process_signup():

        email = bottle.request.forms.get("email")
        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")
        verify = bottle.request.forms.get("verify")

        # set these up in case we have an error case
        errors = {'username': cgi.escape(username), 'email': cgi.escape(email)}
        if validate_signup(username, password, verify, email, errors):

            if not users.add_user(username, password, email):
                # this was a duplicate
                errors['username_error'] = "Username already in use. Please choose another"
                return bottle.template("signup", errors)

            session_id = sessions.start_session(username)
            print session_id
            bottle.response.set_cookie("session", session_id)
            bottle.redirect("/welcome")
        else:
            print "user did not validate"
            return bottle.template("signup", errors)
Пример #12
0
def process_login():

    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")

    user = "******"
    passwrd = "mypassword"

    if username == user and password == passwrd:
        bottle.redirect("/welcome")
    else:
        print "Invalid username or password"
        return bottle.template("login", dict(username=cgi.escape(username), password="",
                                        login_error="Invalid Login"))
Пример #13
0
    def process_signup():

        email = bottle.request.forms.get("email")
        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")
        verify = bottle.request.forms.get("verify")

        # set these up in case we have an error case
        errors = {'username': cgi.escape(username), 'email': cgi.escape(email)}
        if validate_signup(username, password, verify, email, errors):

            if not users.add_user(username, password, email):
                # this was a duplicate
                errors[
                    'username_error'] = "Username already in use. Please choose another"
                return bottle.template("signup", errors)

            session_id = sessions.start_session(username)
            print session_id
            bottle.response.set_cookie("session", session_id)
            bottle.redirect("/welcome")
        else:
            print "user did not validate"
            return bottle.template("signup", errors)
Пример #14
0
def status():
    page = int(request.query.page) if request.query.page else 1
    email = get_email_from_session()
    user = users[email]
    songs = user.get_all_songs()
    num_pages = int(len(songs.keys()) / SONGS_PER_PAGE) + 1
    start_song = ((page - 1) * SONGS_PER_PAGE)
    end_song = ((page - 1) * SONGS_PER_PAGE) + SONGS_PER_PAGE
    logger.debug("displaying results for page %s, showing songs %s to %s" % (page, (page * SONGS_PER_PAGE), (page * SONGS_PER_PAGE) + SONGS_PER_PAGE))
    all_songs = sorted(songs.keys())
    page_songs = []
    for song_path in all_songs[start_song : end_song]:
        page_songs.append(Song(song_path, songs[song_path]['status'], songs[song_path]['id']))

    return template('status', session_status=get_session_data(), songs=page_songs, num_pages=num_pages, curr_page=page)
Пример #15
0
def login():
    session = get_session()
    # If we haven't checked yet (i.e. when first starting up), check for any users that we can log in
    #  and log them in automtically.  We'll pick one at random to be the starting 'active' user
    if not "tokens_checked" in session:
        logger.info("Checking for existing tokens")
        check_for_existing_tokens()
        session["tokens_checked"] = True
    # Check if we've got a user logged in already at this point.  If so, redirect to the main page
    if logged_in:
        logger.info("User %s already logged in" % get_email_from_session())
        redirect("/main")
    # If no one is logged in, present the change to log in
    logger.info("No users logged in, showing oauth screen")
    oauth_uri = oauth2_flow.step1_get_authorize_url()
    return template('login', session_status=get_session_data(), oauth_uri=oauth_uri)
Пример #16
0
def blog_home():
    
    return bottle.template('signup', dict(username="", password="",
                                    password_error="",
                                    email="", username_error="", email_error="",
                                    verify_error=""))
    
    email = bottle.request.forms.get("email")
    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")
    verify = bottle.request.forms.get("verify")

    if username is None and password is None:
        print "You need to fill the form"
    else:
        bottle.redirect('/welcome')
Пример #17
0
def process_login():

    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")

    user = "******"
    passwrd = "mypassword"

    if username == user and password == passwrd:
        bottle.redirect("/welcome")
    else:
        print "Invalid username or password"
        return bottle.template(
            "login",
            dict(username=cgi.escape(username),
                 password="",
                 login_error="Invalid Login"))
Пример #18
0
    def show_post(permalink="notfound"):

        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)
        permalink = cgi.escape(permalink)

        print "about to query on permalink = ", permalink
        post = posts.get_post_by_permalink(permalink)

        if post is None:
            bottle.redirect("/post_not_found")

        # init comment form fields for additional comment
        comment = {'name': "", 'body': "", 'email': ""}

        return bottle.template("entry_template", dict(post=post, username=username, errors="", comment=comment))
Пример #19
0
    def show_post(permalink="notfound"):

        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)
        permalink = cgi.escape(permalink)

        print "about to query on permalink = ", permalink
        post = posts.get_post_by_permalink(permalink)

        if post is None:
            bottle.redirect("/post_not_found")

        # init comment form fields for additional comment
        comment = {'name': "", 'body': "", 'email': ""}

        return bottle.template(
            "entry_template",
            dict(post=post, username=username, errors="", comment=comment))
Пример #20
0
def blog_home():

    return bottle.template(
        'signup',
        dict(username="",
             password="",
             password_error="",
             email="",
             username_error="",
             email_error="",
             verify_error=""))

    email = bottle.request.forms.get("email")
    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")
    verify = bottle.request.forms.get("verify")

    if username is None and password is None:
        print "You need to fill the form"
    else:
        bottle.redirect('/welcome')
Пример #21
0
def index(name=TITLE):
    ''' standard opening page (with settings from cookie or default) '''
    if 'REMOTE_ADDR' in bottle.request.environ:
        ip = bottle.request.environ.get('REMOTE_ADDR')
    else:
        ip = None
    tm = time.perf_counter()
    logger.info("===== index request:%s from %s=====" %
                (bottle.request.body.read(), ip))

    if bottle.request.query.title:
        bottle.redirect('/menu')

    srcs = list(dbStore.sources())
    src = srcs[0]
    quantIds = []
    cookie = bottle.request.get_cookie(COOKIE)
    if cookie:
        logger.info('using cookie :"%s"' % cookie)
        cookie = list(json.loads(cookie))
        cookie.extend([None, None, None])
        src, selqs, ndays = tuple(cookie[:3])
    else:
        selqs = typnames(dbStore.quantities(
            [src], prop=2))[:2]  # quantity typs that are in src
        ndays = 4
        bottle.response.set_cookie(COOKIE,
                                   json.dumps((src, selqs, ndays)),
                                   max_age=AN1)
    logger.info("src:%s,selqs:%s len:%d" % (src, selqs, len(selqs)))
    if len(selqs) == 0 or len(selqs) > 15:
        selqs = ['temperature']
    #page = dict(menitms=buildMenu(srcs,src,typnames(dbStore.quantities(prop=2)),selqs,ndays))
    #page = redraw(src,selqs,julianday())
    jdtill = julianday()
    page = redraw(src, selqs, jdtill, ndays)
    page.update(dict(title=name, footer=__copyright__)
                )  #jdtill=julianday(),ndays=ndays,grQuantIds=quantIds))
    logger.debug("index page:(t:%s)\n%s\n" % (time.perf_counter() - tm, page))
    return bottle.template(TPL, page)
Пример #22
0
    def post_new_comment():
        name = bottle.request.forms.get("commentName")
        email = bottle.request.forms.get("commentEmail")
        body = bottle.request.forms.get("commentBody")
        permalink = bottle.request.forms.get("permalink")

        post = posts.get_post_by_permalink(permalink)
        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)

        # if post not found, redirect to post not found error
        if post is None:
            bottle.redirect("/post_not_found")
            return

        # if values not good, redirect to view with errors

        if name == "" or body == "":
            # user did not fill in enough information

            # init comment for web form
            comment = {'name': name, 'email': email, 'body': body}

            errors = "Post must contain your name and an actual comment."
            return bottle.template(
                "entry_template",
                dict(post=post,
                     username=username,
                     errors=errors,
                     comment=comment))

        else:

            # it all looks good, insert the comment into the blog post and redirect back to the post viewer
            posts.add_comment(permalink, name, email, body)

            bottle.redirect("/post/" + permalink)
Пример #23
0
    def post_newpost():
        title = bottle.request.forms.get("subject")
        post = bottle.request.forms.get("body")
        tags = bottle.request.forms.get("tags")

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        if title == "" or post == "":
            errors = "Post must contain a title and blog entry"
            return bottle.template(
                "newpost_template",
                dict(subject=cgi.escape(title, quote=True),
                     username=username,
                     body=cgi.escape(post, quote=True),
                     tags=tags,
                     errors=errors))

        # extract tags
        tags = cgi.escape(tags)
        tags_array = extract_tags(tags)

        # looks like a good entry, insert it escaped
        escaped_post = cgi.escape(post, quote=True)

        # substitute some <p> for the paragraph breaks
        newline = re.compile('\r?\n')
        formatted_post = newline.sub("<p>", escaped_post)

        permalink = posts.insert_entry(title, formatted_post, tags_array,
                                       username)

        # now bottle.redirect to the blog permalink
        bottle.redirect("/post/" + permalink)
Пример #24
0
def logs():
    email = get_email_from_session()
    with open(LOG_LOCATION, "r") as f:
        log_lines_desc = f.readlines()
        log_lines_desc.reverse()
        return template('logs', session_status=get_session_data(), log_lines=log_lines_desc)
Пример #25
0
 def present_login():
     return bottle.template("login",
                            dict(username="", password="", login_error=""))
Пример #26
0
def index():
    return template('index')
Пример #27
0
def present_login():
    return bottle.template("login", dict(username="", password="",
                                    login_error=""))
Пример #28
0
def about():
    return template('about')
Пример #29
0
def blog_index():

    cookie = bottle.request.get_cookie("session")

    username = sessions.get_username(cookie)

  # even if there is no logged in user, we can show the blog
    l = posts.get_posts(10)

    return bottle.template('blog_template', dict(myposts=l, username=username))


# Displays a particular blog post
    @bottle.get("/post/<permalink>")
    def show_post(permalink="notfound"):

        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)
        permalink = cgi.escape(permalink)

        print "about to query on permalink = ", permalink
        post = posts.get_post_by_permalink(permalink)

        if post is None:
            bottle.redirect("/post_not_found")

        # init comment form fields for additional comment
        comment = {'name': "", 'body': "", 'email': ""}

        return bottle.template("entry_template", dict(post=post, username=username, errors="", comment=comment))


    # used to process a comment on a blog post
    @bottle.post('/newcomment')
    def post_new_comment():
        name = bottle.request.forms.get("commentName")
        email = bottle.request.forms.get("commentEmail")
        body = bottle.request.forms.get("commentBody")
        permalink = bottle.request.forms.get("permalink")

        post = posts.get_post_by_permalink(permalink)
        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)

        # if post not found, redirect to post not found error
        if post is None:
            bottle.redirect("/post_not_found")
            return

        # if values not good, redirect to view with errors

        if name == "" or body == "":
            # user did not fill in enough information

            # init comment for web form
            comment = {'name': name, 'email': email, 'body': body}

            errors = "Post must contain your name and an actual comment."
            return bottle.template("entry_template", dict(post=post, username=username, errors=errors, comment=comment))

        else:

            # it all looks good, insert the comment into the blog post and redirect back to the post viewer
            posts.add_comment(permalink, name, email, body)

            bottle.redirect("/post/" + permalink)


    @bottle.get("/post_not_found")
    def post_not_found():
        return "Sorry, post not found"


    # Displays the form allowing a user to add a new post. Only works for logged in users
    @bottle.get('/newpost')
    def get_newpost():

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        return bottle.template("newpost_template", dict(subject="", body="", errors="", tags="", username=username))

    #
    # Post handler for setting up a new post.
    # Only works for logged in user.


    @bottle.post('/newpost')
    def post_newpost():
        title = bottle.request.forms.get("subject")
        post = bottle.request.forms.get("body")
        tags = bottle.request.forms.get("tags")

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        if title == "" or post == "":
            errors = "Post must contain a title and blog entry"
            return bottle.template("newpost_template", dict(subject=cgi.escape(title, quote=True), username=username,
                                                            body=cgi.escape(post, quote=True), tags=tags, errors=errors))

        # extract tags
        tags = cgi.escape(tags)
        tags_array = extract_tags(tags)

        # looks like a good entry, insert it escaped
        escaped_post = cgi.escape(post, quote=True)

        # substitute some <p> for the paragraph breaks
        newline = re.compile('\r?\n')
        formatted_post = newline.sub("<p>", escaped_post)

        permalink = posts.insert_entry(title, formatted_post, tags_array, username)

        # now bottle.redirect to the blog permalink
        bottle.redirect("/post/" + permalink)


    # displays the initial blog signup form
    @bottle.get('/signup')
    def present_signup():
        return bottle.template("signup",
                               dict(username="", password="",
                                    password_error="",
                                    email="", username_error="", email_error="",
                                    verify_error=""))

    # displays the initial blog login form


    @bottle.get('/login')
    def present_login():
        return bottle.template("login",
                               dict(username="", password="",
                                    login_error=""))

    # handles a login request


    @bottle.post('/login')
    def process_login():

        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")

        print "user submitted ", username, "pass ", password

        user_record = users.validate_login(username, password)
        if user_record:
            # username is stored in the user collection in the _id key
            session_id = sessions.start_session(user_record['_id'])

            if session_id is None:
                bottle.redirect("/internal_error")

            cookie = session_id

            # Warning, if you are running into a problem whereby the cookie being set here is
            # not getting set on the redirect, you are probably using the experimental version of bottle (.12).
            # revert to .11 to solve the problem.
            bottle.response.set_cookie("session", cookie)

            bottle.redirect("/welcome")

        else:
            return bottle.template("login",
                                   dict(username=cgi.escape(username), password="",
                                        login_error="Invalid Login"))


    @bottle.get('/internal_error')
    @bottle.view('error_template')
    def present_internal_error():
        return {'error': "System has encountered a DB error"}


    @bottle.get('/logout')
    def process_logout():

        cookie = bottle.request.get_cookie("session")

        sessions.end_session(cookie)

        bottle.response.set_cookie("session", "")

        bottle.redirect("/signup")


    @bottle.post('/signup')
    def process_signup():

        email = bottle.request.forms.get("email")
        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")
        verify = bottle.request.forms.get("verify")

        # set these up in case we have an error case
        errors = {'username': cgi.escape(username), 'email': cgi.escape(email)}
        if validate_signup(username, password, verify, email, errors):

            if not users.add_user(username, password, email):
                # this was a duplicate
                errors['username_error'] = "Username already in use. Please choose another"
                return bottle.template("signup", errors)

            session_id = sessions.start_session(username)
            print session_id
            bottle.response.set_cookie("session", session_id)
            bottle.redirect("/welcome")
        else:
            print "user did not validate"
            return bottle.template("signup", errors)


    @bottle.get("/welcome")
    def present_welcome():
        # check for a cookie, if present, then extract value

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            print "welcome: can't identify user...redirecting to signup"
            bottle.redirect("/signup")

        return bottle.template("welcome", {'username': username})


    def extract_tags(tags):

        whitespace = re.compile('\s')

        nowhite = whitespace.sub("", tags)
        tags_array = nowhite.split(',')

        # let's clean it up
        cleaned = []
        for tag in tags_array:
            if tag not in cleaned and tag != "":
                cleaned.append(tag)

        return cleaned


    # validates that the user information is valid for new signup, return True of False
    # and fills in the error string if there is an issue
    def validate_signup(username, password, verify, email, errors):
        USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
        PASS_RE = re.compile(r"^.{3,20}$")
        EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")

        errors['username_error'] = ""
        errors['password_error'] = ""
        errors['verify_error'] = ""
        errors['email_error'] = ""

        if not USER_RE.match(username):
            errors['username_error'] = "invalid username. try just letters and numbers"
            return False

        if not PASS_RE.match(password):
            errors['password_error'] = "invalid password."
            return False
        if password != verify:
            errors['verify_error'] = "password must match"
            return False
        if email != "":
            if not EMAIL_RE.match(email):
                errors['email_error'] = "invalid email address"
                return False
        return True

    connection_string = "mongodb://localhost"
    connection = pymongo.MongoClient(connection_string)
    database = connection.blogging

    posts = blogPostDAO.BlogPostDAO(database)
    users = userDAO.UserDAO(database)
    sessions = sessionDAO.SessionDAO(database)
Пример #30
0
def main():
    email = get_email_from_session()
    return template('default', content="Welcome!", session_status=get_session_data())
Пример #31
0
def config():
    email = get_email_from_session()
    user = users[email]
    watched_paths = user.get_watched_paths()
    default_action = user.get_default_action()
    return template('config', session_status=get_session_data(), watched_paths = watched_paths, default_action=default_action)
Пример #32
0
def blog_index():

    cookie = bottle.request.get_cookie("session")

    username = sessions.get_username(cookie)

    # even if there is no logged in user, we can show the blog
    l = posts.get_posts(10)

    return bottle.template('blog_template', dict(myposts=l, username=username))

    # Displays a particular blog post
    @bottle.get("/post/<permalink>")
    def show_post(permalink="notfound"):

        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)
        permalink = cgi.escape(permalink)

        print "about to query on permalink = ", permalink
        post = posts.get_post_by_permalink(permalink)

        if post is None:
            bottle.redirect("/post_not_found")

        # init comment form fields for additional comment
        comment = {'name': "", 'body': "", 'email': ""}

        return bottle.template(
            "entry_template",
            dict(post=post, username=username, errors="", comment=comment))

    # used to process a comment on a blog post
    @bottle.post('/newcomment')
    def post_new_comment():
        name = bottle.request.forms.get("commentName")
        email = bottle.request.forms.get("commentEmail")
        body = bottle.request.forms.get("commentBody")
        permalink = bottle.request.forms.get("permalink")

        post = posts.get_post_by_permalink(permalink)
        cookie = bottle.request.get_cookie("session")

        username = sessions.get_username(cookie)

        # if post not found, redirect to post not found error
        if post is None:
            bottle.redirect("/post_not_found")
            return

        # if values not good, redirect to view with errors

        if name == "" or body == "":
            # user did not fill in enough information

            # init comment for web form
            comment = {'name': name, 'email': email, 'body': body}

            errors = "Post must contain your name and an actual comment."
            return bottle.template(
                "entry_template",
                dict(post=post,
                     username=username,
                     errors=errors,
                     comment=comment))

        else:

            # it all looks good, insert the comment into the blog post and redirect back to the post viewer
            posts.add_comment(permalink, name, email, body)

            bottle.redirect("/post/" + permalink)

    @bottle.get("/post_not_found")
    def post_not_found():
        return "Sorry, post not found"

    # Displays the form allowing a user to add a new post. Only works for logged in users
    @bottle.get('/newpost')
    def get_newpost():

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        return bottle.template(
            "newpost_template",
            dict(subject="", body="", errors="", tags="", username=username))

    #
    # Post handler for setting up a new post.
    # Only works for logged in user.

    @bottle.post('/newpost')
    def post_newpost():
        title = bottle.request.forms.get("subject")
        post = bottle.request.forms.get("body")
        tags = bottle.request.forms.get("tags")

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            bottle.redirect("/login")

        if title == "" or post == "":
            errors = "Post must contain a title and blog entry"
            return bottle.template(
                "newpost_template",
                dict(subject=cgi.escape(title, quote=True),
                     username=username,
                     body=cgi.escape(post, quote=True),
                     tags=tags,
                     errors=errors))

        # extract tags
        tags = cgi.escape(tags)
        tags_array = extract_tags(tags)

        # looks like a good entry, insert it escaped
        escaped_post = cgi.escape(post, quote=True)

        # substitute some <p> for the paragraph breaks
        newline = re.compile('\r?\n')
        formatted_post = newline.sub("<p>", escaped_post)

        permalink = posts.insert_entry(title, formatted_post, tags_array,
                                       username)

        # now bottle.redirect to the blog permalink
        bottle.redirect("/post/" + permalink)

    # displays the initial blog signup form
    @bottle.get('/signup')
    def present_signup():
        return bottle.template(
            "signup",
            dict(username="",
                 password="",
                 password_error="",
                 email="",
                 username_error="",
                 email_error="",
                 verify_error=""))

    # displays the initial blog login form

    @bottle.get('/login')
    def present_login():
        return bottle.template("login",
                               dict(username="", password="", login_error=""))

    # handles a login request

    @bottle.post('/login')
    def process_login():

        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")

        print "user submitted ", username, "pass ", password

        user_record = users.validate_login(username, password)
        if user_record:
            # username is stored in the user collection in the _id key
            session_id = sessions.start_session(user_record['_id'])

            if session_id is None:
                bottle.redirect("/internal_error")

            cookie = session_id

            # Warning, if you are running into a problem whereby the cookie being set here is
            # not getting set on the redirect, you are probably using the experimental version of bottle (.12).
            # revert to .11 to solve the problem.
            bottle.response.set_cookie("session", cookie)

            bottle.redirect("/welcome")

        else:
            return bottle.template(
                "login",
                dict(username=cgi.escape(username),
                     password="",
                     login_error="Invalid Login"))

    @bottle.get('/internal_error')
    @bottle.view('error_template')
    def present_internal_error():
        return {'error': "System has encountered a DB error"}

    @bottle.get('/logout')
    def process_logout():

        cookie = bottle.request.get_cookie("session")

        sessions.end_session(cookie)

        bottle.response.set_cookie("session", "")

        bottle.redirect("/signup")

    @bottle.post('/signup')
    def process_signup():

        email = bottle.request.forms.get("email")
        username = bottle.request.forms.get("username")
        password = bottle.request.forms.get("password")
        verify = bottle.request.forms.get("verify")

        # set these up in case we have an error case
        errors = {'username': cgi.escape(username), 'email': cgi.escape(email)}
        if validate_signup(username, password, verify, email, errors):

            if not users.add_user(username, password, email):
                # this was a duplicate
                errors[
                    'username_error'] = "Username already in use. Please choose another"
                return bottle.template("signup", errors)

            session_id = sessions.start_session(username)
            print session_id
            bottle.response.set_cookie("session", session_id)
            bottle.redirect("/welcome")
        else:
            print "user did not validate"
            return bottle.template("signup", errors)

    @bottle.get("/welcome")
    def present_welcome():
        # check for a cookie, if present, then extract value

        cookie = bottle.request.get_cookie("session")
        username = sessions.get_username(cookie)  # see if user is logged in
        if username is None:
            print "welcome: can't identify user...redirecting to signup"
            bottle.redirect("/signup")

        return bottle.template("welcome", {'username': username})

    def extract_tags(tags):

        whitespace = re.compile('\s')

        nowhite = whitespace.sub("", tags)
        tags_array = nowhite.split(',')

        # let's clean it up
        cleaned = []
        for tag in tags_array:
            if tag not in cleaned and tag != "":
                cleaned.append(tag)

        return cleaned

    # validates that the user information is valid for new signup, return True of False
    # and fills in the error string if there is an issue
    def validate_signup(username, password, verify, email, errors):
        USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
        PASS_RE = re.compile(r"^.{3,20}$")
        EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")

        errors['username_error'] = ""
        errors['password_error'] = ""
        errors['verify_error'] = ""
        errors['email_error'] = ""

        if not USER_RE.match(username):
            errors[
                'username_error'] = "invalid username. try just letters and numbers"
            return False

        if not PASS_RE.match(password):
            errors['password_error'] = "invalid password."
            return False
        if password != verify:
            errors['verify_error'] = "password must match"
            return False
        if email != "":
            if not EMAIL_RE.match(email):
                errors['email_error'] = "invalid email address"
                return False
        return True

    connection_string = "mongodb://localhost"
    connection = pymongo.MongoClient(connection_string)
    database = connection.blogging

    posts = blogPostDAO.BlogPostDAO(database)
    users = userDAO.UserDAO(database)
    sessions = sessionDAO.SessionDAO(database)
Пример #33
0
def present_welcome():
    return bottle.template("welcome", {'username': '******'})
Пример #34
0
def present_welcome():
    return bottle.template("welcome", {'username': '******'})
Пример #35
0
 def present_signup():
     return bottle.template("signup",
                            dict(username="", password="",
                                 password_error="",
                                 email="", username_error="", email_error="",
                                 verify_error=""))