Exemplo n.º 1
0
def index(req,page="README"):
	# make sure the html fetch operation doesn't timeout too early
	sess = Session(req)
	sess.set_timeout(20)
	sess.save()

        # use the README page as the course index
	if page == "index":
		page = "README"
		
	# fetch the markdown text from dropbox
	link = "%s%s"%(githubRoot,page)
	#req.write(link)
	try:
		if page.endswith('.md') or page == 'README':
			# this is an HTML page
			req.content_type = "text/html"
			# give the page a title
			req.write("<title>ACCAD 5102</title>")
			# grab the stylesheet
			req.write("<style>%s</style>"%urllib2.urlopen("%sscreen.css"%webRoot).read())
			response = urllib2.urlopen(link)
                        #req.write(response.read())
			req.write(markdown.markdown(response.read(), ['tables']))
		else:
			util.redirect(req, link)
	except:
##		raise
##		req.write("error")
##		e = sys.exc_info()[0]
##		req.write(e)
		req.write("<br>This page does not exist yet")
Exemplo n.º 2
0
def seen(req, **params):
    """ Return all leak id that this user has seen. """

    sess = Session(req)
    if sess.is_new():
        req.status = apache.HTTP_BAD_REQUEST
        return 'not logged in'

    db = Database.get()

    c = db.cursor()
    q = """
        select
            us.leak_id
        from
            user_seen us
        where
            us.user_id = {user_id}
    """.format(user_id=sess['user_id'])
    c.execute(q)
    r = c.fetchall()
    c.close()

    # reformat the list...
    r = [e[0] for e in r]

    req.content_type = 'application/json'
    return json.dumps(dict(items=r), ensure_ascii=False)
Exemplo n.º 3
0
def clear(req, **params):
    """ Obliterate the session. """

    sess = Session(req)
    if not sess.is_new():
        sess.invalidate()

    req.content_type = 'application/json'
    return json.dumps(dict(success=True), ensure_ascii=False)
Exemplo n.º 4
0
def clear(req, **params):
    """ Obliterate the session. """

    sess = Session(req)
    if not sess.is_new():
        sess.invalidate()

    req.content_type = 'application/json'
    return json.dumps(dict(success=True), ensure_ascii=False)
Exemplo n.º 5
0
def index(req):
    session = Session(req, lock=False)
    # output directory for uploaded files used in _upload_limit.py
    session.lock()
    session['outdir'] = outdir
    session.save()
    session.unlock()
    return psp.PSP(req, 'test.html', vars={})
Exemplo n.º 6
0
def get(req, **params):
    """ Return logged-in username. """

    sess = Session(req)
    if sess.is_new():
        req.content_type = 'application/json'
        return 'null'

    ret = dict()
    ret['created'] = sess.created()
    ret['user_id'] = sess['user_id']
    ret['username'] = sess['username']

    req.content_type = 'application/json'
    return json.dumps(ret, ensure_ascii=False)
Exemplo n.º 7
0
def get(req, **params):
    """ Return logged-in username. """

    sess = Session(req)
    if sess.is_new():
        req.content_type = 'application/json'
        return 'null'

    ret = dict()
    ret['created'] = sess.created()
    ret['user_id'] = sess['user_id']
    ret['username'] = sess['username']

    req.content_type = 'application/json'
    return json.dumps(ret, ensure_ascii=False)
Exemplo n.º 8
0
    def __init_session(self, pysid):

        self.session = Session(req=self.request, sid=pysid, lock=self.core.config.settings['session']['lock'])

        if self.session.is_new():
            self.session.set_timeout(self.core.config.settings['session']['timeout'])
            self.session.save()
Exemplo n.º 9
0
def login(req, **params):
    """ New login attempt. Clean out old session if present, and create new one. """

    sess = Session(req)
    if not sess.is_new():
        sess.delete()
        sess = Session(req)
        if not sess.is_new():
            req.status = apache.HTTP_BAD_REQUEST
            return 'failed to create new session'

    if 'u' not in params or 'p' not in params:
        req.status = apache.HTTP_BAD_REQUEST
        return 'some parameters were not provided'

    ret = dict()

    if params['u'] != 'einstein' or params['p'] != 'fuckbin':
        ret['success'] = False
        ret['error'] = 'bad username or password'

        # note: session is not saved!
    else:
        ret['success'] = True

        # keep some stuff in session...
        sess['username'] = params['u']
        sess['user_id'] = 1

        sess.set_timeout(60 * 60 * 24 * 365 * 10)  # 10 year
        sess.save()

        # grab the user's cookie, and save the seen leaks into the database
        seen_ranges = urllib.unquote(Cookie.get_cookie(req, '__CJ_seen').value)
        seen_ranges = json.loads(seen_ranges)
        values = [[sess['user_id'], i] for seen_range in seen_ranges for i in
            range(seen_range['start'], seen_range['end'] + 1)]

        db = Database.get()
        c = db.cursor()
        c.executemany(""" replace into user_seen (user_id, leak_id) values (%s, %s) """, values)
        db.commit()
        c.close()

    req.content_type = 'application/json'
    return json.dumps(ret, ensure_ascii=False)
Exemplo n.º 10
0
def index(req, **params):
    """ Show details of a certain leek.

    Transfers the data and related information.
    """

    db = Database.get()

    if 'id' not in params or not params['id'].isdigit():
        req.status = apache.HTTP_BAD_REQUEST
        return '"id" param is not digits'

    leak_id = int(params['id'])

    c = db.cursor()
    c.execute("""
        select
            l.data, l.htmldata
        from
            leaks l
        where
            l.leak_id = %s
    """, (leak_id, ))
    r = c.fetchall()

    sess = Session(req)
    if not sess.is_new():
        c.execute("""
            replace into user_seen (user_id, leak_id) values (%s, %s)
        """, (sess['user_id'], leak_id))

    db.commit()
    c.close()

    details = list(r[0])
#    details[0] = urllib.quote(details[0])
    details[0] = details[0].replace('&', '&amp;').replace('<', '&lt;').replace('>',
        '&gt;').replace('"', '&quot;').replace("'", '&#39;')

    req.content_type = 'application/json'
    return json.dumps(details, ensure_ascii=False)
Exemplo n.º 11
0
def fixuphandler(req):
    if req.method == 'POST':
        length = req.headers_in.get('Content-Length')
        if length is None:
            req.status = apache.HTTP_LENGTH_REQUIRED
            req.write("{ 'code': 5, 'desc': 'content length required' }")
            return apache.DONE
        elif int(length) > UPLOAD_LIMIT:
            req.status = apache.HTTP_REQUEST_ENTITY_TOO_LARGE
            req.write("{ 'code': 4, 'desc': 'upload maximum size exceeded' }")
            return apache.DONE
        elif req.uri.startswith('/upload_file'):
            # parse arguments
            args = dict(
                [part.split('=') for part in (req.args or "").split('&')])
            filename = ""
            if args.get('id'):
                filename = urllib.unquote(os.path.split(args['id'])[1])
            if filename == "":
                req.write("{ 'code': 3, 'desc': 'id not supplied' }")
                return apache.DONE
            if not hasattr(req, "session"):
                req.session = Session(req, lock=False)
            session = req.session
            session.lock()
            if filename in os.listdir(session['outdir']):
                session.unlock()
                req.write("{ 'code': 1, 'desc': 'already exist' }")
                return apache.DONE
            session['temp_name_' + filename] = os.path.join(
                session['outdir'], filename)
            session['temp_size_' + filename] = int(length)
            session.save()
            file_factory = StorageFactory(session['outdir'])
            session.unlock()
            util.FieldStorage(req,
                              keep_blank_values=False,
                              file_callback=file_factory.create)
    return apache.OK
Exemplo n.º 12
0
def index(req, **params):
    """ List recent leaks. Limit of 300 leaks shown.

    parameters:
        - after:
            show leaks after this timestamp
        - period:
            show leaks that occured within this period (today, week, month)
    """

    limit = ''
    if 'after' in params:
        if not params['after'].isdigit():
            req.status = apache.HTTP_BAD_REQUEST
            return '"after" param is not digits'

        leak_id = int(params['after'])
        where = 'l.leak_id >= %u' % leak_id

    elif 'before' in params:
        if not params['after'].isdigit():
            req.status = apache.HTTP_BAD_REQUEST
            return '"before" param is not digits'

        leak_id = int(params['after'])
        where = 'l.leak_id <= %u' % leak_id
        limit = 'limit 10'

    elif 'period' in params:
        if params['period'] == 'initial':
            # By default, load today's leaks, otherwise load the last 300 leaks from whenever...
            where = 'DATE(FROM_UNIXTIME(l.date)) = DATE(SYSDATE())'
        else:
            req.status = apache.HTTP_BAD_REQUEST
            return '"period" param has unknown value'
    else:
        req.status = apache.HTTP_BAD_REQUEST
        return 'bad request'

    sess = Session(req)
    if sess.is_new():
        seen = 'false'
    else:
        seen = '(select true from user_seen us where us.user_id = {user_id} and us.leak_id = l.leak_id)'.format(
            user_id=sess['user_id'], )

    db = Database.get()

    c = db.cursor()
    q = """
        select
            l.leak_id,
            ({seen}) as seen,
            l.date, l.comment, l.reason, l.source
        from
            leaks l
        where
            {where} and
            l.isparsed = 1
        order by leak_id
        {limit}
    """.format(seen=seen, where=where, limit=limit)
    c.execute(q)
    r = list(c.fetchall())

    if len(r) == 0 and 'period' in params and params['period'] == 'initial':
        # last chance to get some latest entry...
        c.execute("""
            select
                l.leak_id,
                ({seen}) as seen,
                l.date, l.comment, l.reason, l.source
            from
                leaks l
            where
                l.isparsed = 1
            order by leak_id desc
            limit 200
        """.format(seen=seen, where=where, limit=limit))
        r = list(c.fetchall())
        r.reverse()

    if len(r) > 0:
        leak_ids = [str(e[0]) for e in r]
        c.execute("""
            select
                leak_id, name, value
            from
                leak_metadata
            where
                leak_id in ({ids})
        """.format(ids=','.join(leak_ids)))
        metadata = c.fetchall()

        # append a dictionary at the end of every entry
        for i in range(len(r)):
            r[i] = list(r[i])
            r[i].append({})

        # insert metadata into dictionary
        for i in range(len(r)):
            for data in metadata:
                if data[0] != r[i][0]:
                    continue

                r[i][-1][data[1]] = data[2]

    c.close()

    req.content_type = 'application/json'
    return json.dumps(dict(items=r), ensure_ascii=False)
Exemplo n.º 13
0
 def _wrapper(req, *args, **kwargs):
     if not hasattr(req, "session"):
         req.session = Session(req, lock=False)
     return f(req, *args, **kwargs)
Exemplo n.º 14
0
def login(req, **params):
    """ New login attempt. Clean out old session if present, and create new one. """

    sess = Session(req)
    if not sess.is_new():
        sess.delete()
        sess = Session(req)
        if not sess.is_new():
            req.status = apache.HTTP_BAD_REQUEST
            return 'failed to create new session'

    if 'u' not in params or 'p' not in params:
        req.status = apache.HTTP_BAD_REQUEST
        return 'some parameters were not provided'

    ret = dict()

    if params['u'] != 'einstein' or params['p'] != 'fuckbin':
        ret['success'] = False
        ret['error'] = 'bad username or password'

        # note: session is not saved!
    else:
        ret['success'] = True

        # keep some stuff in session...
        sess['username'] = params['u']
        sess['user_id'] = 1

        sess.set_timeout(60 * 60 * 24 * 365 * 10)  # 10 year
        sess.save()

        # grab the user's cookie, and save the seen leaks into the database
        seen_ranges = urllib.unquote(Cookie.get_cookie(req, '__CJ_seen').value)
        seen_ranges = json.loads(seen_ranges)
        values = [[sess['user_id'], i] for seen_range in seen_ranges
                  for i in range(seen_range['start'], seen_range['end'] + 1)]

        db = Database.get()
        c = db.cursor()
        c.executemany(
            """ replace into user_seen (user_id, leak_id) values (%s, %s) """,
            values)
        db.commit()
        c.close()

    req.content_type = 'application/json'
    return json.dumps(ret, ensure_ascii=False)
Exemplo n.º 15
0
 def retrieveSession(self, req):
   sessionSecret = self.getSessionSecret(req)
   sessionTimeout = self.getSessionTimeout(req)
   session = Session(req,secret=sessionSecret,timeout=sessionTimeout)
   session.save()
   return session
Exemplo n.º 16
0
class session(object):

    session = None

    def __init__(self, core):
        self.request = core.request
        self.core = core

        try:
            self.cookie_name = core.config.apache_options['mod_python.session.cookie_name']
        except:
            self.cookie_name = 'pysid'

        try:
            self.pysid = self.core.input.cookie(self.cookie_name)
        except:
            self.pysid = None

        self.core.log_message(1, '------------ Session Handler Initialised')

    def __init_session(self, pysid):

        self.session = Session(req=self.request, sid=pysid, lock=self.core.config.settings['session']['lock'])

        if self.session.is_new():
            self.session.set_timeout(self.core.config.settings['session']['timeout'])
            self.session.save()

    def start(self):

        try:
            self.__init_session(self.pysid)
        except ValueError:
            self.__init_session(None)

    def get_id(self):

        if self.session == None:
            self.start()

        return self.session.id()

    def set(self, name, value):

        if self.session == None:
            self.start()

        self.session[name] = value
        self.session.save()

    def get(self, name = None):

        if not self.session:
            self.start()

        try:
            if not name:
                return self.session

            return self.session[name]
        except:
            return None

    def destroy(self):
        self.session.invalidate()
        self.session.delete()