def populate_conf_directory(): cork = Cork('example_conf', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['editor'] = 60 cork._store.roles['user'] = 50 cork._store._savejson('roles', cork._store.roles) tstamp = str(datetime.utcnow()) username = password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } username = password = '' cork._store.users[username] = { 'role': 'user', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store._save_users()
def populate_conf_directory(): cork = Cork("example_conf", initialize=True) cork._store.roles["admin"] = 100 cork._store.roles["editor"] = 60 cork._store.roles["user"] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = password = "******" cork._store.users[username] = { "role": "admin", "hash": cork._hash(username, password), "email_addr": username + "@localhost.local", "desc": username + " test user", "creation_date": tstamp, } username = password = "" cork._store.users[username] = { "role": "user", "hash": cork._hash(username, password), "email_addr": username + "@localhost.local", "desc": username + " test user", "creation_date": tstamp, } cork._store.save_users()
def run(*args): #cork (app auth) client = pymongo.MongoClient(app_settings.DATABASE_URI) db = client[app_settings.DATABASE_CORK] db.authenticate(app_settings.DATABASE_USERNAME, app_settings.DATABASE_PASSWORD, app_settings.DATABASE_MAIN) existing = db.users.find_one({"login": "******"}) if existing: return mb = MongoDBBackend(db_name=app_settings.DATABASE_CORK, username=app_settings.DATABASE_USERNAME, password=app_settings.DATABASE_PASSWORD, authdb=app_settings.DATABASE_MAIN, initialize=True) cork = Cork(backend=mb, preferred_hashing_algorithm='scrypt') admin_hash = cork._hash("admin", app_settings.ADMIN_PASSWORD) mb.users._coll.insert({ "login": "******", "email_addr": "*****@*****.**", "desc": "admin user", "role": "admin", "hash": admin_hash, "creation_date": "2012-10-28 20:50:26.286723" }) mb.roles._coll.insert({'role': 'admin', 'val': 100}) #mb.roles._coll.insert({'role': 'editor', 'val': 60}) mb.roles._coll.insert({'role': 'user', 'val': 50})
def populate_conf_directory(adminpass): print("Setting screenly admin pw to "+str(adminpass)) if not os.path.exists("/home/pi/screenly.auth"): os.mkdir("/home/pi/screenly.auth") cork = Cork('/home/pi/screenly.auth', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['editor'] = 60 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = '******' password=adminpass cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } username = password = '******' cork._store.users[username] = { 'role': 'user', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.save_users()
def populate_conf_directory(self, auth_dir): """ Creation of basic auth files. """ logger.info("Creating new authentication files, check STDOUT for the generated admin password.") cork = Cork(auth_dir, initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['access_all'] = 70 cork._store.roles['access_normalized'] = 60 cork._store.roles['public'] = 10 cork._store.save_roles() tstamp = str(datetime.utcnow()) #default admin combo: admin/admin username = '******' password = str(uuid.uuid4()) cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': 'Default administrative account', 'creation_date': tstamp } cork._store.save_users() #for security reasons we fdo not want this in the log files. print "A 'admin' account has been created with the password '{0}'".format(password) return cork
def populate_conf_directory(): cork = Cork('users', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['editor'] = 60 cork._store.roles['user'] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@gmail.com', 'desc': username + ' test user', 'creation_date': tstamp } username = password = '******' cork._store.users[username] = { 'role': 'user', 'hash': cork._hash(username, password), 'email_addr': username + '@usaid.gov', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.save_users()
def populate_conf_directory(): cork = Cork('cork_conf', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['user'] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } username = password = '******' cork._store.users[username] = { 'role': 'user', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.save_users()
def populate_conf_directory(out_dir, non_interactive): cork = Cork(out_dir, initialize=True) cork._store.roles['admin'] = 101 cork._store.roles['portal'] = 100 cork._store.roles['experimenter'] = 60 cork._store.save_roles() tstamp = str(datetime.utcnow()) stop = False while not stop: if non_interactive: choice = 'y' stop = True else: choice = input('do you want to add one user? [Y/n]') if choice.lower() == 'y' or choice.lower() == 'yes' or not choice: username, password, role = get_username_and_password( non_interactive) user_cork = { 'role': role, 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.users[username] = user_cork print("Cork user is: %s, password is %s" % (username, password)) else: stop = True cork._store.save_users()
def change_pass(pwd): sqlalchemy_backend = Cork(backend=SqlAlchemyBackend(config.db_url)) metadata = MetaData() engine = create_engine(config.db_url) metadata.bind = engine users = Table("users", metadata, extend_existing=True, autoload=True, autoload_with=engine) users.update().where(users.c.username == "transito").values( hash=sqlalchemy_backend._hash("transito", pwd)).execute()
def add_user(Base, session): Users = Base.classes.users sqlalchemy_backend = Cork(backend=SqlAlchemyBackend(config.db_url)) session.add( Users(username="******", role="admin", hash=sqlalchemy_backend._hash("transito", "transito"), email_addr="*****@*****.**", desc="operario", creation_date=str(datetime.now()), last_login=str(datetime.now()))) session.commit() session.close()
def __initialize_cork_user(username, role, password): cork = Cork(directory=get_config("api", "cork-files-path", "/etc/softfire/users"), initialize=False) user_cork = { 'role': role, 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()) } cork._store.users[username] = user_cork cork._store.save_users() logger.debug('Created cork user {} with role {}.'.format(username, role))
def add_user(Base, session): Users = Base.classes.users sqlalchemy_backend = Cork(backend=SqlAlchemyBackend(config.db_url)) session.add( Users( username="******", role="admin", hash=sqlalchemy_backend._hash("transito", "transito"), email_addr="*****@*****.**", desc="operario", creation_date=str(datetime.now()), last_login=str(datetime.now()), ) ) session.commit() session.close()
def getAAA(userdb_dir): """ Gets an authentication object for use with cork/bottle. """ # Create default json files for users if not present if not isdir(userdb_dir): makedirs(userdb_dir) if not isfile(userdb_dir + '/register.json'): with open(userdb_dir + '/register.json', 'w') as f: f.write('{}') if not isfile(userdb_dir + '/users.json'): with open(userdb_dir + '/users.json', 'w') as f: now = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f') f.write( '{"admin": {"hash": "cLzRnzbEwehP6ZzTREh3A4MXJyNo+TV8Hs4//EEbPbiDoo+dmNg22f2RJC282aSwgyWv/O6s3h42qrA6iHx8yfw=", "email_addr": "*****@*****.**", "role": "admin", "creation_date": "' + now + '", "desc": "admin test user"}}') if not isfile(userdb_dir + '/roles.json'): with open(userdb_dir + '/roles.json', 'w') as f: f.write('{"admin": 100}') aaa = Cork(userdb_dir) return aaa
def setup_dir(testdir): """Setup test directory with valid JSON files""" #dummy users for testing users = { 'admin': { 'role': 'admin' }, 'a_all': { 'role': 'access_all' }, 'a_norm': { 'role': 'access_normalized' }, 'public': { 'role': 'public' } } #set hash for all users for k, v in users.items(): v['hash'] = Cork._hash(k, 'password') with open("%s/users.json" % testdir, 'w') as f: f.write(json.dumps(users)) with open("%s/roles.json" % testdir, 'w') as f: f.write( """{"admin": 100, "access_all": 70, "access_normalized": 60,"public": 10}""" ) with open("%s/register.json" % testdir, 'w') as f: f.write("""{}""")
def test_unable_to_save(json_db_dir): bogus_dir = '/___inexisting_directory___' with pytest.raises(BackendIOException): Cork(bogus_dir, initialize=True, preferred_hashing_algorithm='PBKDF2sha1', pbkdf2_iterations=100000)
def aaa(mytmpdir): aaa = Cork( mytmpdir, smtp_server="localhost", email_sender="test@localhost", preferred_hashing_algorithm="argon2", ) return aaa
def setup(engine): Role.metadata.create_all(engine) User.metadata.create_all(engine) # setup cork auth backend = SqlAlchemyBackend(engine.url) aaa = Cork(backend=backend) setattr(__import__(__name__), 'aaa', aaa)
def __initialize_cork_role(role_name, role_level): cork = Cork(directory=get_config("api", "cork-files-path", "/etc/softfire/users"), initialize=False) cork._store.roles[role_name] = role_level cork._store.save_roles() logger.debug('Created cork role: {} with level {}.'.format( role_name, role_level))
def populate_conf_directory(): cork = Cork('conf', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['user'] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.save_users() print("Login with the username '{}' and the password '{}'. Then go to /admin, add a new admin, and delete this one.".format(username, password))
def aaa(mytmpdir): aaa = Cork( mytmpdir, smtp_server="localhost", email_sender="test@localhost", preferred_hashing_algorithm="PBKDF2sha1", pbkdf2_iterations=100000, ) return aaa
def create_test_databases(*args): create_databases_with_auth(app_settings.DATABASE_CORK) create_databases_with_auth(app_settings.DATABASE_MAIN) mb = MongoDBBackend(db_name=app_settings.DATABASE_CORK, username=app_settings.DATABASE_USERNAME, password=app_settings.DATABASE_PASSWORD, authdb=app_settings.DATABASE_MAIN, initialize=True) cork = Cork(backend=mb, preferred_hashing_algorithm='scrypt') testuser_hash = cork._hash("testuser", "testuser") mb.users._coll.insert({ "login": "******", "email_addr": "*****@*****.**", "desc": "test user", "role": "user", "hash": testuser_hash, "creation_date": "2012-10-28 20:50:26.286723" })
def create_test_users(): """Run from the 'src' folder""" cork = Cork('config', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['edit'] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = '******' password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.save_users()
def populate_conf_directory(): cork = Cork('.', initialize=True) cork._store.roles['admin'] = 100 cork._store._savejson('roles', cork._store.roles) tstamp = str(datetime.utcnow()) username = "" while not username: username = raw_input("Enter admin username: "******"" while not password: password = raw_input("Enter admin password: ") cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'creation_date': tstamp } cork._store._save_users()
def setup_cork(self): """Set up cork using environment variables.""" EMAIL = os.environ.get('EMAIL_SENDER') EMAIL_PASS = os.environ.get('EMAIL_PASSWORD') self.MONGO_DB = os.environ.get('MONGOHQ_DB') self.MONGO_URL = os.environ.get('MONGOHQ_URL') mb = MongoDBBackend(self.MONGO_DB, self.MONGO_URL) self.loginPlugin = Cork(backend=mb, email_sender=EMAIL, smtp_url='starttls://' + EMAIL + ':' + EMAIL_PASS + '@smtp.gmail.com:587')
def populate_conf_directory(self): """Populate a directory with valid configuration files, to be run just once The files are not modified by each test """ self._tmpdir = os.path.join(self._tmproot, "cork_functional_test_source") # only do this once, as advertised if os.path.exists(self._tmpdir): return os.mkdir(self._tmpdir) os.mkdir(self._tmpdir + "/example_conf") cork = Cork(os.path.join(self._tmpdir, "example_conf"), initialize=True) cork._store.roles["admin"] = 100 cork._store.roles["editor"] = 60 cork._store.roles["user"] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = password = "******" cork._store.users[username] = { "role": "admin", "hash": cork._hash(username, password), "email_addr": username + "@localhost.local", "desc": username + " test user", "creation_date": tstamp, } username = password = "" cork._store.users[username] = { "role": "user", "hash": cork._hash(username, password), "email_addr": username + "@localhost.local", "desc": username + " test user", "creation_date": tstamp, } cork._store.save_users()
def populate_conf_directory(self): """Populate a directory with valid configuration files, to be run just once The files are not modified by each test """ self._tmpdir = os.path.join(self._tmproot, "cork_functional_test_source") # only do this once, as advertised if os.path.exists(self._tmpdir): return os.mkdir(self._tmpdir) os.mkdir(self._tmpdir + "/example_conf") cork = Cork(os.path.join(self._tmpdir, "example_conf"), initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['editor'] = 60 cork._store.roles['user'] = 50 cork._store.save_roles() tstamp = str(datetime.utcnow()) username = password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } username = password = '' cork._store.users[username] = { 'role': 'user', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store.save_users()
def populate_conf_directory(): """Populate a directory with valid configuration files, to be run just once The files are not modified by each test """ global tmpdir tmpdir = "%s/cork_functional_test_source" % tmproot # only do this once, as advertised if os.path.exists(tmpdir): return os.mkdir(tmpdir) os.mkdir(tmpdir + "/example_conf") cork = Cork(tmpdir + "/example_conf", initialize=True) cork._store.roles["admin"] = 100 cork._store.roles["editor"] = 60 cork._store.roles["user"] = 50 cork._store._savejson("roles", cork._store.roles) tstamp = str(datetime.utcnow()) username = password = "******" cork._store.users[username] = { "role": "admin", "hash": cork._hash(username, password), "email_addr": username + "@localhost.local", "desc": username + " test user", "creation_date": tstamp, } username = password = "" cork._store.users[username] = { "role": "user", "hash": cork._hash(username, password), "email_addr": username + "@localhost.local", "desc": username + " test user", "creation_date": tstamp, } cork._store._save_users()
def make_user_admin(*args): username = input("Username: "******"login": username}, {"$set": { "role": "admin" }})
def populate_conf_directory(): """Populate a directory with valid configuration files, to be run just once The files are not modified by each test """ global tmpdir tmpdir = "%s/cork_functional_test_source" % tmproot # only do this once, as advertised if os.path.exists(tmpdir): return os.mkdir(tmpdir) os.mkdir(tmpdir + "/example_conf") cork = Cork(tmpdir + "/example_conf", initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['editor'] = 60 cork._store.roles['user'] = 50 cork._store._savejson('roles', cork._store.roles) tstamp = str(datetime.utcnow()) username = password = '******' cork._store.users[username] = { 'role': 'admin', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } username = password = '' cork._store.users[username] = { 'role': 'user', 'hash': cork._hash(username, password), 'email_addr': username + '@localhost.local', 'desc': username + ' test user', 'creation_date': tstamp } cork._store._save_users()
def test_initialize_storage(): aaa = Cork(testdir, initialize=True) with open("%s/users.json" % testdir) as f: assert f.readlines() == ['{}'] with open("%s/roles.json" % testdir) as f: assert f.readlines() == ['{}'] with open("%s/register.json" % testdir) as f: assert f.readlines() == ['{}'] with open("%s/views/registration_email.tpl" % testdir) as f: assert f.readlines() == [ 'Username:{{username}} Email:{{email_addr}} Code:{{registration_code}}'] with open("%s/views/password_reset_email.tpl" % testdir) as f: assert f.readlines() == [ 'Username:{{username}} Email:{{email_addr}} Code:{{reset_code}}']
def test_initialize_storage(): jb = JsonBackend(testdir, initialize=True) Cork(backend=jb, preferred_hashing_algorithm='scrypt') with open("%s/users.json" % testdir) as f: assert f.readlines() == ['{}'] with open("%s/roles.json" % testdir) as f: assert f.readlines() == ['{}'] with open("%s/register.json" % testdir) as f: assert f.readlines() == ['{}'] with open("%s/views/registration_email.tpl" % testdir) as f: assert f.readlines() == [ 'Username:{{username}} Email:{{email_addr}} Code:{{registration_code}}'] with open("%s/views/password_reset_email.tpl" % testdir) as f: assert f.readlines() == [ 'Username:{{username}} Email:{{email_addr}} Code:{{reset_code}}']
def initiate_authmgr(self): ''' Internal function to intiate authentication manager ''' self.authBackend = MongoDBBackend(db_name=CONF.mongo_conf['db'], hostname=CONF.mongo_conf['host'], port=CONF.mongo_conf['port'], initialize=False, username=CONF.mongo_conf['username'], password=CONF.mongo_conf['password']) smtp_url = CONF.smtp_url self.authmgr = Cork(backend=self.authBackend, email_sender='*****@*****.**', smtp_url=smtp_url) return self.authmgr
def get_cork_instance(): smtp_url = 'ssl://{}:{}@smtp.gmail.com:465'.format( app_settings.SMTP_USERNAME, app_settings.SMTP_PASSWORD) cork = Cork( backend=MongoDBBackend(db_name=app_settings.DATABASE_CORK, username=app_settings.DATABASE_USERNAME, password=app_settings.DATABASE_PASSWORD, authdb=app_settings.DATABASE_MAIN, initialize=False), email_sender=app_settings.SMTP_USERNAME + "@gmail.com", smtp_url=smtp_url, preferred_hashing_algorithm='scrypt', pbkdf2_iterations=10, ) return cork
def test_initialize_storage(json_db_dir): jb = JsonBackend(json_db_dir.strpath, initialize=True) Cork(backend=jb) assert json_db_dir.join('users.json').read() == '{}' assert json_db_dir.join('roles.json').read() == '{}' assert json_db_dir.join('register.json').read() == '{}' return with open("%s/views/registration_email.tpl" % testdir) as f: assert f.readlines() == [ 'Username:{{username}} Email:{{email_addr}} Code:{{registration_code}}' ] with open("%s/views/password_reset_email.tpl" % testdir) as f: assert f.readlines() == [ 'Username:{{username}} Email:{{email_addr}} Code:{{reset_code}}' ]
def populate_conf_directory(): cork = Cork('auth', initialize=True) cork._store.roles['admin'] = 100 cork._store.roles['editor'] = 60 cork._store.roles['user'] = 50 cork._store._savejson('roles', cork._store.roles) tstamp = str(datetime.utcnow()) print "Change the usernames and passwords in the code" exit() makeuser(cork, 'admin', 'CHANGEME', tstamp) makeuser(cork, 'someuser', 'CHANGEME', tstamp) makeuser(cork, 'woohoo', 'CHANGEME', tstamp) cork._store._save_users()
def test_initialize_storage(json_db_dir): jb = JsonBackend(json_db_dir.strpath, initialize=True) Cork(backend=jb, preferred_hashing_algorithm="PBKDF2sha1", pbkdf2_iterations=100000) assert json_db_dir.join("users.json").read() == "{}" assert json_db_dir.join("roles.json").read() == "{}" assert json_db_dir.join("register.json").read() == "{}" return with open("%s/views/registration_email.tpl" % testdir) as f: assert f.readlines() == [ "Username:{{username}} Email:{{email_addr}} Code:{{registration_code}}" ] with open("%s/views/password_reset_email.tpl" % testdir) as f: assert f.readlines() == [ "Username:{{username}} Email:{{email_addr}} Code:{{reset_code}}" ]
def setup_dir(testdir): """Setup test directory with valid JSON files""" # dummy users for testing users = { "admin": {"role": "admin"}, "a_all": {"role": "access_all"}, "a_norm": {"role": "access_normalized"}, "public": {"role": "public"}, } # set hash for all users for k, v in users.items(): v["hash"] = Cork._hash(k, "password") with open("%s/users.json" % testdir, "w") as f: f.write(json.dumps(users)) with open("%s/roles.json" % testdir, "w") as f: f.write("""{"admin": 100, "access_all": 70, "access_normalized": 60,"public": 10}""") with open("%s/register.json" % testdir, "w") as f: f.write("""{}""")
# Cork example web application # # The following users are already available: # admin/admin, demo/demo import bottle from beaker.middleware import SessionMiddleware from cork import Cork import logging logging.basicConfig(format='localhost - - [%(asctime)s] %(message)s', level=logging.DEBUG) log = logging.getLogger(__name__) bottle.debug(True) # Use users.json and roles.json in the local example_conf directory aaa = Cork('example_conf', email_sender='*****@*****.**', smtp_url='smtp://smtp.magnet.ie') # alias the authorization decorator with defaults authorize = aaa.make_auth_decorator(fail_redirect="/login", role="user") bypass_authorize = aaa.make_localbypass_auth_decorator(fail_redirect="/login", role="user", bypassed_addrs = ['127.0.0.0/8', '192.168.1.0/24']) import datetime app = bottle.app() session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': 'please use a random key and keep it secret!', 'session.httponly': True, 'session.timeout': 3600 * 24, # 1 day 'session.type': 'cookie', 'session.validate_key': True, }
# admin/admin, demo/demo import bottle from beaker.middleware import SessionMiddleware from cork import Cork from cork.backends import SQLiteBackend import logging logging.basicConfig(format='localhost - - [%(asctime)s] %(message)s', level=logging.DEBUG) log = logging.getLogger(__name__) bottle.debug(True) # Use users.json and roles.json in the local example_conf directory aaa = Cork('example_conf', email_sender='*****@*****.**', smtp_url='smtp://smtp.magnet.ie') def populate_backend(): b = SQLiteBackend('example.db', initialize=True) b.connection.executescript(""" INSERT INTO users (username, email_addr, desc, role, hash, creation_date) VALUES ( 'admin', '*****@*****.**', 'admin test user', 'admin', 'cLzRnzbEwehP6ZzTREh3A4MXJyNo+TV8Hs4//EEbPbiDoo+dmNg22f2RJC282aSwgyWv/O6s3h42qrA6iHx8yfw=', '2012-10-28 20:50:26.286723' );
'*****@*****.**', 'admin test user', 'admin', 'cLzRnzbEwehP6ZzTREh3A4MXJyNo+TV8Hs4//EEbPbiDoo+dmNg22f2RJC282aSwgyWv/O6s3h42qrA6iHx8yfw=', '2012-10-28 20:50:26.286723' ); INSERT INTO roles (role, level) VALUES ('special', 200); INSERT INTO roles (role, level) VALUES ('admin', 100); INSERT INTO roles (role, level) VALUES ('editor', 60); INSERT INTO roles (role, level) VALUES ('user', 50); """) return b b = populate_backend() from os import environ as E aaa = Cork(backend=b, email_sender=E['EMAIL_SENDER'], smtp_url=E['SMTP_URL']) aaa.isolation_level=None app = bottle.app() session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': 'please use a random key and keep it secret!', 'session.httponly': True, 'session.timeout': 3600 * 24, # 1 day 'session.type': 'cookie', 'session.validate_key': True, } app = SessionMiddleware(app, session_opts)
def __init__(self, datebase_name, static_file_path=None, data_dir='./data', loggly_token=None): cork_dir = os.path.join(data_dir, 'cork') beaker_dir = os.path.join(data_dir, 'beaker') bottle.TEMPLATE_PATH.insert(0,'webapi/views/') #vars which must be visible across all webapi modules shared.static_dir = static_file_path shared.plug = bottle.ext.mongo.MongoPlugin(uri="localhost", db=datebase_name, json_mongo=True) #install mongo plugin for root app install(shared_state.plug) #check if cork files exists cork_files = ['users.json', 'roles.json', 'register.json'] if not set(cork_files).issubset(set(os.listdir(cork_dir))): #if not, create them logger.info('Cork authentication files not found, creating new files.') shared.auth = self.populate_conf_directory(cork_dir) else: shared.auth = Cork(cork_dir) #admin depends on shared.auth import admin #import and mount api version 1 (stable) from webapi.api.v1 import app as api_v1 mount('/api/v1/', api_v1.app) #import and mount development version (unstable) from webapi.api.d import app as api_d mount('/api/d/', api_d.app) #must be imported AFTER mounts. if shared.static_dir is not None: import default_routes #wrap root app in beaker middleware session_opts = { 'session.type': 'file', 'session.cookie_expires': False, 'session.data_dir': beaker_dir, 'session.auto': True, #set secure attribute on cookie 'session.secure': True } self.app = bottle.app() if loggly_token: self.app = Loggly(bottle.app(), loggly_token) self.app = SessionMiddleware(self.app, session_opts) root_app = bottle.app() #setup logging hooks @root_app.hook('before_request') @api_d.app.hook('before_request') @api_v1.app.hook('before_request') def log_request(): user_agent = "" if 'HTTP_USER_AGENT' in bottle.request.environ: user_agent = bottle.request.environ['HTTP_USER_AGENT'] if 'REMOTE_ADDR' in bottle.request.environ: remote_addr = bottle.request.environ['REMOTE_ADDR'] else: remote_addr = "" if 'beaker.session' in bottle.request.environ: session = bottle.request.environ.get('beaker.session') username = session.get('username', None) else: username = "******" logger.info("[{0}/{1}] {2} {3} ({4})".format(remote_addr, username, request.method, request.fullpath, user_agent)) def return_text(self, e): return e.status #make sure error pages for API are pure text api_d.app.default_error_handler = types.MethodType(return_text, self) api_v1.app.default_error_handler = types.MethodType(return_text, self)
def main(): global aaa global app global content_path setproctitle('shoebill') args = parse_args() site_path = os.path.abspath(args.directory) content_path = os.path.join(site_path, 'content') check_site_dir(site_path, content_path) print "Starting Shoebill..." setup_git_repo(site_path) if not args.no_auth: # Setup authentication if not aaa_available: print """Error: the Beaker and/or Cork libraries are missing. \ \nPlease install them or disable authentication using --no-auth""" sys.exit(1) auth_dir = os.path.join(site_path, '.shoebill_auth') if not os.path.isdir(auth_dir): print "Creating authentication data" os.mkdir(auth_dir) token = gen_random_token(21) with open(os.path.join(auth_dir, 'token'), 'w') as f: f.write(token) aaa = Cork(auth_dir, initialize=True) aaa._store.roles['admin'] = 100 aaa._store.roles['editor'] = 50 aaa._store.save_roles() tstamp = str(datetime.utcnow()) admin_password = gen_random_token(6) aaa._store.users['admin'] = { 'role': 'admin', 'hash': aaa._hash('admin', admin_password), 'email_addr': '', 'desc': 'admin', 'creation_date': tstamp, '_accessed_time': tstamp, 'last_login': tstamp } aaa._store.save_users() print "\n", "*" * 32, "\n" print "Initialized user 'admin' with password '%s'" % admin_password print "\n", "*" * 32, "\n" else: aaa = Cork(auth_dir) if aaa: # Sessions are enabled only if authentication is enabled with open(os.path.join(auth_dir, 'token')) as f: session_encrypt_key = f.read() session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': session_encrypt_key, 'session.httponly': True, 'session.timeout': 3600 * 24, # 1 day 'session.type': 'cookie', 'session.validate_key': True, } wrapped_app = SessionMiddleware(app, session_opts) bottle.run(wrapped_app, host=args.host, port=args.port, debug=args.debug, reloader=args.debug, server='auto') else: bottle.run(app, host=args.host, port=args.port, debug=args.debug, reloader=args.debug, server='auto')
def test_unable_to_save(): bogus_dir = '/___inexisting_directory___' Cork(bogus_dir, initialize=True)
class AddressServer(Application): """ This class is the gunicorn wrapper to serve up bottle. Strongly borrowed from: http://damianzaremba.co.uk/2012/08/running-a-wsgi- app-via-gunicorn-from-python/ """ def __init__(self, options={}): self.usage = None self.callable = None self.prog = None self.options = options self.do_load_config() self.setup_cork() super(AddressServer, self).__init__() self.app = Bottle() self.add_routes() self.add_middleware() def setup_cork(self): """Set up cork using environment variables.""" EMAIL = os.environ.get('EMAIL_SENDER') EMAIL_PASS = os.environ.get('EMAIL_PASSWORD') self.MONGO_DB = os.environ.get('MONGOHQ_DB') self.MONGO_URL = os.environ.get('MONGOHQ_URL') mb = MongoDBBackend(self.MONGO_DB, self.MONGO_URL) self.loginPlugin = Cork(backend=mb, email_sender=EMAIL, smtp_url='starttls://' + EMAIL + ':' + EMAIL_PASS + '@smtp.gmail.com:587') def add_middleware(self): """Set up the session middleware.""" ENCRYPT_KEY = os.environ.get('ENCRYPT_KEY') session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': ENCRYPT_KEY, 'session.httponly': True, 'session.timeout': 3600 * 24, # 1 day 'session.type': 'cookie', 'session.validate_key': True, } self.app = SessionMiddleware(self.app, session_opts) def add_routes(self): """Add all the application routes.""" self.app.route(LOGIN_PATH, 'GET', callback=get_login) self.app.route(LOGIN_PATH, 'POST', callback=post_login, apply=self.add_login_plugin) self.app.route('/logout', 'GET', callback=logout, apply=self.add_login_plugin) self.app.route('/register', 'GET', callback=get_register, apply=self.add_login_plugin) self.app.route('/register', 'POST', callback=post_register, apply=self.add_login_plugin) self.app.route(VALIDATE_REGISTRATION_PATH + '/<registration_code>', 'GET', callback=validate_registration, apply=self.add_login_plugin) self.app.route(CHANGE_PASSWORD_PATH + '/<reset_code>', 'GET', callback=get_change_password) self.app.route(CHANGE_PASSWORD_PATH, 'POST', callback=post_change_password, apply=self.add_login_plugin) self.app.route('/reset_password', 'GET', callback=get_reset_password) self.app.route('/reset_password', 'POST', callback=post_reset_password, apply=self.add_login_plugin) self.app.route('/', 'GET', callback=index, apply=self.check_login) self.app.route('/addresses', 'GET', callback=get_addresses, apply=self.check_login) self.app.route('/addresses', 'POST', callback=post_addresses, apply=self.check_login) self.app.route('/addresses', 'PUT', callback=put_addresses, apply=self.check_login) self.app.route('/addresses/<deleteId>', 'DELETE', callback=delete_addresses, apply=self.check_login) self.app.route('/csv', 'GET', callback=csv_export, apply=self.check_login) self.app.route('/christmas_card', 'GET', callback=christmas_card_csv_export, apply=self.check_login) # self.app.route('/import_csv', 'GET', callback=csv_import, # apply=self.check_login) self.app.route('/js/<filename>', 'GET', callback=js_static) self.app.route('/css/<filename>', 'GET', callback=css_static) def init(self, *args): """Add any options passed in to the config. :param *args: the arguments of the application :returns: config object :rtype: dict """ cfg = {} for k, v in self.options.items(): if k.lower() in self.cfg.settings and v is not None: cfg[k.lower()] = v return cfg def load(self): """Load and return the bottle app.""" return self.app @hook('before_request') def check_login(self, fn): """Hook for checking the login before doing logic. :param fn: the function to call if the user is logged in :returns: the wrapped function :rtype: def """ def check_uid(**kwargs): self.loginPlugin.require(fail_redirect=LOGIN_PATH) kwargs["helper"] = AddressModel(self.MONGO_URL, self.MONGO_DB) kwargs["userName"] = self.loginPlugin.current_user.username return fn(**kwargs) return check_uid @hook('before_request') def add_login_plugin(self, fn): """Hook for adding the plugin information. :param fn: the function to pass the plugin :returns: the wrapped function :rtype: def """ def add_plugin(**kwargs): kwargs["loginPlugin"] = self.loginPlugin return fn(**kwargs) return add_plugin
from beaker.middleware import SessionMiddleware from cork import Cork import logging bottle.TEMPLATES.clear() logging.basicConfig(format='localhost - - [%(asctime)s] %(message)s', level=logging.DEBUG) log = logging.getLogger(__name__) bottle.debug(True) # Use users.json and roles.json in the local example_conf directory #aaa = Cork('/home/cwags/cwagswebforms/example_conf', email_sender='*****@*****.**', smtp_url='startttls://[email protected]:[email protected]:587') #should make it use sqlite from cork.backends import SQLiteBackend sb = SQLiteBackend('cwags.sqlite') aaa = Cork(backend=sb) # alias the authorization decorator with defaults authorize = aaa.make_auth_decorator(fail_redirect="/login", role="user") import datetime app = bottle.app() session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': 'please use a random key and keep it secret!', 'session.httponly': True, 'session.timeout': 3600 * 24, # 1 day 'session.type': 'cookie', 'session.validate_key': True, } app = SessionMiddleware(app, session_opts)
import db import queries import assets_helper from utils import json_dump from utils import get_node_ip from utils import validate_url from utils import url_fails from utils import get_video_duration from settings import settings, DEFAULTS get_current_time = datetime.utcnow aaa = Cork('/home/pi/screenly.auth') for u in aaa.list_users(): print str(u) ################################ # Utilities ################################ def make_json_response(obj): response.content_type = "application/json" return json_dump(obj) def api_error(error): response.content_type = "application/json"
import sys import os from datetime import datetime from cork import Cork try: os.mkdir("authconf") except OSError: pass cork = Cork("authconf", initialize=True) cork._store.roles["user"] = 50 cork._store.save_roles() username = sys.argv[1] password = sys.argv[2] cork._store.users[username] = { "role": "user", "hash": cork._hash(username, password), "email_addr": "", "desc": "", "creation_date": str(datetime.utcnow()), } cork._store.save_users() print "Generated directory %s%sauthconf" % (os.getcwd(), os.sep)
Created by: Rui Carmo <https://github.com/rcarmo> Description: Authentication and Authorization for the Codebits digital signage system, modeled on the Cork sample app. """ import bottle, logging from cork import Cork from config import settings log = logging.getLogger() base_url = settings.http.base_url # Use users.json and roles.json in the local 'etc' directory aaa = Cork('etc', email_sender='*****@*****.**', smtp_server='127.0.0.1') authorize = aaa.make_auth_decorator(fail_redirect=base_url+'/auth/unauthorized') def auth(fail_redirect=base_url+'/auth/login'): """Decorator for wrapping a route into a simple authentication test""" def _auth(f): def _inner(*args, **kwargs): aaa.require(fail_redirect=fail_redirect) return f(*args, **kwargs) return _inner return _auth """