def test_sql_json_has_access(self): main_db = get_main_database(db.session) security_manager.add_permission_view_menu('database_access', main_db.perm) db.session.commit() main_db_permission_view = (db.session.query( ab_models.PermissionView).join(ab_models.ViewMenu).join( ab_models.Permission ).filter(ab_models.ViewMenu.name == '[main].(id:1)').filter( ab_models.Permission.name == 'database_access').first()) astronaut = security_manager.add_role('Astronaut') security_manager.add_permission_role(astronaut, main_db_permission_view) # Astronaut role is Gamma + sqllab + main db permissions for perm in security_manager.find_role('Gamma').permissions: security_manager.add_permission_role(astronaut, perm) for perm in security_manager.find_role('sql_lab').permissions: security_manager.add_permission_role(astronaut, perm) gagarin = security_manager.find_user('gagarin') if not gagarin: security_manager.add_user('gagarin', 'Iurii', 'Gagarin', '*****@*****.**', astronaut, password='******') data = self.run_sql('SELECT * FROM ab_user', '3', user_name='gagarin') db.session.query(Query).delete() db.session.commit() self.assertLess(0, len(data['data']))
def create_user_with_roles(username: str, roles: List[str], should_create_roles: bool = False): user_to_create = security_manager.find_user(username) if not user_to_create: security_manager.add_user( username, username, username, f"{username}@superset.com", security_manager.find_role("Gamma"), # it needs a role password="******", ) db.session.commit() user_to_create = security_manager.find_user(username) assert user_to_create user_to_create.roles = [] for chosen_user_role in roles: if should_create_roles: ## copy role from gamma but without data permissions security_manager.copy_role("Gamma", chosen_user_role, merge=False) user_to_create.roles.append( security_manager.find_role(chosen_user_role)) db.session.commit() return user_to_create
def test_sql_json_has_access(self): examples_db = get_example_database() examples_db_permission_view = security_manager.add_permission_view_menu( "database_access", examples_db.perm) astronaut = security_manager.add_role("Astronaut") security_manager.add_permission_role(astronaut, examples_db_permission_view) # Astronaut role is Gamma + sqllab + db permissions for perm in security_manager.find_role("Gamma").permissions: security_manager.add_permission_role(astronaut, perm) for perm in security_manager.find_role("sql_lab").permissions: security_manager.add_permission_role(astronaut, perm) gagarin = security_manager.find_user("gagarin") if not gagarin: security_manager.add_user( "gagarin", "Iurii", "Gagarin", "*****@*****.**", astronaut, password="******", ) data = self.run_sql(QUERY_1, "3", user_name="gagarin") db.session.query(Query).delete() db.session.commit() self.assertLess(0, len(data["data"]))
def test_sql_json_has_access(self): main_db = self.get_main_database(db.session) security_manager.add_permission_view_menu('database_access', main_db.perm) db.session.commit() main_db_permission_view = ( db.session.query(ab_models.PermissionView) .join(ab_models.ViewMenu) .join(ab_models.Permission) .filter(ab_models.ViewMenu.name == '[main].(id:1)') .filter(ab_models.Permission.name == 'database_access') .first() ) astronaut = security_manager.add_role('Astronaut') security_manager.add_permission_role(astronaut, main_db_permission_view) # Astronaut role is Gamma + sqllab + main db permissions for perm in security_manager.find_role('Gamma').permissions: security_manager.add_permission_role(astronaut, perm) for perm in security_manager.find_role('sql_lab').permissions: security_manager.add_permission_role(astronaut, perm) gagarin = security_manager.find_user('gagarin') if not gagarin: security_manager.add_user( 'gagarin', 'Iurii', 'Gagarin', '*****@*****.**', astronaut, password='******') data = self.run_sql('SELECT * FROM ab_user', '3', user_name='gagarin') db.session.query(Query).delete() db.session.commit() self.assertLess(0, len(data['data']))
def test_sql_json_has_access(self): main_db = get_main_database() security_manager.add_permission_view_menu("database_access", main_db.perm) db.session.commit() main_db_permission_view = (db.session.query( ab_models.PermissionView).join(ab_models.ViewMenu).join( ab_models.Permission ).filter(ab_models.ViewMenu.name == "[main].(id:1)").filter( ab_models.Permission.name == "database_access").first()) astronaut = security_manager.add_role("Astronaut") security_manager.add_permission_role(astronaut, main_db_permission_view) # Astronaut role is Gamma + sqllab + main db permissions for perm in security_manager.find_role("Gamma").permissions: security_manager.add_permission_role(astronaut, perm) for perm in security_manager.find_role("sql_lab").permissions: security_manager.add_permission_role(astronaut, perm) gagarin = security_manager.find_user("gagarin") if not gagarin: security_manager.add_user( "gagarin", "Iurii", "Gagarin", "*****@*****.**", astronaut, password="******", ) data = self.run_sql("SELECT * FROM ab_user", "3", user_name="gagarin") db.session.query(Query).delete() db.session.commit() self.assertLess(0, len(data["data"]))
def load_test_users_run(): """ Loads admin, alpha, and gamma user for testing purposes Syncs permissions for those users/roles """ if config.get('TESTING'): security_manager.sync_role_definitions() gamma_sqllab_role = security_manager.add_role('gamma_sqllab') for perm in security_manager.find_role('Gamma').permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) utils.get_or_create_main_db() db_perm = utils.get_main_database(security_manager.get_session).perm security_manager.merge_perm('database_access', db_perm) db_pvm = security_manager.find_permission_view_menu( view_menu_name=db_perm, permission_name='database_access') gamma_sqllab_role.permissions.append(db_pvm) for perm in security_manager.find_role('sql_lab').permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) admin = security_manager.find_user('admin') if not admin: security_manager.add_user( 'admin', 'admin', ' user', '*****@*****.**', security_manager.find_role('Admin'), password='******') gamma = security_manager.find_user('gamma') if not gamma: security_manager.add_user( 'gamma', 'gamma', 'user', '*****@*****.**', security_manager.find_role('Gamma'), password='******') gamma2 = security_manager.find_user('gamma2') if not gamma2: security_manager.add_user( 'gamma2', 'gamma2', 'user', '*****@*****.**', security_manager.find_role('Gamma'), password='******') gamma_sqllab_user = security_manager.find_user('gamma_sqllab') if not gamma_sqllab_user: security_manager.add_user( 'gamma_sqllab', 'gamma_sqllab', 'user', '*****@*****.**', gamma_sqllab_role, password='******') alpha = security_manager.find_user('alpha') if not alpha: security_manager.add_user( 'alpha', 'alpha', 'user', '*****@*****.**', security_manager.find_role('Alpha'), password='******') security_manager.get_session.commit()
def _create_user(username: str, role: str = "Admin", password: str = "general"): security_manager.add_user( username, "firstname", "lastname", "*****@*****.**", security_manager.find_role(role), password, ) return security_manager.find_user(username)
def login(self): role_name = base_role_names[request.host.split(".")[0]] username = f'{request.environ["HTTP_SSO_PROFILE_USER_ID"]}--{role_name}' email_parts = request.environ["HTTP_SSO_PROFILE_EMAIL"].split("@") email_parts[0] += f"+{role_name.lower()}" email = "@".join(email_parts) redirect_url = request.args.get("next", self.appbuilder.get_url_for_index) # If user already logged in, redirect to index... if g.user is not None and g.user.is_authenticated: return redirect(redirect_url) app = self.appbuilder.get_app if role_name == "Admin": is_admin = request.headers["Sso-Profile-Email"] in app.config[ "ADMIN_USERS"] if not is_admin: return make_response({}, 401) # In flask, when a user is not authenticated or lacks permissions for a page they # they are redirected (to either the index or login page), and a flash message is added # to the session saying "Access is denied". # So, in the case when a public (unauthed) DW user tries to view a DW embedded dashboard, # they will be redirected to this login flow and flask will add the access denied # message to their session. There is no easy way around this so in this specific # case clear the message queue before the public user is redirected to the dashboard if (role_name == "Public" and redirect_url != self.appbuilder.get_url_for_index and "_flashes" in session): session["_flashes"].clear() # ... else if user exists but not logged in, update details, log in, and redirect to index user = security_manager.find_user(username=username) if user is not None: user.first_name = request.headers["Sso-Profile-First-Name"] user.last_name = f'{request.headers["Sso-Profile-Last-Name"]} ({role_name})' user.email = email security_manager.update_user(user) login_user(user) return redirect(redirect_url) # ... else create user, login, and redirect to index user = security_manager.add_user( username=username, first_name=request.headers["Sso-Profile-First-Name"], last_name= f'{request.headers["Sso-Profile-Last-Name"]} ({role_name})', email=email, role=security_manager.find_role(role_name), ) if not user: return make_response( f"Unable to find or create a user with role {role_name}", 500) login_user(user) return redirect(redirect_url)
def create_user_with_roles(username: str, roles: List[str]): user_to_create = security_manager.find_user(username) if not user_to_create: security_manager.add_user( username, username, username, f"{username}@superset.com", security_manager.find_role("Gamma"), # it needs a role password="******", ) db.session.commit() user_to_create = security_manager.find_user(username) assert user_to_create user_to_create.roles = [security_manager.find_role(r) for r in roles] db.session.commit()
def test_slices_V2(self): # Add explore-v2-beta role to admin user # Test all slice urls as user with with explore-v2-beta role security_manager.add_role('explore-v2-beta') security_manager.add_user( 'explore_beta', 'explore_beta', ' user', '*****@*****.**', security_manager.find_role('explore-v2-beta'), password='******') self.login(username='******', password='******') Slc = models.Slice urls = [] for slc in db.session.query(Slc).all(): urls += [ (slc.slice_name, 'slice_url', slc.slice_url), ] for name, method, url in urls: print('[{name}]/[{method}]: {url}'.format(**locals())) response = self.client.get(url)
def create_user( username: str, password: str, role_name: str, first_name: str = "admin", last_name: str = "user", email: str = "*****@*****.**", ) -> Union[ab_models.User, bool]: role_admin = security_manager.find_role(role_name) return security_manager.add_user(username, first_name, last_name, email, role_admin, password)
def ta_user_creation(self) -> Response: """ Return the csrf token --- get: description: >- Fetch the CSRF token responses: 200: description: Result contains the CSRF token content: application/json: schema: type: object properties: result: type: string 401: $ref: '#/components/responses/401' 500: $ref: '#/components/responses/500' """ data = request.json role_name = '' # admin, user, sub if data['type'] == 'admin': role_name = 'Admin' elif data['type'] == 'user': role_name = data['key'] elif data['type'] == 'sub': role_name = data['key'] + '_sub' role = sm.find_role(role_name) if role is None: datasourceIds = data['datasourceIds'].split(',') datasourceNames = data['datasourceNames'].split(',') isUser = data['type'] = 'user' self.create_role(role_name, datasourceIds, datasourceNames, isUser) role_names = [role_name] if role_name != 'Admin': role_names.append('Gamma') user = sm.add_user(data['username'], 'DS2G', "User", data['email'], list(map(lambda rn: sm.find_role(rn), role_names)), password=data['password']) sm.get_session.commit() return self.response(200, id=user.id)
def test_slices_V2(self): # Add explore-v2-beta role to admin user # Test all slice urls as user with with explore-v2-beta role security_manager.add_role("explore-v2-beta") security_manager.add_user( "explore_beta", "explore_beta", " user", "*****@*****.**", security_manager.find_role("explore-v2-beta"), password="******", ) self.login(username="******", password="******") Slc = Slice urls = [] for slc in db.session.query(Slc).all(): urls += [(slc.slice_name, "slice_url", slc.slice_url)] for name, method, url in urls: print(f"[{name}]/[{method}]: {url}") self.client.get(url)
def setUpClass(cls): try: os.remove(app.config.get('SQL_CELERY_DB_FILE_PATH')) except OSError as e: app.logger.warn(str(e)) try: os.remove(app.config.get('SQL_CELERY_RESULTS_DB_FILE_PATH')) except OSError as e: app.logger.warn(str(e)) security_manager.sync_role_definitions() worker_command = BASE_DIR + '/bin/superset worker' subprocess.Popen( worker_command, shell=True, stdout=subprocess.PIPE) admin = security_manager.find_user('admin') if not admin: security_manager.add_user( 'admin', 'admin', ' user', '*****@*****.**', security_manager.find_role('Admin'), password='******') cli.load_examples_run(load_test_data=True)
def setUpClass(cls): try: os.remove(app.config.get('SQL_CELERY_DB_FILE_PATH')) except OSError as e: app.logger.warn(str(e)) try: os.remove(app.config.get('SQL_CELERY_RESULTS_DB_FILE_PATH')) except OSError as e: app.logger.warn(str(e)) security_manager.sync_role_definitions() worker_command = BASE_DIR + '/bin/superset worker' subprocess.Popen( worker_command, shell=True, stdout=subprocess.PIPE) admin = security_manager.find_user('admin') if not admin: security_manager.add_user( 'admin', 'admin', ' user', '*****@*****.**', security_manager.find_role('Admin'), password='******') cli.load_examples(load_test_data=True)
def init(): """Inits the Superset application""" utils.get_or_create_main_db() security_manager.sync_role_definitions() role_admin = security_manager.find_role(security_manager.auth_role_admin) username = firstname = lastname = password = "******" email = "*****@*****.**" user = security_manager.find_user(username) if user is None: user = security_manager.add_user(username, firstname, lastname, email, role_admin, password) if user: print(Fore.GREEN + 'Admin User {0} created.'.format(username)) else: print(Fore.RED + 'No user created an error occured')
def bootstrap(): # always run migrations first db_upgrade() # always gitbase script to update datasource if it was changed in env var dbobj = get_or_create_datasource('gitbase', conf.get('GITBASE_DATABASE_URI'), allow_run_async=True, allow_dml=True) create_datasource_tables(dbobj, conf.get('GITBASE_DB')) # add metadata data source only in sync mode if conf.get('SYNC_MODE'): dbobj = get_or_create_datasource('metadata', conf.get('METADATA_DATABASE_URI')) create_datasource_tables(dbobj, conf.get('METADATA_DB')) # initialize database if empty users = [u.username for u in security_manager.get_all_users()] if not conf.get('DEFAULT_USERNAME') in users: # Create an admin user role_admin = security_manager.find_role( security_manager.auth_role_admin) admin_user = security_manager.add_user(conf.get('DEFAULT_USERNAME'), os.environ['ADMIN_FIRST_NAME'], os.environ['ADMIN_LAST_NAME'], os.environ['ADMIN_EMAIL'], role_admin, os.environ['ADMIN_PASSWORD']) # Create default roles and permissions utils.get_or_create_main_db() security_manager.sync_role_definitions() # set admin user as a current user g.user = admin_user # Add dashboards dashboards_root = '/home/superset/dashboards' import_dashboard(dashboards_root + '/gitbase/overview.json') if conf.get('SYNC_MODE'): import_dashboard(dashboards_root + '/metadata/welcome.json') import_dashboard(dashboards_root + '/metadata/collaboration.json') else: import_dashboard(dashboards_root + '/gitbase/welcome.json') # set welcome dashboard as a default set_welcome_dashboard(conf.get('DEFAULT_DASHBOARD_ID'), admin_user)
def __init__(self, *args, **kwargs): if ( self.requires_examples and not os.environ.get('examples_loaded') ): logging.info('Loading examples') cli.load_examples(load_test_data=True) logging.info('Done loading examples') security_manager.sync_role_definitions() os.environ['examples_loaded'] = '1' else: security_manager.sync_role_definitions() super(SupersetTestCase, self).__init__(*args, **kwargs) self.client = app.test_client() self.maxDiff = None gamma_sqllab_role = security_manager.add_role('gamma_sqllab') for perm in security_manager.find_role('Gamma').permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) utils.get_or_create_main_db() db_perm = self.get_main_database(security_manager.get_session).perm security_manager.merge_perm('database_access', db_perm) db_pvm = security_manager.find_permission_view_menu( view_menu_name=db_perm, permission_name='database_access') gamma_sqllab_role.permissions.append(db_pvm) for perm in security_manager.find_role('sql_lab').permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) admin = security_manager.find_user('admin') if not admin: security_manager.add_user( 'admin', 'admin', ' user', '*****@*****.**', security_manager.find_role('Admin'), password='******') gamma = security_manager.find_user('gamma') if not gamma: security_manager.add_user( 'gamma', 'gamma', 'user', '*****@*****.**', security_manager.find_role('Gamma'), password='******') gamma2 = security_manager.find_user('gamma2') if not gamma2: security_manager.add_user( 'gamma2', 'gamma2', 'user', '*****@*****.**', security_manager.find_role('Gamma'), password='******') gamma_sqllab_user = security_manager.find_user('gamma_sqllab') if not gamma_sqllab_user: security_manager.add_user( 'gamma_sqllab', 'gamma_sqllab', 'user', '*****@*****.**', gamma_sqllab_role, password='******') alpha = security_manager.find_user('alpha') if not alpha: security_manager.add_user( 'alpha', 'alpha', 'user', '*****@*****.**', security_manager.find_role('Alpha'), password='******') security_manager.get_session.commit() # create druid cluster and druid datasources session = db.session cluster = ( session.query(DruidCluster) .filter_by(cluster_name='druid_test') .first() ) if not cluster: cluster = DruidCluster(cluster_name='druid_test') session.add(cluster) session.commit() druid_datasource1 = DruidDatasource( datasource_name='druid_ds_1', cluster_name='druid_test', ) session.add(druid_datasource1) druid_datasource2 = DruidDatasource( datasource_name='druid_ds_2', cluster_name='druid_test', ) session.add(druid_datasource2) session.commit()
def __init__(self, *args, **kwargs): if (self.requires_examples and not os.environ.get('examples_loaded')): logging.info('Loading examples') cli.load_examples_run(load_test_data=True) logging.info('Done loading examples') security_manager.sync_role_definitions() os.environ['examples_loaded'] = '1' else: security_manager.sync_role_definitions() super(SupersetTestCase, self).__init__(*args, **kwargs) self.client = app.test_client() self.maxDiff = None gamma_sqllab_role = security_manager.add_role('gamma_sqllab') for perm in security_manager.find_role('Gamma').permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) utils.get_or_create_main_db() db_perm = self.get_main_database(security_manager.get_session).perm security_manager.merge_perm('database_access', db_perm) db_pvm = security_manager.find_permission_view_menu( view_menu_name=db_perm, permission_name='database_access') gamma_sqllab_role.permissions.append(db_pvm) for perm in security_manager.find_role('sql_lab').permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) admin = security_manager.find_user('admin') if not admin: security_manager.add_user('admin', 'admin', ' user', '*****@*****.**', security_manager.find_role('Admin'), password='******') gamma = security_manager.find_user('gamma') if not gamma: security_manager.add_user('gamma', 'gamma', 'user', '*****@*****.**', security_manager.find_role('Gamma'), password='******') gamma2 = security_manager.find_user('gamma2') if not gamma2: security_manager.add_user('gamma2', 'gamma2', 'user', '*****@*****.**', security_manager.find_role('Gamma'), password='******') gamma_sqllab_user = security_manager.find_user('gamma_sqllab') if not gamma_sqllab_user: security_manager.add_user('gamma_sqllab', 'gamma_sqllab', 'user', '*****@*****.**', gamma_sqllab_role, password='******') alpha = security_manager.find_user('alpha') if not alpha: security_manager.add_user('alpha', 'alpha', 'user', '*****@*****.**', security_manager.find_role('Alpha'), password='******') security_manager.get_session.commit() # create druid cluster and druid datasources session = db.session cluster = (session.query(DruidCluster).filter_by( cluster_name='druid_test').first()) if not cluster: cluster = DruidCluster(cluster_name='druid_test') session.add(cluster) session.commit() druid_datasource1 = DruidDatasource( datasource_name='druid_ds_1', cluster_name='druid_test', ) session.add(druid_datasource1) druid_datasource2 = DruidDatasource( datasource_name='druid_ds_2', cluster_name='druid_test', ) session.add(druid_datasource2) session.commit()
def load_test_users_run(): """ Loads admin, alpha, and gamma user for testing purposes Syncs permissions for those users/roles """ if config.get("TESTING"): security_manager.sync_role_definitions() gamma_sqllab_role = security_manager.add_role("gamma_sqllab") for perm in security_manager.find_role("Gamma").permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) utils.get_or_create_main_db() db_perm = utils.get_main_database().perm security_manager.add_permission_view_menu("database_access", db_perm) db_pvm = security_manager.find_permission_view_menu( view_menu_name=db_perm, permission_name="database_access" ) gamma_sqllab_role.permissions.append(db_pvm) for perm in security_manager.find_role("sql_lab").permissions: security_manager.add_permission_role(gamma_sqllab_role, perm) admin = security_manager.find_user("admin") if not admin: security_manager.add_user( "admin", "admin", " user", "*****@*****.**", security_manager.find_role("Admin"), password="******", ) gamma = security_manager.find_user("gamma") if not gamma: security_manager.add_user( "gamma", "gamma", "user", "*****@*****.**", security_manager.find_role("Gamma"), password="******", ) gamma2 = security_manager.find_user("gamma2") if not gamma2: security_manager.add_user( "gamma2", "gamma2", "user", "*****@*****.**", security_manager.find_role("Gamma"), password="******", ) gamma_sqllab_user = security_manager.find_user("gamma_sqllab") if not gamma_sqllab_user: security_manager.add_user( "gamma_sqllab", "gamma_sqllab", "user", "*****@*****.**", gamma_sqllab_role, password="******", ) alpha = security_manager.find_user("alpha") if not alpha: security_manager.add_user( "alpha", "alpha", "user", "*****@*****.**", security_manager.find_role("Alpha"), password="******", ) security_manager.get_session.commit()