# Buggy code
def lookup():
    msgs = []
    flagged = False
    for fn in os.listdir(g.loc):
        if fn == "_FLAG":
            flagged = True
            continue
        if fn.startswith("reply-"):
            msgs.append(
                dict(
                    id=fn,
                    date=str(
                        datetime.fromtimestamp(os.stat(store.path(g.sid, fn)).st_mtime)
                    ),
                    msg=crypto_util.decrypt(
                        g.sid, g.codename, file(store.path(g.sid, fn)).read()
                    ),
                )
            )
    if flagged:
        session["flagged"] = True

    def async_genkey(sid, codename):
        with app.app_context():
            background.execute(lambda: crypto_util.genkeypair(sid, codename))

    # Generate a keypair to encrypt replies from the journalist
    # Only do this if the journalist has flagged the source as one
    # that they would like to reply to. (Issue #140.)
    if not crypto_util.getkey(g.sid) and flagged:
        async_genkey(g.sid, g.codename)

    return render_template(
        "lookup.html",
        codename=g.codename,
        msgs=msgs,
        flagged=flagged,
        haskey=crypto_util.getkey(g.sid),
    )


# Traceback (KeyError)
[Mon Dec 02 21:49:44 2013] [error] ERROR:source:Exception on / [GET]
[Mon Dec 02 21:49:44 2013] [error] Traceback (most recent call last):
[Mon Dec 02 21:49:44 2013] [error]   File
"/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in
wsgi_app
[Mon Dec 02 21:49:44 2013] [error]     response =
self.full_dispatch_request()
[Mon Dec 02 21:49:44 2013] [error]   File
"/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in
full_dispatch_request
[Mon Dec 02 21:49:44 2013] [error]     rv = self.handle_user_exception(e)
[Mon Dec 02 21:49:44 2013] [error]   File
"/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in
handle_user_exception
[Mon Dec 02 21:49:44 2013] [error]     reraise(exc_type, exc_value, tb)
[Mon Dec 02 21:49:44 2013] [error]   File
"/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1473, in
full_dispatch_request
[Mon Dec 02 21:49:44 2013] [error]     rv = self.preprocess_request()
[Mon Dec 02 21:49:44 2013] [error]   File
"/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1666, in
preprocess_request
[Mon Dec 02 21:49:44 2013] [error]     rv = func()
[Mon Dec 02 21:49:44 2013] [error]   File
"/var/www/securedrop/source.py", line 52, in decorated_function
[Mon Dec 02 21:49:44 2013] [error]     return f(*args, **kwargs)
[Mon Dec 02 21:49:44 2013] [error]   File
"/var/www/securedrop/source.py", line 64, in setup_g
[Mon Dec 02 21:49:44 2013] [error]     g.flagged = session['flagged']
[Mon Dec 02 21:49:44 2013] [error]   File
"/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 368, in
<lambda>
[Mon Dec 02 21:49:44 2013] [error]     __getitem__ = lambda x, i:
x._get_current_object()[i]
[Mon Dec 02 21:49:44 2013] [error] KeyError: 'flagged'

# Fixed code
def lookup():
    msgs = []
    flagged = False
    for fn in os.listdir(g.loc):
        # TODO: make 'flag' a db column, so we can replace this with a db
        # lookup in the future
        if fn == "_FLAG":
            flagged = True
            continue
        if fn.startswith("reply-"):
            msgs.append(
                dict(
                    id=fn,
                    date=str(
                        datetime.fromtimestamp(os.stat(store.path(g.sid, fn)).st_mtime)
                    ),
                    msg=crypto_util.decrypt(
                        g.sid, g.codename, file(store.path(g.sid, fn)).read()
                    ),
                )
            )
    if flagged:
        session["flagged"] = True

    def async_genkey(sid, codename):
        with app.app_context():
            background.execute(lambda: crypto_util.genkeypair(sid, codename))

    # Generate a keypair to encrypt replies from the journalist
    # Only do this if the journalist has flagged the source as one
    # that they would like to reply to. (Issue #140.)
    if not crypto_util.getkey(g.sid) and flagged:
        async_genkey(g.sid, g.codename)

    return render_template(
        "lookup.html",
        codename=g.codename,
        msgs=msgs,
        flagged=flagged,
        haskey=crypto_util.getkey(g.sid),
    )