Beispiel #1
0
	def __init__(self):
		"""Creates a new instance of ImportThread and connects to the database.
		This design pattern is important: since the constructor runs synchonously,
		it ensures that two threads don't attempt to initialize the database at
		the same time.
		"""
		super(ImportThread, self).__init__(name=__name__)
		self.log = initLogging(__name__)
		db = DatabaseWrapper()
		self.sa_session = db.get_session()
Beispiel #2
0
def check_password():
    """If the supplied username and password are valid, returns False, indicating that the request has not been 
    handled, and other request handlers should be allowed to execute.
    
    If the supplied username and password are not valid, returns True, indicating that the request has been 
    handled, and other request handlers should not be allowed to execute. An HTTP 401/403 error will also be
    thrown in this case.
    
    The password argument is first treated as a session token. If this check fails, then it is treated as a 
    password. If either test passes, the cherrypy.request.authorized member is set to True and the 
    cherrypy.request.user member is set to the authenticated user."""
    db = DatabaseWrapper()
    session = db.get_session()

    if 'authorization' in cherrypy.request.headers:
        auth = httpauth.parseAuthorization(cherrypy.request.headers['authorization'])
        if auth is None:
            raise cherrypy.HTTPError(400, 'Invalid Authorization Header.')

        username = auth['username']
        password = auth['password']
        user = None

        # try to treat username as a session token
        if username is not None:
            user = session.query(User).filter(User.username == username and User.token == password and User.token_expires > datetime.datetime.utcnow()).first()
            if user is not None:
                user.update_token_expiry()
                session.commit()
                cherrypy.request.user = user

        # try to look up username and password in the database
        if user is None and username is not None and password is not None:
            user = session.query(User).filter(User.username == username).first()
            if user is not None and user.passhash == user.password_hash(username, password):
                cherrypy.request.user = user

        if user is not None:
            cherrypy.request.authorized = True
            # if the user was authorized, allow other page handlers to run
            return False
        else:
            cherrypy.request.authorized = False
            if cherrypy.request.headers['X-Requested-With'] == 'XMLHttpRequest':
                # if the request came from a browser, don't send a 401 because that will
                # trigger a shitty looking popup. Use a 403 instead.
                raise cherrypy.HTTPError(403, 'Invalid Credentials.')
            else:
                raise cherrypy.HTTPError(401, 'Invalid Credentials.')

            # the user was not authorized, suppress other page handlers from running
            return True
    else:
        raise cherrypy.HTTPError(400, 'Missing Authorization Header.')
Beispiel #3
0
    def __init__(self):
        """Creates a new instance of ImportThread and connects to the database.
        This design pattern is important: since the constructor runs synchonously,
        it ensures that two threads don't attempt to initialize the database at
        the same time.
        """
        super(ImportThread, self).__init__(name=__name__)
        db = DatabaseWrapper()
        self.sa_session = db.get_session()

        # create a log object that uses the same session that we do so that we can write error messages
        # during transactions
        self.log = log.Log(__name__, self.sa_session)
Beispiel #4
0
	def emit(self, record):
		responsible_for_session = False
		if self.session is None:
			# if a session wasn't specified by the calling object, create one and set a flag that ensures that
			# we will clean up after ourselves.
			db = DatabaseWrapper()
			self.session = db.get_session()
			responsible_for_session = True

		try:
			logEntry = LogEntry(record.levelname, self.module_name, self.format(record), record.exc_text)
			self.session.add(logEntry)

			if responsible_for_session:
				self.session.commit()
		except:
			print (u'WARNING: Database is locked, failed to write message to log_entries: %s' % self.format(record))
			if responsible_for_session and self.session is not None:
				self.session.rollback()
		finally:
			if responsible_for_session and self.session is not None:
				self.session.close()
				self.session = None
Beispiel #5
0
class SAEnginePlugin(plugins.SimplePlugin):
	def __init__(self, bus):
		plugins.SimplePlugin.__init__(self, bus)
		self.sa_engine = None
		self.bus.subscribe(u'bind', self.bind)

	def start(self):
		self.db = DatabaseWrapper()
		self.sa_engine = self.db.get_engine()

	def stop(self):
		if self.sa_engine:
			self.sa_engine.dispose()
			self.sa_engine = None

	def bind(self, session):
		session.configure(bind=self.sa_engine)
Beispiel #6
0
class SAEnginePlugin(plugins.SimplePlugin):
    """A plugin to help SQLAlchemy bind correctly to CherryPy threads.
    See http://www.defuze.org/archives/222-integrating-sqlalchemy-into-a-cherrypy-application.html
    """
    def __init__(self, bus):
        plugins.SimplePlugin.__init__(self, bus)
        self.sa_engine = None
        self.bus.subscribe(u'bind', self.bind)

    def start(self):
        self.db = DatabaseWrapper()
        self.sa_engine = self.db.get_engine()

    def stop(self):
        if self.sa_engine:
            self.sa_engine.dispose()
            self.sa_engine = None

    def bind(self, session):
        session.configure(bind=self.sa_engine)
Beispiel #7
0
 def start(self):
     self.db = DatabaseWrapper()
     self.sa_engine = self.db.get_engine()