def main(): updater = Updater(utils.get_token('res/token_telegram.json')) bot = telegram.Bot(token=utils.get_token('res/token_telegram.json')) dp = updater.dispatcher dp.add_handler(CommandHandler('info', info)) dp.add_handler(CommandHandler('help', help)) dp.add_handler(CommandHandler('start', help)) dp.add_handler(MessageHandler(Filters.command, choose_backend)) dp.add_handler(MessageHandler(Filters.text, help)) updater.start_polling() updater.idle()
def get(self): token = get_token(request) if not token: return {'status': 'invalid_token'} user = User.query.filter_by(id=token['user_id']).first() if user: profile = Employee.query.filter_by(user_id=user.id).first() keywords = EmployeeKeyword.query.filter_by(employee_id=profile.id).all() all_keywords = [] for keyword in keywords: all_keywords.append(keyword.keyword) return { 'status': 'success', 'token': token['new_token'], 'firstName': user.firstname, 'lastName': user.lastname, 'birth': profile.birth.strftime('%Y-%m-%d'), 'city': profile.city, 'telephone': profile.telephone, 'description': profile.description, 'workExperience': profile.work_experience, 'keywords': all_keywords } else: return {'status': 'error'}
def test_losers_advantage(client): """ user with the lose_count of 3 and others with that of 0 attempt to apply a lottery test loser is more likely to win target_url: /lotteries/<id>/draw """ users_num = 12 idx = 1 win_count = {i: 0 for i in range(1, users_num + 1)} # user.id -> count with client.application.app_context(): target_lottery = Lottery.query.get(idx) index = target_lottery.index users = User.query.order_by(User.id).all()[:users_num] users[0].lose_count = 3 user0_id = users[0].id add_db(users2application(users, target_lottery)) token = get_token(client, admin) resp = draw(client, token, idx, index) for winner_json in resp.get_json(): winner_id = winner_json['id'] win_count[winner_id] += 1 # display info when this test fails print("final results of applications (1's lose_count == 3)") print(win_count) assert win_count[user0_id] > 0
def recieve_new_messages(token): #Check that request is a post request and that the token is valid if request.method == 'POST' and token == utils.get_token(): try: # Parse the response update_data = json.loads(request.data) for update in update_data["result"]: try: message = update.get('message', {}) message_text = message.get('text','') if utils.should_forward(message_text): chat_id = message.get('chat', {}).get('id', '') message_id = message.get('message_id', '') print "MESSAGE_ID: " + str(message_id) print "CHAT_ID: " + str(chat_id) if len(str(chat_id)) == 0 or len(str(message_id)) == 0: print("Could not retrieve chat or message id") utils.forward_message(chat_id, message_id) except Exception as e: print e continue except Exception as e: print e return ''
def test_apply_normal(client): """attempt to apply new application. 1. test: error isn't returned 2. test: DB is changed target_url: /lotteries/<id> [POST] """ idx = 1 user_info = test_user with client.application.app_context(): target_lottery = Lottery.query.get(idx) index = target_lottery.index token = get_token(client, user_info) with mock.patch('api.routes.api.get_time_index', return_value=index): resp = post(client, f'/lotteries/{idx}', token, group_members=[]) assert resp.status_code == 200 with client.application.app_context(): # get needed objects target_lottery = Lottery.query.get(idx) user = User.query.filter_by(secret_id=user_info['secret_id']).first() # this application should be added by previous 'client.put' application = get_application(user, target_lottery) assert application is not None assert resp.get_json() == application_schema.dump(application)[0]
def main(): global bot token = utils.get_token('res/token.json') args = parser.parse_args() if args.proxy == 1: print('-> USE PROXY') req = telegram.utils.request.Request(proxy_url='socks5h://127.0.0.1:9050', read_timeout=30, connect_timeout=20, con_pool_size=10) bot = telegram.Bot(token=token, request=req) elif args.proxy == 0: print('-> NO PROXY') bot = telegram.Bot(token=token) else: raise ValueError('Wrong proxy.') announcer.start() updater = Updater(bot=bot) dp = updater.dispatcher dp.add_handler(CommandHandler('help', help)) dp.add_handler(CommandHandler('start', help)) dp.add_handler(MessageHandler(Filters.text, help)) updater.start_polling() updater.idle()
def wrapper(*args, **kwargs): try: coverage = get_coverage(request) token = get_token(request) except exceptions.HeaderAbsent, e: return marshal({'error': {'message': utils.parse_error(e)}}, fields.error_fields), 400
def get_request_headers(repo_uuid): #with open("bitbucket_access_token") as f: # ACCESS_TOKEN = f.read() ACCESS_TOKEN = utils.get_token(repo_uuid, "Bitbucket") headers = {"Authorization": "Bearer " + ACCESS_TOKEN} return headers
def run(self): url = utils.read_secret("setting_url") token = utils.get_token(CONTEXT) repo = setr.setting_repo() setting_names = [] setting_values = {} for name in utils.retry_if_none(lambda: repo.get_setting_names()): setting_names.append(name) value = utils.retry_if_none(lambda: repo.get_value(name)) setting_values[name] = value post_setting(url, token, name, value) while is_streaming: for name in setting_names: setting = get_setting(url, token, name) if not setting is None and setting[ "value"] != setting_values.get(name): utils.retry_if_none( lambda: repo.set_value(name, setting["value"])) setting_values[name] = value time.sleep(1) repo.close_connection()
def legacy_upload_document(data_pool_id, label, content_type, filepath): token, token_type = get_token() content_md5 = get_content_md5(filepath) # POST document and store response content resp = requests.post( url=f'https://api.glynt.ai/v6/data-pools/{data_pool_id}/documents/', headers={ 'Authorization': f'{token_type} {token}', 'content-type': 'application/json' }, json={ 'label': label, 'content_type': content_type, 'content_md5': content_md5 }) assert resp.status_code == 201 document = resp.json() # PUT document content with open(filepath, 'rb') as f: resp = requests.put(url=document['file_upload_url'], headers={ 'content-type': content_type, 'content-md5': content_md5 }, data=f.read()) assert resp.status_code == 200 return document
def renew_token(self): '''refresh/retrieve the token''' result = False auth_token = None username = self.get_username() if username: # stop connect daemon self.stop_connect_daemon() # retrieve token log_msg("Retrieving auth token....") auth_token = get_token(self.spotty) if auth_token: log_msg("Retrieved auth token") self.auth_token = auth_token # only update token info in spotipy object self.sp._auth = auth_token["access_token"] me = self.sp.me() self.current_user = me["id"] log_msg("Logged in to Spotify - Username: %s" % self.current_user, xbmc.LOGINFO) # store authtoken and username as window prop for easy access by plugin entry self.win.setProperty("spotify-token", auth_token["access_token"]) self.win.setProperty("spotify-username", self.current_user) self.win.setProperty("spotify-country", me["country"]) result = True # start experimental spotify connect daemon self.start_connect_daemon() return result
def __init__(self, name=None, passwd=None, project=None, flag='non-sys', domain='default'): self.__users_url = ('http://' + utils.init_data().get('host', 'IP') + ':' + utils.init_data().get('keystone', 'PORT') + '/' + utils.init_data().get('keystone', 'VERSION') + '/users') self.flag = flag self.domain = domain self.name = name self.passwd = passwd self.project = project self.identification = None self.enable = False self.endpoint = {} # TODO(dc) user quota # TODO(dc) self.quota = None self.token = utils.get_token(self) self.headers = { 'User-Agent': utils.init_data().get('agent', 'ALL'), 'X-Auth-Token': self.token, "Content-type": "application/json", "Accept": "application/json" } self._set_info()
def test_draw_all_invalid(client): """attempt to draw in not acceptable time target_url: /draw_all [POST] """ token = get_token(client, admin) def try_with_datetime(t): resp = draw_all(client, token, time=t) assert resp.status_code == 400 assert 'Not acceptable' in resp.get_json()['message'] outofhours1 = client.application.config['START_DATETIME'] - \ datetime.timedelta.resolution try_with_datetime(outofhours1) outofhours2 = client.application.config['END_DATETIME'] + \ datetime.timedelta.resolution try_with_datetime(outofhours2) timepoints = client.application.config['TIMEPOINTS'] ext = client.application.config['DRAWING_TIME_EXTENSION'] for i, (_, en) in enumerate(timepoints): res = datetime.timedelta.resolution try_with_datetime(mod_time(en, -res)) try_with_datetime(mod_time(en, +ext+res))
def run(self) -> None: for ext in self.startup_extensions: try: self.load_extension(ext) except Exception as e: logger.error(Constants.EXT_FAILED_TO_RUN, ext, e) super().run(get_token(), reconnect=True)
def __init__(self): self.path = config.IHRM_URL + "/api/sys/profile" self.path_department = config.IHRM_URL + "/api/company/department" self.headers = { "Authorization": get_token(), "Content-Type": "application/json" }
def post(self): """Authenticate and get token""" username = self.get_argument('username') password = self.get_argument('password') try: user = User.logon(username, password) except UserNotFound: data = errors.get(errors.INVALID_LOGIN) else: token = utils.get_token() session = { 'username': username, 'token': token } db.sessions.insert(session) data = { 'username': username, 'is_staff': user.is_staff, 'token': token } self.finish(data)
def try_create_ok(): emps_before = get_all() data = { "email": "*****@*****.**", "password": "******", "departmentId": 1, "bossId": None, "firstName": "Testing", "lastName": "Employee", "salary": 1337, "isActive": 1, } headers = {"Token": get_token()} r = requests.post(f"{BASE_URL}/employees", data=data, headers=headers) emps_after = get_all() print(r.json()) assert r.status_code == 200 assert len(emps_before) + 1 == len(emps_after) createdId = r.json()["lastId"] created = requests.get(f"{BASE_URL}/employees/{createdId}").json()[0] for field in data: assert data[field] == created[field]
def run(self): url = utils.read_secret("switch_url") token = utils.get_token(CONTEXT) repo = dr.device_repo() switch_names = [] switch_statuses = {} for name in utils.retry_if_none(lambda: repo.get_device_names()): switch_names.append(name) while is_streaming: for name in switch_names: value = utils.retry_if_none(lambda: repo.get_value(name)) if not value is None and value != switch_statuses.get(name): post_switch_status(url, token, name, value) switch_statuses[name] = value switch_status = get_switch_status(url, token, name) if not switch_status is None and switch_status[ "value"] != switch_statuses.get(name): utils.retry_if_none( lambda: repo.set_value(name, switch_status["value"])) switch_statuses[name] = value time.sleep(1) repo.close_connection()
def try_delete_ok(): emps_first = get_all() data = { "email": "*****@*****.**", "password": "******", "departmentId": 1, "bossId": None, "firstName": "Testing", "lastName": "Employee", "salary": 1337, "isActive": 1, } headers = {"Token": get_token()} r = requests.post(f"{BASE_URL}/employees", data=data, headers=headers) assert r.status_code == 200 insertedId = r.json()["lastId"] emps_after_insert = get_all() assert len(emps_after_insert) == len(emps_first) + 1 r = requests.get(f"{BASE_URL}/employees/{insertedId}") assert r.status_code == 200 r = requests.delete(f"{BASE_URL}/employees/{insertedId}", headers=headers) assert r.status_code == 200 emps_after_delete = get_all() assert emps_after_delete == emps_first r = requests.get(f"{BASE_URL}/employees/{insertedId}")
def login(): # redirect to home if already logged in if session.get('user_id'): return redirect(url_for('ph_bp.home')) if request.method == 'POST': token = md5(request.form['password'] + session.get('nonce', '')).hexdigest() if token == request.form['token']: query = "SELECT * FROM users WHERE username='******' AND password_hash='{}'" username = request.form['username'] password_hash = xor_encrypt(request.form['password'], current_app.config['PW_ENC_KEY']) user = db.session.execute(query.format(username, password_hash)).first() if user and user['status'] == 1: session['user_id'] = user.id path = os.path.join(current_app.config['UPLOAD_FOLDER'], md5(str(user.id)).hexdigest()) if not os.path.exists(path): os.makedirs(path) session['upload_folder'] = path session.rotate() return redirect( request.args.get('next') or url_for('ph_bp.home')) return redirect( url_for('ph_bp.login', error='Invalid username or password.')) return redirect(url_for('ph_bp.login', error='Bot detected.')) session['nonce'] = get_token(5) return render_template('login.html')
def get_request_headers(repo_uuid): ACCESS_TOKEN = utils.get_token(repo_uuid, "OneNote") # with open(ONENOTE_ACCESS_TOKEN_FILE) as f: # ACCESS_TOKEN = f.read() headers = {"Authorization": "Bearer " + ACCESS_TOKEN} return headers
def wrapper(*args, **kwargs): try: coverage = get_coverage(request) token = get_token(request) except exceptions.HeaderAbsent, e: return marshal({'error': { 'message': utils.parse_error(e) }}, fields.error_fields), 400
def get_group_name_by_id(group_id): group_id = utils.shortname_to_id(group_id) params = {"gid": group_id, "access_token": utils.get_token()} result = requests.get('https://api.vk.com/method/execute.getGroupNameById', params=params) if 'error' not in result.json(): return result.json()['response'] else: return None
def try_create_repeated(): dpmts_before = get_all() token = get_token() headers = {"Token": token} data = {"name": "Department of testing", "city": "Testingville"} r = requests.post(f"{BASE_URL}/departments", data=data, headers=headers) dpmts_after = get_all() assert r.status_code == 400 assert len(dpmts_before) == len(dpmts_after)
def confirm_order(mid): ''' Notify merchant of order confirmation from customer ''' merchant = utils.get_merchant(mid) data = request.get_json() oid = data["oid"] order = utils.confirm_order(mid, oid, data["customer_contact"]) fcm.notify_confirm_order(utils.get_token(merchant), order) return {"message": "OK"}
def get_group_name_by_id(group_id): group_id = utils.shortname_to_id(group_id) params = {"gid": group_id, "access_token": utils.get_token() } result = requests.get('https://api.vk.com/method/execute.getGroupNameById', params=params) if 'error' not in result.json(): return result.json()['response'] else: return None
def test_get_token_works_with_well_formed_token_file(): obj_token_json = {"api": "test-token"} with tempfile.NamedTemporaryFile() as temp_token_file: with open(temp_token_file.name, "w") as temp_token_file_write: json.dump(obj_token_json, temp_token_file_write, indent=2) temp_filename = temp_token_file.name returned_token = utils.get_token(temp_filename) assert returned_token == "test-token"
def wrapper(*args, **kwargs): try: coverage = get_coverage(request) token = get_token(request) except exceptions.HeaderAbsent as e: return marshal({'error': { 'message': utils.parse_error(e) }}, fields.error_fields), 400 nav = Navitia(current_app.config['NAVITIA_URL'], coverage, token) return func(*args, navitia=nav, **kwargs)
def test_apply_admin(client): """attempt to apply new application as admin test: 403 is returned target_url: /lotteries/<id> [POST] """ idx = 1 token = get_token(client, admin) resp = post(client, f'/lotteries/{idx}', token, group_members=[]) assert resp.status_code == 403
def test_draw_invalid(client): """attempt to draw non-exsit lottery target_url: /lotteries/<id>/draw [POST] """ idx = invalid_lottery_id token = get_token(client, admin) resp = draw(client, token, idx) assert resp.status_code == 404 assert 'Not found' in resp.get_json()['message']
def wrapper(*args, **kwargs): try: coverage = get_coverage(request) token = get_token(request) except exceptions.HeaderAbsent as e: return marshal( {'error': {'message': utils.parse_error(e)}}, fields.error_fields ), 400 nav = Navitia(current_app.config['NAVITIA_URL'], coverage, token) return func(*args, navitia=nav, **kwargs)
def login(self, request): user = User.query(User.email==request.email).get() if not user: user = User(email=request.email, password=request.password) user.put() else: if not user.password == request.password: return UserLoginMessage(error='Wrong password') return UserLoginMessage(email=user.email, nickname = user.nickname(), token=get_token(user.email))
def __init__(self): self.token = utils.get_token() self.enable = True self.__headers = { 'User-Agent': utils.init_data().get('agent', 'ALL'), 'X-Auth-Token': self.token, "Content-type": "application/json", "Accept": "application/json" } self.__roles_url = utils.get_endpoint(self.token, 'keystone') + '/roles'
def wrapper(*args, **kwargs): try: token = get_token(request) client_code = get_client_code(request) client_token_is_allowed(self.clients_tokens, client_code, token) except (exceptions.HeaderAbsent, exceptions.Unauthorized) as e: return marshal( {'error': {'message': utils.parse_error(e)}}, fields.error_fields ), 401 return func(*args, **kwargs)
def output(self, key, obj): if not obj: return None if obj.type == 'line_section': return None navitia = Navitia(current_app.config['NAVITIA_URL'], get_coverage(request), get_token(request)) response = navitia.get_pt_object(obj.uri, obj.type) if response and 'name' in response: return response['name'] return 'Unable to find object'
def wrapper(*args, **kwargs): try: token = get_token(request) client_code = get_client_code(request) client_token_is_allowed(self.clients_tokens, client_code, token) except (exceptions.HeaderAbsent, exceptions.Unauthorized) as e: return marshal({'error': { 'message': utils.parse_error(e) }}, fields.error_fields), 401 return func(*args, **kwargs)
def test_draw_noperm(client): """attempt to draw without proper permission. target_url: /lotteries/<id>/draw [POST] """ idx = 1 token = get_token(client, test_user) resp = draw(client, token, idx) assert resp.status_code == 403 assert 'You have no permission to perform the action' in \ resp.get_json()['message']
def get_post(group_id, offset): group_id = utils.shortname_to_id(group_id) params = { "gid": group_id, "access_token": utils.get_token(), "offset": offset, "v": api_version } result = requests.get('https://api.vk.com/method/execute.getWallPostNew', params=params) if 'error' in result.json()['response']: logger.error('Error in get_post()') return result.json()['response']
def is_first_pinned(group_id): group_id = utils.shortname_to_id(group_id) params = { "owner_id": -group_id, "count": 2, "access_token": utils.get_token() } result = requests.get('https://api.vk.com/method/wall.get', params=params) try: v = result.json()['response'][1]['is_pinned'] return True except Exception: return False
def output(self, key, obj): if not obj: return None if obj.type == 'line_section': return None navitia = Navitia( current_app.config['NAVITIA_URL'], get_coverage(request), get_token(request)) response = navitia.get_pt_object(obj.uri, obj.type) if response and 'name' in response: return response['name'] return 'Unable to find object'
def output(self, key, obj): if not obj: return None if isinstance(obj, dict) and 'uri' in obj and 'type' in obj: obj_uri = obj['uri'] obj_type = obj['type'] else: obj_uri = obj.uri obj_type = obj.type navitia = Navitia( current_app.config['NAVITIA_URL'], get_coverage(request), get_token(request)) return navitia.find_tc_object_name(obj_uri, obj_type)
def share(): if request.method == 'POST': pw = Password( hash=get_token(10), cipher=request.form.get('cipher'), comment=request.form.get('comment'), ) db.session.add(pw) db.session.commit() msg = 'Send the following link to the recipient.' email = request.form.get('email') if email: send_share(email, pw) msg = 'The following link has been sent to the recipient.' flash('Password added.') return render_template('share.html', password=pw, message=msg) return redirect(url_for('index'))
def get_first_post_id(group_id): """ Получает идентификатор верхнего поста в группе. Если есть закрепленный пост, то возвращает первый на самой стене :param group_id: ID группы (буквенный или числовой) """ group_id = utils.shortname_to_id(group_id) params = { "gid": group_id, "access_token": utils.get_token(), "v": api_version } result = requests.get('https://api.vk.com/method/execute.getFirstPostId', params=params) try: res = result.json()['response'] return res except Exception as e: logger.error('get_first_post_id exception: {0!s}'.format(e)) return None
def output(self, key, obj): to_return = [] navitia = Navitia(current_app.config['NAVITIA_URL'], get_coverage(request), get_token(request)) if isinstance(obj, dict) and 'localizations' in obj: for localization in obj['localizations']: response = navitia.get_pt_object( localization['uri'], localization['type']) if response and 'name' in response: response["type"] = localization['type'] to_return.append(response) else: to_return.append( { "id": localization['uri'], "name": "Unable to find object", "type": localization['type'] } ) elif obj.localizations: for localization in obj.localizations: response = navitia.get_pt_object( localization.uri, localization.type) if response and 'name' in response: response["type"] = localization.type to_return.append(response) else: to_return.append( { "id": localization.uri, "name": "Unable to find object", "type": localization.type } ) return to_return
def get_first_unread(group_id): group_id = utils.shortname_to_id(group_id) params = { "gid": group_id, "access_token": utils.get_token(), "v": api_version } result = requests.get('https://api.vk.com/method/execute.getUnreadCount', params=params) array = result.json()['response'] if array['is_first_pinned'] is None: return None else: try: if array['is_first_pinned'] == 1: return array['items'][1] else: return array['items'][0] except TypeError as e: logger.error('FirstUnread TypeError: {0!s}'.format(e)) except IndexError: logger.error('FirstUnread IndexError') pass
def get_unread_count(group_id, last_id): group_id = utils.shortname_to_id(group_id) params = { "gid": group_id, "access_token": utils.get_token(), "v": api_version } result = requests.get('https://api.vk.com/method/execute.getUnreadCount', params=params, timeout=10) logger.debug('GetUnreadCount result: ' + str(result.json())) array = result.json()['response'] chosen = 0 logger.debug('UnreadCount last_id = ' + str(last_id)) try: for index, item in enumerate(array['items']): if item > last_id: chosen += 1 if item == last_id: break except TypeError as ex: logger.error('UnreadCount TypeError: {0!s}'.format(ex)) logger.debug('UnreadCount chosen = {0!s}'.format(chosen)) return chosen
import json from utils import get_token, get_cats import requests as r with open('credentials.json') as credentials_file: creds = json.load(credentials_file) detector_url = 'http://catdetector.biz/?imageurl=' access_token = get_token(creds) cats = get_cats(access_token, 10) if cats: for cat in cats: resp = r.get(detector_url + cat['image_url'] + '&json') if resp.status_code == 200: probability_of_cat = resp.json()['probability'] if probability_of_cat > 70: comment = 'This is cat! I am %.2f%% sure of it.' % probability_of_cat elif 70 >= probability_of_cat > 50: comment = 'This might be cat... there is a %.2f%% chance' % probability_of_cat elif probability_of_cat <= 50: comment = 'This is not a cat! How dare you disparage the #cat hashtag! I am %.2f%% sure this is not a cat' % (100 - probability_of_cat) comment_url = 'https://api.instagram.com/v1/media/%s/comments' % cat['id'] print comment post_data = {'text': comment, 'access_token': access_token}
def main(): f = open('log_test_values_cider.txt', 'w') original = sys.stdout sys.stdout = utils.Tee(sys.stdout, f) token = 0 domain_id, production_project_id, cms_project_id, atlas_project_id = (0, )*4 computing_project_id, visualisation_project_id, services_project_id = (0, )*3 operations_project_id = 0 try: token_json = utils.default_token_json('admin', 'demo') token = utils.get_token(token_json) print '=======================================================================' print 'This script will use the follow hierarchy to validate the quota values' print 'related to Nested Quotas on Cinder' print '=======================================================================' print 'Hierarchy:' print ' Domain_X ' print ' |' print ' ProductionIT - Mike' print ' / \ ' print ' Jay - CMS ATLAS - John' print ' / \ / \ ' print ' Computing Visualisation Operations Services ' print ' Walter Duncan Eric Xing' print '' print 'Actors:' print '' print 'Mike - Cloud Admin (i.e. role:cloud-admin) of ProductionIT' print 'Jay - Manager (i.e. role: project-admin) of Project CMS' print 'John - Manager (i.e. role: project-admin) of Project ATLAS' print 'Eric - Manager (i.e. role: project-admin) of Project Operations' print 'Xing - Manager (i.e. role: project-admin) of Project Services' print 'Walter - Manager (i.e. role: project-admin) of Project Computing' print 'Duncan - Manager (i.e. role: project-admin) of Project Visualisation' print '=======================================================================' # Create a new domain print 'Creating the domain...' domain = utils.domain_json() domain_id = utils.create_domain(domain, token) print 'Domain created: %s' % domain_id print '=======================================================================' print 'Creating the projects...' # Create project ProductionIT production_project_json = utils.project_json('ProductionIT', domain_id) production_project_id = utils.create_project(production_project_json, token) print "ProductionIT created: %s" % production_project_id print '=======================================================================' # Create Project CMS cms_project_json = utils.project_json('CMS', domain_id, production_project_id) cms_project_id = utils.create_project(cms_project_json, token) print "CMS created: %s" % cms_project_id print '=======================================================================' # Create Project Atlas atlas_project_json = utils.project_json('ATLAS', domain_id, production_project_id) atlas_project_id = utils.create_project(atlas_project_json, token) print "ATLAS created: %s" % atlas_project_id print '=======================================================================' # Create Project computing computing_project_json = utils.project_json('computing', domain_id, cms_project_id) computing_project_id = utils.create_project(computing_project_json, token) print "Computing created: %s" % computing_project_id print '=======================================================================' # Create Project visualisation visual_project_json = utils.project_json('visualisation', domain_id, cms_project_id) visualisation_project_id = utils.create_project(visual_project_json, token) print "Visualisation created: %s" % visualisation_project_id print '=======================================================================' # Create Project services services_project_json = utils.project_json('services', domain_id, atlas_project_id) services_project_id = utils.create_project(services_project_json, token) print "Services created: %s" % services_project_id print '=======================================================================' # Create Project operations operations_project_json = utils.project_json('operations', domain_id, atlas_project_id) operations_project_id = utils.create_project(operations_project_json, token) print "Operations created: %s" % operations_project_id print '=======================================================================' admin_role = utils.get_role(token, 'admin') # Creating users # Creating and grant admin role to mike in production print 'Creating the users...' mike = utils.create_user(token, 'Mike', domain_id) print "Mike: %s" % mike utils.grant_user_role(token, mike, admin_role, [production_project_id]) print '=======================================================================' # Creating and grant admin role to jay in cms jay = utils.create_user(token, 'Jay', domain_id) print "Jay: %s" % jay utils.grant_user_role(token, jay, admin_role, [cms_project_id]) print '=======================================================================' # Creating and grant admin role to john in atlas john = utils.create_user(token, 'John', domain_id) print "John: %s" % john utils.grant_user_role(token, john, admin_role, [atlas_project_id]) print '=======================================================================' # Creating and grant admin role to eric in operations eric = utils.create_user(token, 'Eric', domain_id) print "Eric: %s" % eric utils.grant_user_role(token, eric, admin_role, [operations_project_id]) print '=======================================================================' # Creating and grant admin role to xing in services xing = utils.create_user(token, 'Xing', domain_id) print "Xing: %s" % xing utils.grant_user_role(token, xing, admin_role, [services_project_id]) print '=======================================================================' # Creating and grant admin role to walter in computing walter = utils.create_user(token, 'Walter', domain_id) print "Walter: %s" % walter utils.grant_user_role(token, walter, admin_role, [computing_project_id]) print '=======================================================================' # Creating and grant admin role to duncan in visualisation duncan = utils.create_user(token, 'Duncan', domain_id) print "Ducnan: %s" % duncan utils.grant_user_role(token, duncan, admin_role, [visualisation_project_id]) print '=======================================================================' print 'Now, we will get a token for Mike in ProductionIT (root project)' print 'and show that the quota calculation in the hierarchy works well.' print '=======================================================================' # Get a token for Mike in ProductionIT mike_token_json = utils.get_token_json('Mike', production_project_id) mike_token = utils.get_token(mike_token_json) print 'Token for mike: %s' % mike_token print '=======================================================================' # Update the Prduction Quota to 100 print 'Updating the ProductionIT quota for 100...' quota_value = 100 production_quota = utils.update_quota(mike_token, production_project_id, production_project_id, quota_value) quota_show_production = utils.quota_show(mike_token, production_project_id, production_project_id) print '=======================================================================' print "Production Quota: %s" % quota_show_production print '=======================================================================' # Update the CMS Quota to 40 print 'Updating the CMS quota for 40...' quota_value = 40 cms_quota = utils.update_quota(mike_token, production_project_id, cms_project_id, quota_value) quota_show_production = utils.quota_show(mike_token, production_project_id, production_project_id) quota_show_cms = utils.quota_show(mike_token, production_project_id, cms_project_id) print 'Verify that allocated ProductionIT quota was updated to 40' print "Production Quota: %s" % quota_show_production print "CMS Quota: %s" % quota_show_cms print '=======================================================================' # Update the Atlas Quota to 30 print 'Updating the Atlas quota for 30...' quota_value = 30 atlas_quota = utils.update_quota(mike_token, production_project_id, atlas_project_id, quota_value) quota_show_production = utils.quota_show(mike_token, production_project_id, production_project_id) quota_show_atlas = utils.quota_show(mike_token, production_project_id, atlas_project_id) print 'Verify that allocated ProductionIT quota was updated to 70' print "Production Quota: %s" % quota_show_production print "Atlas Quota: %s" % quota_show_atlas print '=======================================================================' # Update the Computing Quota to 15 print 'Updating the Computing quota for 15...' quota_value = 15 computing_quota = utils.update_quota(mike_token, production_project_id, computing_project_id, quota_value) quota_show_cms = utils.quota_show(mike_token, production_project_id, cms_project_id) quota_show_computing = utils.quota_show(mike_token, production_project_id, computing_project_id) print 'Verify that allocated CMS quota was updated to 15' print "CMS Quota: %s" % quota_show_cms print "Computing Quota: %s" % quota_show_computing print '=======================================================================' # Update the visualisaton Quota to 15 print 'Updating the Visualisation quota for 15...' quota_value = 15 visualisation_quota = utils.update_quota(mike_token, production_project_id, visualisation_project_id, quota_value) quota_show_cms = utils.quota_show(mike_token, production_project_id, cms_project_id) quota_show_visualisation = utils.quota_show(mike_token, production_project_id, visualisation_project_id) print 'Verify that allocated CMS quota was updated to 30' print "CMS Quota: %s" % quota_show_cms print "Visualisation Quota: %s" % quota_show_visualisation print '=======================================================================' print 'Updating the Services quota for 10...' # Update the services Quota to 10 quota_value = 10 services_quota = utils.update_quota(mike_token, production_project_id, services_project_id, quota_value) quota_show_atlas = utils.quota_show(mike_token, production_project_id, atlas_project_id) quota_show_services = utils.quota_show(mike_token, production_project_id, services_project_id) print 'Verify that allocated Atlas quota was updated to 10' print "Atlas Quota: %s" % quota_show_atlas print "Service Quota: %s" % quota_show_services print '=======================================================================' # Update the operations Quota to 10 quota_value = 10 operations_quota = utils.update_quota(mike_token, production_project_id, operations_project_id, quota_value) quota_show_atlas = utils.quota_show(mike_token, production_project_id, atlas_project_id) quota_show_operations = utils.quota_show(mike_token, production_project_id, operations_project_id) print 'Verify that allocated Atlas quota was updated to 20' print "Atlas Quota: %s" % quota_show_atlas print "Operations Quota: %s" % quota_show_operations print '=======================================================================' # Update the CMS Quota to 40 quota_value = 71 print 'Trying update the CMS quota for 71...' cms_quota = utils.update_quota(mike_token, production_project_id, cms_project_id, quota_value) print "Error: %s" % cms_quota print '=======================================================================' print "Creating 10 Volumes in CMS..." # Get a token for Jay in CMS jay_token_json = utils.get_token_json('Jay', cms_project_id) jay_token = utils.get_token(jay_token_json) for i in range(0,10): utils.create_volume(jay_token, cms_project_id) quota_show_cms = utils.quota_show(jay_token, cms_project_id, cms_project_id) print "CMS Quota: %s" % quota_show_cms print 'Now, we dont have free quota in CMS' print '=======================================================================' print "Trying update the computing quota to 16 (subproject for CMS)..." quota_value = 16 computing_quota = utils.update_quota(mike_token, production_project_id, computing_project_id, quota_value) print "Error: %s" % computing_quota print '=======================================================================' print 'Clean up...' except Exception as e: print 'Error' tear_down(token, [production_project_id, cms_project_id, atlas_project_id, computing_project_id, visualisation_project_id, services_project_id, operations_project_id], domain_id) f.close() print e tear_down(token, [production_project_id, cms_project_id, atlas_project_id, computing_project_id, visualisation_project_id, services_project_id, operations_project_id], domain_id) f.close()
def main(): f = open("log_test_authorization_cider.txt", "w") original = sys.stdout sys.stdout = utils.Tee(sys.stdout, f) token = 0 domain_id, production_project_id, cms_project_id, atlas_project_id = (0,) * 4 computing_project_id, visualisation_project_id, services_project_id = (0,) * 3 operations_project_id = 0 try: token_json = utils.default_token_json("admin", "demo") token = utils.get_token(token_json) print "=======================================================================" print "This script will use the follow hierarchy to validate the authorization" print "actions related to Nested Quotas on Cinder" print "=======================================================================" print "Hierarchy:" print " Domain_X " print " |" print " ProductionIT - Mike" print " / \ " print " Jay - CMS ATLAS - John" print " / \ / \ " print " Computing Visualisation Operations Services " print " Walter Duncan Eric Xing" print "" print "Actors:" print "" print "Mike - Cloud Admin (i.e. role:cloud-admin) of ProductionIT" print "Jay - Manager (i.e. role: project-admin) of Project CMS" print "John - Manager (i.e. role: project-admin) of Project ATLAS" print "Eric - Manager (i.e. role: project-admin) of Project Operations" print "Xing - Manager (i.e. role: project-admin) of Project Services" print "Walter - Manager (i.e. role: project-admin) of Project Computing" print "Duncan - Manager (i.e. role: project-admin) of Project Visualisation" print "=======================================================================" admin_role = utils.get_role(token, "admin") # Create a new domain print "Creating the domain..." domain = utils.domain_json() domain_id = utils.create_domain(domain, token) print "Domain created: %s" % domain_id print "=======================================================================" print "Creating the projects..." # Create project ProductionIT production_project_json = utils.project_json("ProductionIT", domain_id) production_project_id = utils.create_project(production_project_json, token) print "ProductionIT created: %s" % production_project_id print "=======================================================================" # Create Project CMS cms_project_json = utils.project_json("CMS", domain_id, production_project_id) cms_project_id = utils.create_project(cms_project_json, token) print "CMS created: %s" % cms_project_id print "=======================================================================" # Create Project Atlas atlas_project_json = utils.project_json("ATLAS", domain_id, production_project_id) atlas_project_id = utils.create_project(atlas_project_json, token) print "ATLAS created: %s" % atlas_project_id print "=======================================================================" # Create Project computing computing_project_json = utils.project_json("computing", domain_id, cms_project_id) computing_project_id = utils.create_project(computing_project_json, token) print "Computing created: %s" % computing_project_id print "=======================================================================" # Create Project visualisation visual_project_json = utils.project_json("visualisation", domain_id, cms_project_id) visualisation_project_id = utils.create_project(visual_project_json, token) print "Visualisation created: %s" % visualisation_project_id print "=======================================================================" # Create Project services services_project_json = utils.project_json("services", domain_id, atlas_project_id) services_project_id = utils.create_project(services_project_json, token) print "Services created: %s" % services_project_id print "=======================================================================" # Create Project operations operations_project_json = utils.project_json("operations", domain_id, atlas_project_id) operations_project_id = utils.create_project(operations_project_json, token) print "Operations created: %s" % operations_project_id print "=======================================================================" # Creating users # Creating and grant admin role to mike in production print "Creating the users..." mike = utils.create_user(token, "Mike", domain_id) print "Mike: %s" % mike utils.grant_user_role(token, mike, admin_role, [production_project_id]) print "=======================================================================" # Creating and grant admin role to jay in cms jay = utils.create_user(token, "Jay", domain_id) print "Jay: %s" % jay utils.grant_user_role(token, jay, admin_role, [cms_project_id]) print "=======================================================================" # Creating and grant admin role to john in atlas john = utils.create_user(token, "John", domain_id) print "John: %s" % john utils.grant_user_role(token, john, admin_role, [atlas_project_id]) print "=======================================================================" # Creating and grant admin role to eric in operations eric = utils.create_user(token, "Eric", domain_id) print "Eric: %s" % eric utils.grant_user_role(token, eric, admin_role, [operations_project_id]) print "=======================================================================" # Creating and grant admin role to xing in services xing = utils.create_user(token, "Xing", domain_id) print "Xing: %s" % xing utils.grant_user_role(token, xing, admin_role, [services_project_id]) print "=======================================================================" # Creating and grant admin role to walter in computing walter = utils.create_user(token, "Walter", domain_id) print "Walter: %s" % walter utils.grant_user_role(token, walter, admin_role, [computing_project_id]) print "=======================================================================" # Creating and grant admin role to duncan in visualisation duncan = utils.create_user(token, "Duncan", domain_id) print "Ducnan: %s" % duncan utils.grant_user_role(token, duncan, admin_role, [visualisation_project_id]) print "=======================================================================" print "Now, we will get a token for Mike in ProductionIT (root project)" print "and show that Mike can update the quota for the root project." print "=======================================================================" # Get a token for Mike in ProductionIT mike_token_json = utils.get_token_json("Mike", production_project_id) mike_token = utils.get_token(mike_token_json) print "Token for mike: %s" % mike_token print "=======================================================================" # Update the Production Quota to 100 print "Updating the ProductionIT quota for 100..." quota_value = 100 production_quota = utils.update_quota(mike_token, production_project_id, production_project_id, quota_value) print "Mike updating Production Quota: %s" % production_quota print "=======================================================================" print "Trying get the default quota for CMS..." # Verify that the default quotas for CMS is zero cms_quota = utils.get_quota(mike_token, production_project_id, cms_project_id) print "Mike getting CMS Quota: %s" % cms_quota print "=======================================================================" print "Trying update the CMS quota for 45..." # Update the CMS Quota to 45 quota_value = 45 new_cms_quota = utils.update_quota(mike_token, production_project_id, cms_project_id, quota_value) print "Mike updating CMS Quota: %s" % new_cms_quota print "=======================================================================" print "Now, we get a token for Jay in CMS and we will try update the CMS Quota" print "=======================================================================" # Get a token for Jay in CMS jay_token_json = utils.get_token_json("Jay", cms_project_id) jay_token = utils.get_token(jay_token_json) print "Token for Jay: %s " % jay_token print "=======================================================================" # Raise a exception when try update the CMS Quota with # only a project_admin print "Trying update the CMS quota for 50" quota_value = 50 forbidden_error = 403 new_cms_quota = utils.update_quota(jay_token, cms_project_id, cms_project_id, quota_value) if new_cms_quota == forbidden_error: print "Error: Cannot update the quota for CMS with user Jay" print "=======================================================================" # Verify that the default quotas for Visualisation is zero cms_quota = utils.get_quota(jay_token, cms_project_id, cms_project_id) print "Trying get the CMS Quota: %s" % cms_quota print "=======================================================================" # Raise a exception when try update the Visualisation Quota with a # project_admin in a non-root project print "Trying update the Visualisation Quota with Jay" quota_value = 10 new_visualisation_quota = utils.update_quota(jay_token, cms_project_id, visualisation_project_id, quota_value) if new_visualisation_quota == forbidden_error: print "Error: Cannot update the quota for Visualisation with user Jay" else: print "New Visualisation Quota: %s " % new_visualisation_quota print "=======================================================================" # Raise a exception when try get the Visualisation Quota with a # project_admin in a non-root project print "Trying get the Visualisation Quota with Jay" visualisation_quota = utils.get_quota(jay_token, cms_project_id, visualisation_project_id) if visualisation_quota == forbidden_error: print "Error: Cannot get the quota for Visualisation with user Jay" else: print "Get Visualisation Quota: %s " % new_visualisation_quota print "=======================================================================" # Raise a exception when try get the Atlas Quota with a project_admin # in a non-root project atlas_quota = utils.get_quota(jay_token, cms_project_id, atlas_project_id) if atlas_quota == forbidden_error: print "Error: Cannot get the quota for Atlas with user Jay" print "=======================================================================" # Get a token for Duncan in Visualisation duncan_token_json = utils.get_token_json("Duncan", visualisation_project_id) duncan_token = utils.get_token(duncan_token_json) print "Get a token for Duncan in Visualisation: %s " % duncan_token # Raise a exception when try get the Atlas Quota with a project_admin # in a subproject cms_quota = utils.get_quota(duncan_token, visualisation_project_id, cms_project_id) if cms_quota == forbidden_error: print "Error: Cannot get the quota for CMS with user Duncan" print "=======================================================================" # Raise a exception when try update the Visualisation Quota # with a project_admin in a non-root project quota_value = 10 new_visualisation_quota = utils.update_quota( duncan_token, visualisation_project_id, visualisation_project_id, quota_value ) if new_visualisation_quota == forbidden_error: print ("Cannot update the quota for Visualisation with user Duncan") print "=======================================================================" # Verify that the default quotas for Visualisation is zero visual_quota = utils.get_quota(duncan_token, visualisation_project_id, visualisation_project_id) print ("Duncan getting the Visualisation Quota: %s" % visual_quota) print "=======================================================================" print "Clean up..." except Exception as e: print "Error" tear_down( token, [ production_project_id, cms_project_id, atlas_project_id, computing_project_id, visualisation_project_id, services_project_id, operations_project_id, ], domain_id, ) f.close() print e tear_down( token, [ production_project_id, cms_project_id, atlas_project_id, computing_project_id, visualisation_project_id, services_project_id, operations_project_id, ], domain_id, ) f.close()
def pass_filter( value, col_name ): global features_by_col token = get_token( value ) if token in features_by_col[col_name]: return True