def __init__(self, config): self.server = config.get_server() self.tornado_server = None self.api_cache = {} self.registered_base_handlers = [] self.max_upload_size = config.getint('max_upload_size', 200) self.max_upload_size *= 1024 * 1024 # Set Up Websocket and Authorization Managers self.wsm = WebsocketManager(self.server) self.auth = Authorization(config['authorization']) mimetypes.add_type('text/plain', '.log') mimetypes.add_type('text/plain', '.gcode') mimetypes.add_type('text/plain', '.cfg') debug = config.getboolean('enable_debug_logging', True) # Set up HTTP only requests self.mutable_router = MutableRouter(self) app_handlers = [(AnyMatches(), self.mutable_router), (r"/websocket", WebSocket), (r"/api/version", EmulateOctoprintHandler)] self.app = tornado.web.Application(app_handlers, serve_traceback=debug, websocket_ping_interval=10, websocket_ping_timeout=30, parent=self) self.get_handler_delegate = self.app.get_handler_delegate # Register handlers logfile = config['cmd_args'].get('logfile') self.register_static_file_handler("moonraker.log", logfile) self.auth.register_handlers(self)
def refresh_token(cls, content): token = content.get('token', None) result, msg = Authorization.verify_refresh_token(token) if result: user = UserProcess.user_map.get(msg, None) if user: token = Authorization.generate_access_token(user.user_id) return {'access_token': token} return None
def wrapper(*args: Any, **kwargs: Any) -> Any: username = get_session_username(str(request.cookies.get(SESSION_ID))) authorization = Authorization(calendar_data=CalendarData(data_folder=config.DATA_FOLTER)) if "calendar_id" not in kwargs: raise ValueError("calendar_id") calendar_id = str(kwargs["calendar_id"]) if not authorization.can_access(username=username, calendar_id=calendar_id): abort(403) return decorated_function(*args, **kwargs)
def add_authorization(): get_json = json.loads(request) required = ['inputs', 'outputs', 'duration', 'timestamp'] if not all(k in get_json for k in required): return 'Missing values', 400 # Create a new Transaction authorization = Authorization(get_json['inputs'], get_json['outputs'], get_json['duration'], get_json['timestamp']) node.add_authorization(authorization) response = authorization.to_json() return jsonify(response), 201
class ProxyAuthorization(Header): def __init__(self, params=None): Header.__init__(self, params) self.name = "Proxy-Authorization" self.auth = Authorization() self.value = self.generate_valid_value() def generate_valid_value(self): return self.auth.generate_valid_value() def mutate_validity(self, value): return self.auth.mutate_validity(value) def mutate_length(self, value): return self.auth.mutate_length(value)
def login(cls, content): account_name = content.get('account_name', None) password = content.get('password', None) user = UserProcess.user_map.get(account_name, None) if not user or user.password != password: return {'message': '账户或密码不正确!'} return { 'message': 'success', 'super': '1' if account_name == 'ias_admin' else '0', 'access_token': Authorization.generate_access_token(user.user_id), 'refresh_token': Authorization.generate_refresh_token(user.user_name) }
def testGoodData(self): # корректные логин и пароль test_name = "TestUser" test_pass = "******" test_code = 0 real_code = Authorization.login(test_name, test_pass) res = real_code > test_code self.assertTrue(res)
def log(): if current_user.is_authenticated: return redirect(url_for('main_page')) form = LogForm() if form.validate_on_submit(): user = None try: user = User.get(User.login == form.login.data) except User.DoesNotExist: pass auth = Authorization() if user is None or not auth.check_password(user, form.password.data): return redirect(url_for('log')) login_user(user) return redirect(url_for('main_page')) return render_template('log.html', form=form)
def __init__(self, config): self.server = config.get_server() self.tornado_server = None self.api_cache = {} self.registered_base_handlers = [] self.max_upload_size = config.getint('max_upload_size', 1024) self.max_upload_size *= 1024 * 1024 # Set Up Websocket and Authorization Managers self.wsm = WebsocketManager(self.server) self.auth = Authorization(config['authorization']) mimetypes.add_type('text/plain', '.log') mimetypes.add_type('text/plain', '.gcode') mimetypes.add_type('text/plain', '.cfg') debug = config.getboolean('enable_debug_logging', False) log_level = logging.DEBUG if debug else logging.INFO logging.getLogger().setLevel(log_level) app_args = { 'serve_traceback': debug, 'websocket_ping_interval': 10, 'websocket_ping_timeout': 30, 'parent': self, 'default_handler_class': AuthorizedErrorHandler, 'default_handler_args': {} } if not debug: app_args['log_function'] = self.log_release_mode # Set up HTTP only requests self.mutable_router = MutableRouter(self) app_handlers = [(AnyMatches(), self.mutable_router), (r"/websocket", WebSocket)] self.app = tornado.web.Application(app_handlers, **app_args) self.get_handler_delegate = self.app.get_handler_delegate # Register handlers logfile = config['system_args'].get('logfile') if logfile: self.register_static_file_handler("moonraker.log", logfile, force=True) self.register_static_file_handler("klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True) self.auth.register_handlers(self)
def handle_dialog(req, res): user_id = req['session']['user_id'] session_id = req['session']['session_id'] if req['session']['new']: # Это новый пользователь. # Инициализируем сессию и поприветствуем его. sessionStorage[user_id] = { 'suggests': [ "Собрать тариф", "Пополнить счет", "Все что вы хотите!", ], 'current_flow': None } with open(session_path + session_id + '.pickle', 'wb') as f: pickle.dump(sessionStorage, f) f.close() auth = Authorization(session_id) auth.authorize(req['request'], res) return if "расскажи" in req['request']['nlu']['tokens']: res['response']['text'] = 'Я - новый умный помощник от команды "3 фронтендера и я". ' \ 'Пока что я могу выполнять такие функции:' res['response']['buttons'] = [ { "title": "Собрать тариф" }, { "title": "Пополнить счет" }, { "title": "Найти музыку" }, ] return # Обрабатываем ответ пользователя. auth = Authorization(session_id) if not auth.is_authorized(): auth.authorize(req['request'], res) return handler = GlobalHandler(session_id) handler.handle_request(req['request'], res)
def main(): print('initializing role based resource access system') dao = DataAccessObject() dao.load_data() authorization = Authorization(dao) ui = UserInterface(authorization) ui.start()
def admin_authorization(): cookies = request.cookies print(cookies) if request.method == "POST": username = request.form['username'] password = request.form['password'] admin = Authorization(username, password) if admin.check_log_pass_registration(): category_list = dbmanager.get_category_name() print(category_list) resp = make_response(redirect('/admin/db_access/')) resp.set_cookie('secret_key', dbmanager.secret_key) return resp else: return render_template('admin.html', error="Wrong data. Try again!") else: return render_template('admin.html')
class GlobalWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(400, 200, 400, 600) self.setWindowTitle('VkClient') self.setWhatsThis(QtCore.QString('hello')) self.setStyleSheet('background: #356AA0;') self.setFont(QtGui.QFont('Arial')) self.setMaximumSize(400, 600) self.setMinimumSize(400, 600) self.layout = QtGui.QVBoxLayout() self.top_frame = TopFrame() self.top_frame.show() self.user_frame = UserFrame() self.authorization = Authorization(self.user_frame) self.authorization.show() self.user_frame.show() self.layout.addWidget(self.top_frame,1) self.layout.addWidget(self.user_frame, 2) self.setLayout(self.layout)
def __init__(self, server, args): self.server = server self.tornado_server = None self.api_cache = {} self.registered_base_handlers = [] # Set Up Websocket and Authorization Managers self.wsm = WebsocketManager(server) self.auth = Authorization(args.apikey) mimetypes.add_type('text/plain', '.log') mimetypes.add_type('text/plain', '.gcode') mimetypes.add_type('text/plain', '.cfg') # Set up HTTP only requests self.mutable_router = MutableRouter(self) app_handlers = [(AnyMatches(), self.mutable_router), (r"/websocket", WebSocket, { 'wsm': self.wsm, 'auth': self.auth }), (r"/api/version", EmulateOctoprintHandler, { 'server': server, 'auth': self.auth })] self.app = tornado.web.Application(app_handlers, serve_traceback=args.debug, websocket_ping_interval=10, websocket_ping_timeout=30, enable_cors=False) self.get_handler_delegate = self.app.get_handler_delegate # Register handlers self.register_static_file_handler("moonraker.log", args.logfile) self.auth.register_handlers(self)
class MoonrakerApp: def __init__(self, server, args): self.server = server self.tornado_server = None self.api_cache = {} self.registered_base_handlers = [] # Set Up Websocket and Authorization Managers self.wsm = WebsocketManager(server) self.auth = Authorization(args.apikey) mimetypes.add_type('text/plain', '.log') mimetypes.add_type('text/plain', '.gcode') mimetypes.add_type('text/plain', '.cfg') # Set up HTTP only requests self.mutable_router = MutableRouter(self) app_handlers = [(AnyMatches(), self.mutable_router), (r"/websocket", WebSocket, { 'wsm': self.wsm, 'auth': self.auth }), (r"/api/version", EmulateOctoprintHandler, { 'server': server, 'auth': self.auth })] self.app = tornado.web.Application(app_handlers, serve_traceback=args.debug, websocket_ping_interval=10, websocket_ping_timeout=30, enable_cors=False) self.get_handler_delegate = self.app.get_handler_delegate # Register handlers self.register_static_file_handler("moonraker.log", args.logfile) self.auth.register_handlers(self) def listen(self, host, port): self.tornado_server = self.app.listen(port, address=host, max_body_size=MAX_UPLOAD_SIZE, xheaders=True) async def close(self): if self.tornado_server is not None: self.tornado_server.stop() await self.wsm.close() self.auth.close() def load_config(self, config): if 'enable_cors' in config: self.app.settings['enable_cors'] = config['enable_cors'] self.auth.load_config(config) def register_remote_handler(self, endpoint): if endpoint in RESERVED_ENDPOINTS: return api_def = self.api_cache.get(endpoint, self._create_api_definition(endpoint)) if api_def.uri in self.registered_base_handlers: # reserved handler or already registered return logging.info("Registering remote endpoint: (%s) %s" % (" ".join(api_def.request_methods), api_def.uri)) self.wsm.register_handler(api_def) params = {} params['server'] = self.server params['auth'] = self.auth params['methods'] = api_def.request_methods params['arg_parser'] = api_def.parser params['remote_callback'] = api_def.endpoint self.mutable_router.add_handler(api_def.uri, RemoteRequestHandler, params) self.registered_base_handlers.append(api_def.uri) def register_local_handler(self, uri, ws_method, request_methods, callback, http_only=False): if uri in self.registered_base_handlers: return api_def = self._create_api_definition(uri, ws_method, request_methods) logging.info("Registering local endpoint: (%s) %s" % (" ".join(request_methods), uri)) if not http_only: self.wsm.register_handler(api_def, callback) params = {} params['server'] = self.server params['auth'] = self.auth params['methods'] = request_methods params['arg_parser'] = api_def.parser params['callback'] = callback self.mutable_router.add_handler(uri, LocalRequestHandler, params) self.registered_base_handlers.append(uri) def register_static_file_handler(self, pattern, file_path, can_delete=False, op_check_cb=None): if pattern[0] != "/": pattern = "/server/files/" + pattern if os.path.isfile(file_path): pattern += '()' elif os.path.isdir(file_path): if pattern[-1] != "/": pattern += "/" pattern += "(.*)" else: logging.info("Invalid file path: %s" % (file_path)) return methods = ['GET'] if can_delete: methods.append('DELETE') params = { 'server': self.server, 'auth': self.auth, 'path': file_path, 'methods': methods, 'op_check_cb': op_check_cb } self.mutable_router.add_handler(pattern, FileRequestHandler, params) def register_upload_handler(self, pattern): params = {'server': self.server, 'auth': self.auth} self.mutable_router.add_handler(pattern, FileUploadHandler, params) def remove_handler(self, endpoint): api_def = self.api_cache.get(endpoint) if api_def is not None: self.wsm.remove_handler(api_def.uri) self.mutable_router.remove_handler(api_def.ws_method) def _create_api_definition(self, endpoint, ws_method=None, request_methods=['GET', 'POST']): if endpoint in self.api_cache: return self.api_cache[endpoint] if endpoint[0] == '/': uri = endpoint else: uri = "/printer/" + endpoint if ws_method is None: ws_method = uri[1:].replace('/', '_') if endpoint.startswith("objects/"): parser = _status_parser else: parser = _default_parser api_def = APIDefinition(endpoint, uri, ws_method, request_methods, parser) self.api_cache[endpoint] = api_def return api_def
def testPassCase(self): # неправильный пароль - в другом регистре test_name = "TestUser" test_pass = "******" test_code = -102 real_code = Authorization.login(test_name, test_pass) self.assertEqual(test_code, real_code)
class MoonrakerApp: def __init__(self, config): self.server = config.get_server() self.tornado_server = None self.api_cache = {} self.registered_base_handlers = [] self.max_upload_size = config.getint('max_upload_size', 1024) self.max_upload_size *= 1024 * 1024 # Set Up Websocket and Authorization Managers self.wsm = WebsocketManager(self.server) self.auth = Authorization(config['authorization']) mimetypes.add_type('text/plain', '.log') mimetypes.add_type('text/plain', '.gcode') mimetypes.add_type('text/plain', '.cfg') debug = config.getboolean('enable_debug_logging', False) log_level = logging.DEBUG if debug else logging.INFO logging.getLogger().setLevel(log_level) app_args = { 'serve_traceback': debug, 'websocket_ping_interval': 10, 'websocket_ping_timeout': 30, 'parent': self, 'default_handler_class': AuthorizedErrorHandler, 'default_handler_args': {} } if not debug: app_args['log_function'] = self.log_release_mode # Set up HTTP only requests self.mutable_router = MutableRouter(self) app_handlers = [(AnyMatches(), self.mutable_router), (r"/websocket", WebSocket)] self.app = tornado.web.Application(app_handlers, **app_args) self.get_handler_delegate = self.app.get_handler_delegate # Register handlers logfile = config['system_args'].get('logfile') if logfile: self.register_static_file_handler("moonraker.log", logfile, force=True) self.register_static_file_handler("klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True) self.auth.register_handlers(self) def listen(self, host, port): self.tornado_server = self.app.listen(port, address=host, max_body_size=MAX_BODY_SIZE, xheaders=True) def log_release_mode(self, handler): status_code = handler.get_status() if status_code in [200, 204]: # don't log OK and No Content return if status_code < 400: log_method = access_log.info elif status_code < 500: log_method = access_log.warning else: log_method = access_log.error request_time = 1000.0 * handler.request.request_time() log_method("%d %s %.2fms", status_code, handler._request_summary(), request_time) def get_server(self): return self.server def get_auth(self): return self.auth def get_websocket_manager(self): return self.wsm async def close(self): if self.tornado_server is not None: self.tornado_server.stop() await self.tornado_server.close_all_connections() await self.wsm.close() self.auth.close() def register_remote_handler(self, endpoint): if endpoint in RESERVED_ENDPOINTS: return api_def = self._create_api_definition(endpoint) if api_def.uri in self.registered_base_handlers: # reserved handler or already registered return logging.info( f"Registering remote endpoint - " f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; " f"Websocket: {', '.join(api_def.ws_methods)}") self.wsm.register_remote_handler(api_def) params = {} params['methods'] = api_def.request_methods params['callback'] = api_def.endpoint params['need_object_parser'] = api_def.need_object_parser self.mutable_router.add_handler(api_def.uri, DynamicRequestHandler, params) self.registered_base_handlers.append(api_def.uri) def register_local_handler(self, uri, request_methods, callback, protocol=["http", "websocket"], wrap_result=True): if uri in self.registered_base_handlers: return api_def = self._create_api_definition(uri, request_methods, is_remote=False) msg = "Registering local endpoint" if "http" in protocol: msg += f" - HTTP: ({' '.join(request_methods)}) {uri}" params = {} params['methods'] = request_methods params['callback'] = callback params['wrap_result'] = wrap_result params['is_remote'] = False self.mutable_router.add_handler(uri, DynamicRequestHandler, params) self.registered_base_handlers.append(uri) if "websocket" in protocol: msg += f" - Websocket: {', '.join(api_def.ws_methods)}" self.wsm.register_local_handler(api_def, callback) logging.info(msg) def register_static_file_handler(self, pattern, file_path, force=False): if pattern[0] != "/": pattern = "/server/files/" + pattern if os.path.isfile(file_path) or force: pattern += '()' elif os.path.isdir(file_path): if pattern[-1] != "/": pattern += "/" pattern += "(.*)" else: logging.info(f"Invalid file path: {file_path}") return logging.debug(f"Registering static file: ({pattern}) {file_path}") params = {'path': file_path} self.mutable_router.add_handler(pattern, FileRequestHandler, params) def register_upload_handler(self, pattern): self.mutable_router.add_handler( pattern, FileUploadHandler, {'max_upload_size': self.max_upload_size}) def remove_handler(self, endpoint): api_def = self.api_cache.get(endpoint) if api_def is not None: self.wsm.remove_handler(api_def.uri) self.mutable_router.remove_handler(api_def.ws_method) def _create_api_definition(self, endpoint, request_methods=[], is_remote=True): if endpoint in self.api_cache: return self.api_cache[endpoint] if endpoint[0] == '/': uri = endpoint elif is_remote: uri = "/printer/" + endpoint else: uri = "/server/" + endpoint ws_methods = [] if is_remote: # Remote requests accept both GET and POST requests. These # requests execute the same callback, thus they resolve to # only a single websocket method. ws_methods.append(uri[1:].replace('/', '.')) request_methods = ['GET', 'POST'] else: name_parts = uri[1:].split('/') if len(request_methods) > 1: for req_mthd in request_methods: func_name = req_mthd.lower() + "_" + name_parts[-1] ws_methods.append(".".join(name_parts[:-1] + [func_name])) else: ws_methods.append(".".join(name_parts)) if not is_remote and len(request_methods) != len(ws_methods): raise self.server.error( "Invalid API definition. Number of websocket methods must " "match the number of request methods") need_object_parser = endpoint.startswith("objects/") api_def = APIDefinition(endpoint, uri, ws_methods, request_methods, need_object_parser) self.api_cache[endpoint] = api_def return api_def
def __init__(self, params=None): Header.__init__(self, params) self.name = "Proxy-Authorization" self.auth = Authorization() self.value = self.generate_valid_value()
def testBadLogin(self): # неправильный логин test_name = "UserNotExist" test_pass = "******" test_code = -101 real_code = Authorization.login(test_name, test_pass) self.assertEqual(test_code, real_code)
def testEmptyLogin(self): # пустой логин test_name = '' test_pass = "******" test_code = -101 real_code = Authorization.login(test_name, test_pass) self.assertEqual(test_code, real_code)
class MoonrakerApp: def __init__(self, config): self.server = config.get_server() self.tornado_server = None self.api_cache = {} self.registered_base_handlers = [] self.max_upload_size = config.getint('max_upload_size', 200) self.max_upload_size *= 1024 * 1024 # Set Up Websocket and Authorization Managers self.wsm = WebsocketManager(self.server) self.auth = Authorization(config['authorization']) mimetypes.add_type('text/plain', '.log') mimetypes.add_type('text/plain', '.gcode') mimetypes.add_type('text/plain', '.cfg') debug = config.getboolean('enable_debug_logging', True) # Set up HTTP only requests self.mutable_router = MutableRouter(self) app_handlers = [(AnyMatches(), self.mutable_router), (r"/websocket", WebSocket), (r"/api/version", EmulateOctoprintHandler)] self.app = tornado.web.Application(app_handlers, serve_traceback=debug, websocket_ping_interval=10, websocket_ping_timeout=30, parent=self) self.get_handler_delegate = self.app.get_handler_delegate # Register handlers logfile = config['cmd_args'].get('logfile') self.register_static_file_handler("moonraker.log", logfile) self.auth.register_handlers(self) def listen(self, host, port): self.tornado_server = self.app.listen( port, address=host, max_body_size=self.max_upload_size, xheaders=True) def get_server(self): return self.server def get_auth(self): return self.auth def get_websocket_manager(self): return self.wsm async def close(self): if self.tornado_server is not None: self.tornado_server.stop() await self.tornado_server.close_all_connections() await self.wsm.close() self.auth.close() def register_remote_handler(self, endpoint): if endpoint in RESERVED_ENDPOINTS: return api_def = self._create_api_definition(endpoint) if api_def.uri in self.registered_base_handlers: # reserved handler or already registered return logging.info( f"Registering remote endpoint - " f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; " f"Websocket: {', '.join(api_def.ws_methods)}") self.wsm.register_remote_handler(api_def) params = {} params['arg_parser'] = api_def.parser params['remote_callback'] = api_def.endpoint self.mutable_router.add_handler(api_def.uri, RemoteRequestHandler, params) self.registered_base_handlers.append(api_def.uri) def register_local_handler(self, uri, request_methods, callback, protocol=["http", "websocket"]): if uri in self.registered_base_handlers: return api_def = self._create_api_definition(uri, request_methods, is_remote=False) msg = "Registering local endpoint" if "http" in protocol: msg += f" - HTTP: ({' '.join(request_methods)}) {uri}" params = {} params['methods'] = request_methods params['arg_parser'] = api_def.parser params['callback'] = callback self.mutable_router.add_handler(uri, LocalRequestHandler, params) self.registered_base_handlers.append(uri) if "websocket" in protocol: msg += f" - Websocket: {', '.join(api_def.ws_methods)}" self.wsm.register_local_handler(api_def, callback) logging.info(msg) def register_static_file_handler(self, pattern, file_path): if pattern[0] != "/": pattern = "/server/files/" + pattern if os.path.isfile(file_path): pattern += '()' elif os.path.isdir(file_path): if pattern[-1] != "/": pattern += "/" pattern += "(.*)" else: logging.info(f"Invalid file path: {file_path}") return logging.debug(f"Registering static file: ({pattern}) {file_path}") params = {'path': file_path} self.mutable_router.add_handler(pattern, FileRequestHandler, params) def register_upload_handler(self, pattern): self.mutable_router.add_handler(pattern, FileUploadHandler, {}) def remove_handler(self, endpoint): api_def = self.api_cache.get(endpoint) if api_def is not None: self.wsm.remove_handler(api_def.uri) self.mutable_router.remove_handler(api_def.ws_method) def _create_api_definition(self, endpoint, request_methods=[], is_remote=True): if endpoint in self.api_cache: return self.api_cache[endpoint] if endpoint[0] == '/': uri = endpoint elif is_remote: uri = "/printer/" + endpoint else: uri = "/server/" + endpoint ws_methods = [] if is_remote: # Remote requests accept both GET and POST requests. These # requests execute the same callback, thus they resolve to # only a single websocket method. ws_methods.append(uri[1:].replace('/', '.')) request_methods = ['GET', 'POST'] else: name_parts = uri[1:].split('/') if len(request_methods) > 1: for req_mthd in request_methods: func_name = req_mthd.lower() + "_" + name_parts[-1] ws_methods.append(".".join(name_parts[:-1] + [func_name])) else: ws_methods.append(".".join(name_parts)) if not is_remote and len(request_methods) != len(ws_methods): raise self.server.error( "Invalid API definition. Number of websocket methods must " "match the number of request methods") if endpoint.startswith("objects/"): parser = _status_parser else: parser = _default_parser api_def = APIDefinition(endpoint, uri, ws_methods, request_methods, parser) self.api_cache[endpoint] = api_def return api_def
def testLoginCase(self): # правильный логин - в другом регистре test_name = "testuser" test_pass = "******" test_code = -101 real_code = Authorization.login(test_name, test_pass) self.assertEqual(test_code, real_code)
def testEmptyPass(self): # пустой пароль test_name = "TestUser" test_pass = '' test_code = -102 real_code = Authorization.login(test_name, test_pass) self.assertEqual(test_code, real_code)
def testBadPass(self): # неправильный пароль test_name = "TestUser" test_pass = "******" test_code = -102 real_code = Authorization.login(test_name, test_pass) self.assertEqual(test_code, real_code)
def test_authorized_if_calendar_user_in_list_using_calendar_data( authorization: Authorization) -> None: data = {"users": [EXISTING_USERNAME]} assert authorization.can_access(username=EXISTING_USERNAME, data=data) is True
import urllib3 import sys from authorization import Authorization from employee import Employee from erp_organization import Organization from workspace import Workspace from dbconnect import DBConnect urllib3.disable_warnings() env = sys.argv[1] space_name = sys.argv[2] email = sys.argv[3] new_space = Workspace(env) new_space_admin = Employee(env) db = DBConnect(env) space_guid = new_space.create_workspace(space_name=space_name, space_code=space_name) new_space_admin.create_admin_for_new_space(space_guid, email) auth = Authorization(env) headers = auth.create_headers(email) new_organization_guid = Organization(env, headers).add_organization('Owner') new_space.set_space_owner(new_organization_guid) new_space_admin.add_admin_to_employees(new_organization_guid, headers) print(space_guid, space_name, email)
def __init__(self, env, headers): self._base_url = base_url_from_env(env) self._headers = headers self._spaceGuid = headers['SpaceGuid'] def add_organization(self, organization_title): url = self._base_url + 'ctms/api/v1/organizations/create' data = { 'statusGuid': '655aa6f2-434a-4b8d-8254-722d160e611e', # Active 'categoryGuid': 'b6b010d3-2a9b-4e93-8db8-01cd6056b713', # CRO 'countryGuid': '2876aae7-b8f5-4a35-bf61-9ad69f12ccc0', # Russia 'spaceGuid': self._spaceGuid, 'name': organization_title, 'addresses': [], 'createdByGuid': '1d99e18d-a366-4b91-956e-1388463ba09f' } response = requests.post(url, headers=self._headers, json=data, verify=False) if response.status_code != 200: print(response.status_code, response.text) raise Exception('Не удалось создать организацию') else: organization_guid = response.json()['GuidCode'] return organization_guid if __name__ == '__main__': from authorization import Authorization headers_for_test = Authorization('test').create_headers('*****@*****.**', 'somepwd') new_organization_guid = Organization('test', headers_for_test).add_organization('test_4111') print(new_organization_guid)
def test_authorized_if_calendar_user_in_list( authorization: Authorization) -> None: assert authorization.can_access(username=EXISTING_USERNAME, calendar_id="sample_data_file") is True
db = DBConnect(env) while True: space_name = input("Введите Имя Спейса (должно быть уникальным): ") if space_name.lower() in db.space_codes_on_server(): print("Пространство с таким именем уже сущестует. Введите другое имя") continue break while True: email = input("Введите валидный email (логин должен быть уникальным в рамках всех спейсов): ") if new_space_admin.login_exists(email): print("Логин занят") continue break space_guid = new_space.create_workspace(space_name=space_name, space_code=space_name) new_space_admin.create_admin_for_new_space(space_guid, email, DEFAULT_ADMIN_PASSWORD) print(f"\n\nСпейс {space_name} создан. Логин - {email}, Пароль - {DEFAULT_ADMIN_PASSWORD}") auth = Authorization(env) headers = auth.create_headers(email, password=DEFAULT_ADMIN_PASSWORD) new_organization_guid = Organization(env, headers).add_organization(DEFAULT_FIRST_ORGANIZATION_TITLE) print(f"В спейсе с Guid-кодом - {space_guid} создана организация {DEFAULT_FIRST_ORGANIZATION_TITLE}") new_space.set_space_owner(new_organization_guid) new_space_admin.add_admin_to_employees(new_organization_guid, headers) input("Press any key to exit")
def test_unauthorized_if_calendar_user_not_in_list( authorization: Authorization) -> None: assert authorization.can_access(username="******", calendar_id="sample_data_file") is False
def authorization() -> Authorization: return Authorization(calendar_data=CalendarData("test/fixtures"))