def __init__(self): self.logger = logging.getLogger('modules.users') Manageusers.createTable(ifNotExists=True) htpc.MODULES.append({ 'name': 'Manage users', 'description': 'Add more users to HTPC-Manager. Make sure you enable authentication and have provided a master username and password in General settings, otherwise authentication will not be used.', 'isThirdParty': False, 'id': 'users', 'action': htpc.WEBDIR + 'users/setusers', 'fields': [ {'type':'select', 'label':'User', 'name':'users_user_id', 'options':[ {'name':'New', 'value':0} ]}, {'type':'text', 'label':'Username', 'name':'users_user_username'}, {'type':'password', 'label':'Password', 'name':'users_user_password'}, {'type':'select', 'label':'Role', 'name': 'users_user_role', 'desc': 'Admin users can change settings while normal users can only view pages.', 'options': [ {'name': 'user', 'value':'user'}, {'name':'admin', 'value': 'admin'} ]} ]})
def __init__(self): self.logger = logging.getLogger('modules.users') Manageusers.createTable(ifNotExists=True) htpc.MODULES.append({ 'name': 'Manage users', 'description': '<div class="alert alert-block alert-danger"><i class="fa fa-exclamation-triangle fa-fw"></i> Make sure you enable authentication and provide a master username and password in General settings, otherwise authentication will not be used.</div>', 'isThirdParty': False, 'id': 'users', 'action': htpc.WEBDIR + 'users/setusers', 'fields': [ {'type': 'select', 'label': 'User', 'name': 'users_user_id', 'options': [{'name': 'New', 'value': 0}] }, {'type': 'text', 'label': 'Username', 'name': 'users_user_username'}, {'type': 'password', 'label': 'Password', 'name': 'users_user_password'}, {'type': 'select', 'label': 'Role', 'name': 'users_user_role', 'desc': 'Admin users can change settings whilst normal users can only view pages.', 'options': [ {'name': 'restricted user', 'value': 'restricted_user'}, {'name': 'user', 'value': 'user'}, {'name': 'admin', 'value': 'admin'} ] } ] })
def updatebl(self): # fix me from modules.newznab import NewznabIndexers from modules.kodi import KodiServers from htpc.manageusers import Manageusers NewznabIndexers.createTable(ifNotExists=True) KodiServers.createTable(ifNotExists=True) Manageusers.createTable(ifNotExists=True) bl = [] fl = Setting.select().orderBy(Setting.q.key) for i in fl: if i.key.endswith("_apikey") or i.key.endswith("_username") or i.key.endswith("_password") or i.key.endswith("_passkey"): if len(i.val) > 1: bl.append(i.val) indexers = NewznabIndexers.select().orderBy(NewznabIndexers.q.apikey) for indexer in indexers: if len(indexer.apikey) > 1: bl.append(indexer.apikey) kodi = KodiServers.select().orderBy(KodiServers.q.password) for k in kodi: if len(k.password) > 1: bl.append(k.password) users = Manageusers.select().orderBy(Manageusers.q.username) for user in users: if len(user.password) > 1: bl.append(user.password) htpc.BLACKLISTWORDS = bl return bl
def __init__(self): self.logger = logging.getLogger('modules.users') Manageusers.createTable(ifNotExists=True) htpc.MODULES.append({ 'name': 'Manage users', 'description': 'Add more users to HTPC-Manager. Make sure you enable authentication and have provided a master username and password in General settings, otherwise authentication will not be used.', 'isThirdParty': False, 'id': 'users', 'action': htpc.WEBDIR + 'users/setusers', 'fields': [{ 'type': 'select', 'label': 'User', 'name': 'users_user_id', 'options': [{ 'name': 'New', 'value': 0 }] }, { 'type': 'text', 'label': 'Username', 'name': 'users_user_username' }, { 'type': 'password', 'label': 'Password', 'name': 'users_user_password' }, { 'type': 'select', 'label': 'Role', 'name': 'users_user_role', 'desc': 'Admin users can change settings while normal users can only view pages.', 'options': [{ 'name': 'user', 'value': 'user' }, { 'name': 'admin', 'value': 'admin' }] }] })
def getuser(self, id=None): if id: """ Get user info, used by settings """ try: user = Manageusers.selectBy(id=id).getOne() return dict( (c, getattr(user, c)) for c in user.sqlmeta.columns) except SQLObjectNotFound: return """ Get a list of all users""" users = [] for s in Manageusers.select(): users.append({'id': s.id, 'name': s.username}) if len(users) < 1: return return {'users': users}
def getuser(self, id=None): if id: """ Get user info, used by settings """ try: user = Manageusers.selectBy(id=id).getOne() return dict((c, getattr(user, c)) for c in user.sqlmeta.columns) except SQLObjectNotFound: return """ Get a list of all users""" users = [] for s in Manageusers.select(): users.append({'id': s.id, 'name': s.username}) if len(users) < 1: return return {'users': users}
def setusers(self, users_user_id, users_user_username, users_user_password, users_user_role): if users_user_id == "0": self.logger.debug('Creating Manage users in db') try: Manageusers(username=users_user_username, password=users_user_password, role=users_user_role) return 'hack' except Exception, e: self.logger.debug('Failed to create %s %s' % (users_user_username, e)) return
def check_credentials(username, password): """Verifies credentials for username and password. Returns None on success or a string describing the error on failure""" # Adapt to your needs try: #Select one item with in username col with username (there is only one as its unique) userexist = Manageusers.selectBy(username=username).getOne() if userexist and userexist.password == password: return None else: return u"Incorrect username or password." except Exception as e: return u"Incorrect username or password."
def updatebl(self): # fix me from modules.newznab import NewznabIndexers from modules.kodi import KodiServers from htpc.manageusers import Manageusers NewznabIndexers.createTable(ifNotExists=True) KodiServers.createTable(ifNotExists=True) Manageusers.createTable(ifNotExists=True) bl = [] fl = Setting.select().orderBy(Setting.q.key) for i in fl: if i.key.endswith("_apikey") or i.key.endswith( "_username") or i.key.endswith( "_password") or i.key.endswith("_passkey"): if len(i.val) > 1: bl.append(i.val) indexers = NewznabIndexers.select().orderBy(NewznabIndexers.q.apikey) for indexer in indexers: if len(indexer.apikey) > 1: bl.append(indexer.apikey) kodi = KodiServers.select().orderBy(KodiServers.q.password) for k in kodi: if len(k.password) > 1: bl.append(k.password) users = Manageusers.select().orderBy(Manageusers.q.username) for user in users: if len(user.password) > 1: bl.append(user.password) htpc.BLACKLISTWORDS = bl return bl
def check_credentials(username, password): """Verifies credentials for username and password. Returns None on success or a string describing the error on failure""" # Adapt to your needs try: #Select one item with in username col with username (there is only one as its unique) userexist = Manageusers.selectBy(username=username).getOne() if userexist and userexist.password == password: logger.debug("%s %s logged in from %s" % (userexist.role.upper(), userexist.username, cherrypy.request.remote.ip)) return None else: logger.warning("Failed login attempt with username: %s password: %s from ip: %s" % (username, password, cherrypy.request.remote.ip)) return u"Incorrect username or password." except Exception as e: logger.warning("Failed login attempt with username: %s password: %s from IP: %s" % (username, password, cherrypy.request.remote.ip)) return u"Incorrect username or password."
def check(): userexist = Manageusers.selectBy(username=cherrypy.request.login).getOne() if userexist and userexist.role in groupname: return cherrypy.request.login == userexist.username and userexist.role in groupname
def start(): """ Main function for starting HTTP server """ logger = logging.getLogger('htpc.server') logger.debug("Setting up to start cherrypy") protocol = "" # Set server ip, port and root cherrypy.config.update({ 'server.socket_host': htpc.HOST, 'server.socket_port': htpc.PORT, 'log.screen': False, 'server.thread_pool': 15, 'server.socket_queue_size': 10 }) # Wrap htpc manager in secure headers. # http://cherrypy.readthedocs.org/en/latest/advanced.html#securing-your-server if htpc.settings.get('app_use_secure_headers', True): cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60) cherrypy.config.update({'tools.secureheaders.on': True}) # Enable auth if username and pass is set, add to db as admin if htpc.USERNAME and htpc.PASSWORD: """ Lets see if the that username and password is already in the db""" try: user = Manageusers.selectBy(username=htpc.USERNAME).getOne() # If the user exist if user: # Activate the new password user.password = htpc.PASSWORD except SQLObjectNotFound: logger.debug( "Added htpc.USERNAME and htpc.PASSWORD to Manageusers table") Manageusers(username=htpc.USERNAME, password=htpc.PASSWORD, role='admin') logger.debug('Updating cherrypy config, activating sessions and auth') cherrypy.config.update({ 'tools.sessions.on': True, 'tools.auth.on': True, 'tools.sessions.timeout': 43200, 'tools.sessions.httponly': True #'tools.sessions.secure': True # Auth does not work with this on #TODO }) # Set server environment to production unless when debugging if not htpc.DEV: cherrypy.config.update({'environment': 'production'}) if htpc.settings.get('app_use_ssl'): serverkey = os.path.join(htpc.DATADIR, 'server.key') cert = os.path.join(htpc.DATADIR, 'server.cert') # If either the HTTPS certificate or key do not exist, make some self-signed ones. if not (cert and os.path.exists(cert)) or not ( serverkey and os.path.exists(serverkey)): logger.debug( 'There isnt any certificate or key, trying to make them') if create_https_certificates(cert, serverkey): # Save the new crt and key to settings htpc.SSLKEY = htpc.settings.set('app_ssl_key', serverkey) htpc.SSLCERT = htpc.settings.set('app_ssl_cert', cert) htpc.ENABLESSL = True logger.debug("Created certificate and key successfully") logger.info("Restarting to activate SSL") do_restart() if (os.path.exists(htpc.settings.get('app_ssl_cert')) and os.path.exists(htpc.settings.get('app_ssl_key'))): htpc.ENABLESSL = True if htpc.ENABLESSL: protocol = "s" logger.debug("SSL is enabled") cherrypy.config.update({ 'server.ssl_certificate': htpc.settings.get('app_ssl_cert'), 'server.ssl_private_key': htpc.settings.get('app_ssl_key') }) if htpc.settings.get('app_use_proxy_headers'): cherrypy.config.update({'tools.proxy.on': True}) if htpc.settings.get('app_use_proxy_headers') and htpc.settings.get( 'app_use_proxy_headers_basepath'): cherrypy.config.update({ 'tools.proxy.base': str(htpc.settings.get('app_use_proxy_headers_basepath')) }) # Daemonize cherrypy if specified if htpc.DAEMON: if sys.platform == 'win32': logger.error( "You are using Windows - I cannot setup daemon mode. Please use the pythonw executable instead." ) logger.error( "More information at http://docs.python.org/2/using/windows.html." ) else: Daemonizer(cherrypy.engine).subscribe() # Create PID if specified if htpc.PID: PIDFile(cherrypy.engine, htpc.PID).subscribe() def stopp_ap(): htpc.SCHED.shutdown(wait=False) stopp_ap.priority = 10 cherrypy.engine.subscribe('stop', stopp_ap) cherrypy.engine.timeout_monitor.unsubscribe() # Set static directories webdir = os.path.join(htpc.RUNDIR, htpc.TEMPLATE) favicon = os.path.join(webdir, "img/favicon.ico") app_config = { '/': { 'tools.staticdir.root': webdir, 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.gzip.on': True, 'tools.gzip.mime_types': [ 'text/html', 'text/plain', 'text/css', 'text/javascript', 'application/json', 'application/javascript' ] }, '/js': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'css' }, '/img': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'img' }, '/favicon.ico': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticfile.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticfile.filename': favicon } } # Start the CherryPy server logger.info("Starting up webserver") print '*******************************************************************' print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.' print 'Start your browser and go to http%s://localhost:%s%s' % ( protocol, htpc.PORT, htpc.WEBDIR[:-1]) print '*******************************************************************' cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)
def delusers(self, id): """ Delete a user """ self.logger.debug("Deleting user " + str(id)) Manageusers.delete(id) return
@cherrypy.expose() @require(member_of("admin")) def setusers(self, users_user_id, users_user_username, users_user_password, users_user_role): if users_user_id == "0": self.logger.debug('Creating Manage users in db') try: Manageusers(username=users_user_username, password=users_user_password, role=users_user_role) return 'hack' except Exception, e: self.logger.debug('Failed to create %s %s' % (users_user_username, e)) return else: try: users = Manageusers.selectBy(username=users_user_username).getOne() users.username = users_user_username users.password = users_user_password users.role = users_user_role return 'hack' except SQLObjectNotFound, e: self.logger.debug('Failed to update username on %s' % users_user_username) return @cherrypy.expose() @require(member_of("admin")) @cherrypy.tools.json_out() def getuser(self, id=None): if id: """ Get user info, used by settings """ try:
def deluser(self, id): """ Delete a user """ self.logger.debug("Deleting user " + str(id)) Manageusers.delete(id) return
def setusers(self, users_user_id, users_user_username, users_user_password, users_user_role): if users_user_id == "0": self.logger.debug('Creating Manage users in db') try: Manageusers(username=users_user_username, password=users_user_password, role=users_user_role) return 'hack' except Exception, e: self.logger.debug('Failed to create %s %s' % (users_user_username, e)) return else: try: users = Manageusers.selectBy( username=users_user_username).getOne() users.username = users_user_username users.password = users_user_password users.role = users_user_role return 'hack' except SQLObjectNotFound, e: self.logger.debug('Failed to update username on %s' % users_user_username) return @cherrypy.expose() @require(member_of("admin")) @cherrypy.tools.json_out() def getuser(self, id=None): if id: """ Get user info, used by settings """
def start(): """ Main function for starting HTTP server """ logger = logging.getLogger('htpc.server') logger.debug("Setting up to start cherrypy") protocol = "" # Set server ip, port and root cherrypy.config.update({ 'server.socket_host': htpc.HOST, 'server.socket_port': htpc.PORT, 'log.screen': False, 'server.thread_pool': 15, 'server.socket_queue_size': 10 }) # Wrap htpc manager in secure headers. # http://cherrypy.readthedocs.org/en/latest/advanced.html#securing-your-server if htpc.settings.get('app_use_secure_headers', True): cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60) cherrypy.config.update({'tools.secureheaders.on': True}) # Enable auth if username and pass is set, add to db as admin if htpc.USERNAME and htpc.PASSWORD: """ Lets see if the that username and password is already in the db""" try: user = Manageusers.selectBy(username=htpc.USERNAME).getOne() # If the user exist if user: # Activate the new password user.password = htpc.PASSWORD except SQLObjectNotFound: logger.debug("Added htpc.USERNAME and htpc.PASSWORD to Manageusers table") Manageusers(username=htpc.USERNAME, password=htpc.PASSWORD, role='admin') logger.debug('Updating cherrypy config, activating sessions and auth') cherrypy.config.update({ 'tools.sessions.on': True, 'tools.auth.on': True, 'tools.sessions.timeout': 43200, 'tools.sessions.httponly': True #'tools.sessions.secure': True # Auth does not work with this on #TODO }) # Set server environment to production unless when debugging if not htpc.DEV: cherrypy.config.update({ 'environment': 'production' }) if htpc.settings.get('app_use_ssl'): serverkey = os.path.join(htpc.DATADIR, 'server.key') cert = os.path.join(htpc.DATADIR, 'server.cert') # If either the HTTPS certificate or key do not exist, make some self-signed ones. if not (cert and os.path.exists(cert)) or not (serverkey and os.path.exists(serverkey)): logger.debug('There isnt any certificate or key, trying to make them') if create_https_certificates(cert, serverkey): # Save the new crt and key to settings htpc.SSLKEY = htpc.settings.set('app_ssl_key', serverkey) htpc.SSLCERT = htpc.settings.set('app_ssl_cert', cert) htpc.ENABLESSL = True logger.debug("Created certificate and key successfully") logger.info("Restarting to activate SSL") do_restart() if (os.path.exists(htpc.settings.get('app_ssl_cert')) and os.path.exists(htpc.settings.get('app_ssl_key'))): htpc.ENABLESSL = True if htpc.ENABLESSL: protocol = "s" logger.debug("SSL is enabled") cherrypy.config.update({ 'server.ssl_certificate': htpc.settings.get('app_ssl_cert'), 'server.ssl_private_key': htpc.settings.get('app_ssl_key') }) if htpc.settings.get('app_use_proxy_headers'): cherrypy.config.update({ 'tools.proxy.on': True }) if htpc.settings.get('app_use_proxy_headers') and htpc.settings.get('app_use_proxy_headers_basepath'): cherrypy.config.update({ 'tools.proxy.base': str(htpc.settings.get('app_use_proxy_headers_basepath')) }) # Daemonize cherrypy if specified if htpc.DAEMON: if sys.platform == 'win32': logger.error("You are using Windows - I cannot setup daemon mode. Please use the pythonw executable instead.") logger.error("More information at http://docs.python.org/2/using/windows.html.") else: Daemonizer(cherrypy.engine).subscribe() # Create PID if specified if htpc.PID: PIDFile(cherrypy.engine, htpc.PID).subscribe() def stopp_ap(): htpc.SCHED.shutdown(wait=False) stopp_ap.priority = 10 cherrypy.engine.subscribe('stop', stopp_ap) cherrypy.engine.timeout_monitor.unsubscribe() # Set static directories webdir = os.path.join(htpc.RUNDIR, htpc.TEMPLATE) favicon = os.path.join(webdir, "img/favicon.ico") app_config = { '/': { 'tools.staticdir.root': webdir, 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.gzip.on': True, 'tools.gzip.mime_types': ['text/html', 'text/plain', 'text/css', 'text/javascript', 'application/json', 'application/javascript'] }, '/js': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'css' }, '/img': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'img' }, '/favicon.ico': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticfile.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticfile.filename': favicon } } # Start the CherryPy server logger.info("Starting up webserver") print '*******************************************************************' print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.' print 'Start your browser and go to http%s://localhost:%s%s' % (protocol, htpc.PORT, htpc.WEBDIR[:-1]) print '*******************************************************************' cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)
def start(): """ Main function for starting HTTP server """ logger = logging.getLogger('htpc.server') logger.debug("Setting up to start cherrypy") # Set server ip, port and root cherrypy.config.update({ 'server.socket_host': htpc.HOST, 'server.socket_port': htpc.PORT, 'log.screen': False }) # Enable auth if username and pass is set, add to db as admin if htpc.USERNAME and htpc.PASSWORD: """ Lets see if the that username and password is already in the db""" try: user = Manageusers.selectBy(username=htpc.USERNAME).getOne() except SQLObjectNotFound: Manageusers(username=htpc.USERNAME, password=htpc.PASSWORD, role='admin') logger.debug('Updating cherrypy config, activating sessions and auth') cherrypy.config.update({ 'tools.sessions.on': True, 'tools.auth.on': True, 'tools.sessions.timeout':60 }) # Set server environment to production unless when debugging if not htpc.DEBUG: cherrypy.config.update({ 'environment': 'production' }) # Enable SSL if htpc.SSLCERT and htpc.SSLKEY: cherrypy.config.update({ 'server.ssl_module': 'builtin', 'server.ssl_certificate': htpc.SSLCERT, 'server.ssl_private_key': htpc.SSLKEY }) # Daemonize cherrypy if specified if htpc.DAEMON: if sys.platform == 'win32': logger.error("You are using Windows - I cannot setup daemon mode. Please use the pythonw executable instead.") logger.error("More information at http://docs.python.org/2/using/windows.html.") else: Daemonizer(cherrypy.engine).subscribe() # Create PID if specified if htpc.PID: PIDFile(cherrypy.engine, htpc.PID).subscribe() # Set static directories webdir = os.path.join(htpc.RUNDIR, htpc.TEMPLATE) favicon = os.path.join(webdir, "img/favicon.ico") app_config = { '/': { 'tools.staticdir.root': webdir, 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.gzip.on': True, 'tools.gzip.mime_types': ['text/html', 'text/plain', 'text/css', 'text/javascript', 'application/json', 'application/javascript'] }, '/js': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 6, 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 6, 'tools.staticdir.on': True, 'tools.staticdir.dir': 'css' }, '/img': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 6, 'tools.staticdir.on': True, 'tools.staticdir.dir': 'img' }, '/favicon.ico': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 6, 'tools.staticfile.on': True, 'tools.staticfile.filename': favicon }, } # Start the CherryPy server (remove trailing slash from webdir) logger.info("Starting up webserver") print '******************************************************' print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.' print 'Start your browser and go to http://localhost:' + str(htpc.PORT) + '/' + htpc.WEBDIR[:-1] print '******************************************************' cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)