def api_delete_apikey(apikey_id): apikey = ApiKey.query.get(apikey_id) if not apikey: abort(404) logging.debug(g.user.role.name) if g.user.role.name not in ['Administrator', 'Operator']: apikeys = g.user.get_apikeys() user_domains_obj_list = g.user.get_domain().all() apikey_domains_obj_list = apikey.domains user_domains_list = [item.name for item in user_domains_obj_list] apikey_domains_list = [item.name for item in apikey_domains_obj_list] apikeys_ids = [apikey_item.id for apikey_item in apikeys] inter = set(apikey_domains_list).intersection(set(user_domains_list)) if not (len(inter) == len(apikey_domains_list)): msg = "You don't have access to some domains apikey belongs to" logging.error(msg) raise DomainAccessForbidden(message=msg) if apikey_id not in apikeys_ids: raise DomainAccessForbidden() try: apikey.delete() except Exception as e: logging.error('Error: {0}'.format(e)) abort(500) return '', 204
def api_generate_apikey(): data = request.get_json() description = None role_name = None apikey = None domain_obj_list = [] abort(400) if 'domains' not in data else None abort(400) if not isinstance(data['domains'], (list, )) else None abort(400) if 'role' not in data else None description = data['description'] if 'description' in data else None role_name = data['role'] domains = data['domains'] if role_name == 'User' and len(domains) == 0: logging.error("Apikey with User role must have domains") raise ApiKeyNotUsable() elif role_name == 'User': domain_obj_list = Domain.query.filter(Domain.name.in_(domains)).all() if len(domain_obj_list) == 0: msg = "One of supplied domains does not exists" logging.error(msg) raise DomainNotExists(message=msg) if g.user.role.name not in ['Administrator', 'Operator']: # domain list of domain api key should be valid for # if not any domain error # role of api key, user cannot assign role above for api key if role_name != 'User': msg = "User cannot assign other role than User" logging.error(msg) raise NotEnoughPrivileges(message=msg) user_domain_obj_list = g.user.get_domains() domain_list = [item.name for item in domain_obj_list] user_domain_list = [item.name for item in user_domain_obj_list] logging.debug("Input domain list: {0}".format(domain_list)) logging.debug("User domain list: {0}".format(user_domain_list)) inter = set(domain_list).intersection(set(user_domain_list)) if not (len(inter) == len(domain_list)): msg = "You don't have access to one of domains" logging.error(msg) raise DomainAccessForbidden(message=msg) apikey = ApiKey(desc=description, role_name=role_name, domains=domain_obj_list) try: apikey.create() except Exception as e: logging.error('Error: {0}'.format(e)) raise ApiKeyCreateFail(message='Api key create failed') return json.dumps(apikey_plain_schema.dump([apikey])), 201
def decorated_function(*args, **kwargs): if g.user.role.name not in [ 'Administrator', 'Operator' ] and not Setting().get('allow_user_create_domain'): msg = "User {0} does not have enough privileges to create domain" logging.error(msg.format(g.user.username)) raise NotEnoughPrivileges() return f(*args, **kwargs)
def initial_apikey_data(): pdns_proto = os.environ['PDNS_PROTO'] pdns_host = os.environ['PDNS_HOST'] pdns_port = os.environ['PDNS_PORT'] pdns_api_url = '{0}://{1}:{2}'.format(pdns_proto, pdns_host, pdns_port) api_url_setting = Setting('pdns_api_url', pdns_api_url) api_key_setting = Setting('pdns_api_key', os.environ['PDNS_API_KEY']) allow_create_domain_setting = Setting('allow_user_create_domain', True) try: with app.app_context(): flask_migrate.upgrade() db.session.add(api_url_setting) db.session.add(api_key_setting) db.session.add(allow_create_domain_setting) test_user_apikey = app.config.get('TEST_USER_APIKEY') test_admin_apikey = app.config.get('TEST_ADMIN_APIKEY') dummy_apikey = ApiKey( desc="dummy", role_name="Administrator" ) admin_key = dummy_apikey.get_hashed_password( plain_text_password=test_admin_apikey ).decode('utf-8') admin_apikey = ApiKey( key=admin_key, desc="test admin apikey", role_name="Administrator" ) admin_apikey.create() user_key = dummy_apikey.get_hashed_password( plain_text_password=test_user_apikey ).decode('utf-8') user_apikey = ApiKey( key=user_key, desc="test user apikey", role_name="User" ) user_apikey.create() except Exception as e: logging.error("Unexpected ERROR: {0}".format(e)) raise e yield db.session.close() os.unlink(app.config['TEST_DB_LOCATION'])
def initial_data(): pdns_proto = os.environ['PDNS_PROTO'] pdns_host = os.environ['PDNS_HOST'] pdns_port = os.environ['PDNS_PORT'] pdns_api_url = '{0}://{1}:{2}'.format(pdns_proto, pdns_host, pdns_port) api_url_setting = Setting('pdns_api_url', pdns_api_url) api_key_setting = Setting('pdns_api_key', os.environ['PDNS_API_KEY']) allow_create_domain_setting = Setting('allow_user_create_domain', True) try: with app.app_context(): flask_migrate.upgrade() db.session.add(api_url_setting) db.session.add(api_key_setting) db.session.add(allow_create_domain_setting) test_user_pass = app.config.get('TEST_USER_PASSWORD') test_user = app.config.get('TEST_USER') test_admin_user = app.config.get('TEST_ADMIN_USER') test_admin_pass = app.config.get('TEST_ADMIN_PASSWORD') admin_user = User( username=test_admin_user, plain_text_password=test_admin_pass, email="*****@*****.**" ) msg = admin_user.create_local_user() if not msg: raise Exception("Error occurred creating user {0}".format(msg)) ordinary_user = User( username=test_user, plain_text_password=test_user_pass, email="*****@*****.**" ) msg = ordinary_user.create_local_user() if not msg: raise Exception("Error occurred creating user {0}".format(msg)) except Exception as e: logging.error("Unexpected ERROR: {0}".format(e)) raise e yield db.session.close() os.unlink(app.config['TEST_DB_LOCATION'])
def api_login_delete_zone(domain_name): pdns_api_url = Setting().get('pdns_api_url') pdns_api_key = Setting().get('pdns_api_key') pdns_version = Setting().get('pdns_version') api_uri_with_prefix = utils.pdns_api_extended_uri(pdns_version) api_full_uri = api_uri_with_prefix + '/servers/localhost/zones' api_full_uri += '/' + domain_name headers = {} headers['X-API-Key'] = pdns_api_key domain = Domain.query.filter(Domain.name == domain_name) if not domain: abort(404) if g.user.role.name not in ['Administrator', 'Operator']: user_domains_obj_list = g.user.get_domains() user_domains_list = [item.name for item in user_domains_obj_list] if domain_name not in user_domains_list: raise DomainAccessForbidden() msg_str = "Sending request to powerdns API {0}" logging.debug(msg_str.format(domain_name)) try: resp = utils.fetch_remote( urljoin(pdns_api_url, api_full_uri), method='DELETE', headers=headers, accept='application/json; q=1' ) if resp.status_code == 204: logging.debug("Request to powerdns API successful") history = History( msg='Delete domain {0}'.format(domain_name), detail='', created_by=g.user.username ) history.add() domain = Domain() domain.update() except Exception as e: logging.error('Error: {0}'.format(e)) abort(500) return resp.content, resp.status_code, resp.headers.items()
def decorated_function(*args, **kwargs): auth_header = request.headers.get('X-API-KEY') if auth_header: try: apikey_val = str(base64.b64decode(auth_header), 'utf-8') except TypeError as e: logging.error('Error: {0}'.format(e)) abort(401) apikey = ApiKey(key=apikey_val) apikey.plain_text_password = apikey_val try: auth_method = 'LOCAL' auth = apikey.is_validate(method=auth_method, src_ip=request.remote_addr) g.apikey = auth except Exception as e: logging.error('Error: {0}'.format(e)) abort(401) else: logging.error('Error: API key header missing!') abort(401) return f(*args, **kwargs)
def api_get_apikeys(domain_name): apikeys = [] logging.debug("Getting apikeys") if g.user.role.name not in ['Administrator', 'Operator']: if domain_name: msg = "Check if domain {0} exists and \ is allowed for user.".format(domain_name) logging.debug(msg) apikeys = g.user.get_apikeys(domain_name) if not apikeys: raise DomainAccessForbidden(name=domain_name) logging.debug(apikey_schema.dump(apikeys)) else: msg_str = "Getting all allowed domains for user {0}" msg = msg_str.format(g.user.username) logging.debug(msg) try: apikeys = g.user.get_apikeys() logging.debug(apikey_schema.dump(apikeys)) except Exception as e: logging.error('Error: {0}'.format(e)) abort(500) else: logging.debug("Getting all domains for administrative user") try: apikeys = ApiKey.query.all() logging.debug(apikey_schema.dump(apikeys)) except Exception as e: logging.error('Error: {0}'.format(e)) abort(500) return json.dumps(apikey_schema.dump(apikeys)), 200
def decorated_function(*args, **kwargs): auth_header = request.headers.get('Authorization') if auth_header: auth_header = auth_header.replace('Basic ', '', 1) try: auth_header = str(base64.b64decode(auth_header), 'utf-8') username, password = auth_header.split(":") except TypeError as e: logging.error('Error: {0}'.format(e)) abort(401) user = User(username=username, password=password, plain_text_password=password) try: auth_method = request.args.get('auth_method', 'LOCAL') auth_method = 'LDAP' if auth_method != 'LOCAL' else 'LOCAL' auth = user.is_validate(method=auth_method, src_ip=request.remote_addr) if not auth: logging.error('Checking user password failed') abort(401) else: user = User.query.filter(User.username == username).first() g.user = user except Exception as e: logging.error('Error: {0}'.format(e)) abort(401) else: logging.error('Error: Authorization header missing!') abort(401) return f(*args, **kwargs)
def decorated_function(*args, **kwargs): if g.apikey.role.name != 'Administrator': msg = "Apikey {0} does not have enough privileges to create domain" logging.error(msg.format(g.apikey.id)) raise NotEnoughPrivileges() return f(*args, **kwargs)
def api_update_apikey(apikey_id): # if role different and user is allowed to change it, update # if apikey domains are different and user is allowed to handle # that domains update domains data = request.get_json() description = data['description'] if 'description' in data else None role_name = data['role'] if 'role' in data else None domains = data['domains'] if 'domains' in data else None domain_obj_list = None apikey = ApiKey.query.get(apikey_id) if not apikey: abort(404) logging.debug('Updating apikey with id {0}'.format(apikey_id)) if role_name == 'User' and len(domains) == 0: logging.error("Apikey with User role must have domains") raise ApiKeyNotUsable() elif role_name == 'User': domain_obj_list = Domain.query.filter(Domain.name.in_(domains)).all() if len(domain_obj_list) == 0: msg = "One of supplied domains does not exists" logging.error(msg) raise DomainNotExists(message=msg) if g.user.role.name not in ['Administrator', 'Operator']: if role_name != 'User': msg = "User cannot assign other role than User" logging.error(msg) raise NotEnoughPrivileges(message=msg) apikeys = g.user.get_apikeys() apikey_domains = [item.name for item in apikey.domains] apikeys_ids = [apikey_item.id for apikey_item in apikeys] user_domain_obj_list = g.user.get_domain().all() domain_list = [item.name for item in domain_obj_list] user_domain_list = [item.name for item in user_domain_obj_list] logging.debug("Input domain list: {0}".format(domain_list)) logging.debug("User domain list: {0}".format(user_domain_list)) inter = set(domain_list).intersection(set(user_domain_list)) if not (len(inter) == len(domain_list)): msg = "You don't have access to one of domains" logging.error(msg) raise DomainAccessForbidden(message=msg) if apikey_id not in apikeys_ids: msg = 'Apikey does not belong to domain to which user has access' logging.error(msg) raise DomainAccessForbidden() if set(domains) == set(apikey_domains): logging.debug("Domains are same, apikey domains won't be updated") domains = None if role_name == apikey.role: logging.debug("Role is same, apikey role won't be updated") role_name = None if description == apikey.description: msg = "Description is same, apikey description won't be updated" logging.debug(msg) description = None try: apikey = ApiKey.query.get(apikey_id) apikey.update(role_name=role_name, domains=domains, description=description) except Exception as e: logging.error('Error: {0}'.format(e)) abort(500) return '', 204