Exemple #1
0
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)
Exemple #2
0
    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)
Exemple #3
0
 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)
Exemple #4
0
def main():
    print('initializing role based resource access system')

    dao = DataAccessObject()
    dao.load_data()

    authorization = Authorization(dao)

    ui = UserInterface(authorization)
    ui.start()
Exemple #5
0
        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
Exemple #6
0
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)
Exemple #7
0
    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)
Exemple #8
0
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')
Exemple #9
0
    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)
Exemple #10
0
    def __init__(self):
        '''инициализирует игру и создает игровые ресурсы'''

        pygame.init()

        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Cactus evolution")

        self.clicker = Clicker(self)

        self.arrows = pygame.sprite.Group()
        self.game_folder = os.path.dirname(__file__)
        self.sounds_folder = os.path.join(self.game_folder, 'sounds')

        self.passed_time = 0
        self.start_game_time = time.time()
        self.clock = pygame.time.Clock()

        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.au = Authorization(self)

        self.last = None
        self.in_mission = False

        self.time = None
        self.access = False
        self.random_color = None

        self.left = False
        self.right = False
        self.up = False
        self.down = False

        self.current_color = None

        #Создание кнопки Play
        self.play_button = Button(self, "Play")

        self.start_time = None
        self.music_play = False
        self.waiting = True
        self.pause = False

        self.start_countdown = True
        self.timer = False
        #self.timer_h = 1
        self.timer_s = self.settings.timer
        self.timer_tick = None
        self.timer_access = True

        #Меню
        self.menu_access = True
        self.check_start_game = False
        self.menu = Menu(self)
        self.multiplayer_access = False
        self.singleplayer_access = False
        self.shop_access = False
        self.end_access = False

        self.reset_arrows = True
        self.authorization_access = True
        self.user_login = ''
        self.user_password = ''
        self.font = pygame.font.Font(None, 32)
        self.text_surface = None

        self.write_access_login = False
        self.write_access_password = False
        self.login = ''
        self.password = ''
        self.bool_resp = None
        self.without_symb = None

        self.multiplayer_timer = 30
        self.multiplayer_ticks = None
        self.mu = Multiplayer(self)
        self.SSP_access = True
        self.step = None

        self.reg = Registration(self)
        self.reg_access = False

        #Мультиплеер - инфа о игроках и игре
        self.search_game_access = False
        self.end_round = False
        self.interval = 3
        self.start_room = False
        self.CLIENT_ID = None
        self.enemy_id = None
        self.game_data = {}
        self.game_search_ticks = None
        self.game_search_timer = None

        self.search_button = True
        self.choise = False

        self.my_health_loss = 0
        self.enemy_health_loss = 0
        self.my_health = None
        self.enemy_health = 1000
        self.end_multiplayer_game_access = False
        self.rez = ''

        self.shop = Shop(self)
        self.level = None
        self.next_level_exp = None
        self.exp = None
        self.coins = None
        self.singleplayer_coins = 0
        self.multiplayer_coins = 0
        self.multiplayer_add_coins = False
        self.singleplayer_add_coins = False
        self.singleplayer_exp = 0
        self.multiplayer_exp = 0
from starcodes import StarCodes
from authorization import Authorization

for filename in os.listdir("/tmp"):
    os.remove("/tmp/{:s}".format(filename))

config = Configuration('config')

led = StatusLED()
led.start()
conn = Connection(config, status_led=led)
conn.start()
kpd = Keypad(config, status_led=led, layout=TEL_16_KEY)
kpd.start()

auth = Authorization(config, status_led=led)
starcode = StarCodes(config, auth, status_led=led)


async def watch_events(keypad):
    while True:
        event = await keypad.queue.get()
        user_code = "".join(
            event[:config.CODE_LENGTH])  # We leave the user code as a string
        if len(user_code) is 0: user_code = None
        if "*" in event:
            handle_event = starcode.runcode(int("".join(
                event[-2:])))  # But we convert starcodes to ints
        else:
            handle_event = lambda *args, **kwargs: None
        if user_code is not None and auth.check_code(user_code):
    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)
Exemple #13
0
 def __init__(self, params=None):
     Header.__init__(self, params)
     self.name = "Proxy-Authorization"
     self.auth = Authorization()
     self.value = self.generate_valid_value()
Exemple #14
0
        if state == 'PLAYER_STOPPED':
            play_next(recommendations, instance)
        sleep_timer_set = True
        sleep_timer = Timer(sleep_interval,
                            sleep_callback,
                            args=[recommendations])
        sleep_timer.start()
    else:
        sleep_timer_set = False


if __name__ == '__main__':
    with open('credentials') as f:
        client_id = f.readline().strip()
        client_secret = f.readline().strip()
    authorization = Authorization(client_id, client_secret)
    access_token = authorization.get_access_token()
    recommendations = Recommendations(access_token)
    instance = Instance()

    while True:
        k = getch()
        if k == ' ':
            play_pause(recommendations, instance)
        elif k == '.':
            stop(recommendations)
        elif k == 'm':
            set_sleep_timer(recommendations, instance)
        elif k == 'q':
            sleep_timer_set = False
            if sleep_timer is not None:
Exemple #15
0
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")
Exemple #16
0
        def upload_data():
            # check if got enough values
            get_json = request.get_json()
            print(get_json)
            print(type(get_json))
            required = ['public_key', 'data', 'timestamp', 'op', 'signature']
            if not all(k in get_json for k in required):
                return 'Missing values', 400
            public_key = get_json['public_key']
            data = get_json['data']
            timestamp = get_json['timestamp']
            op = get_json['op']
            hash = hashlib.sha256((str(data) + str(timestamp) + str(0)).encode()).hexdigest()
            signature = get_json['signature']

            # check if op is upload operation
            if op != 0:
                return 'op is not matched!', 400

            # check if there is enough room
            if len(self._database) + len(get_json['data']) >= MAX_DATA_RANGE:
                return 'no enough storage', 400

            # check if timestamp is not expired
            if timestamp + 600 < time.time():
                return 'Request expired', 400

            # check if signature is matched
            print(signature)
            print(type(signature))

            if not verify_signature(public_key, hash, eval(signature)):
                return 'Signature unmatched', 400

            # everything is fine then store data into database
            if type(data) is 'list':
                self._database += data
            else:
                self._database.append(data)

            # generate a new authorization
            input = Input(0, 0, 0)

            if type(data) is 'list':
                data_url = DataURL(len(self._database) - len(data), len(self._database))
            else:
                data_url = DataURL(len(self._database) - 1, len(self._database))
            output = Output(recipient=public_key, data_url=data_url, limit=Limit(7))

            authorization = Authorization(inputs=[input], outputs=[output], duration=Duration(), timestamp=time.time())

            # sign this authorization
            input.add_signature(self._account.sign_message(authorization.calc_hash()))

            # store this authorization and broadcast it
            auth_number = self.add_authorization(authorization)
            print(auth_number)
            # return the position of authorization to client
            response = {
                'block_number': self._blockchain.get_height(),
                'auth_number': auth_number,
                'output_number': 0
            }
            return jsonify(response), 201
            colored("Ragnar image search retrieval OK, metadata saved to:\n{}".
                    format(self.path_RESULTS),
                    color='green'))
        write_json(self.retr_results,
                   self.path_RESULTS + "Ragnar_retrieved_results.json")


if __name__ == "__main__":
    import asyncio
    from authorization import Authorization

    loop = asyncio.get_event_loop()

    # In order to run you must have valid Token in the files,
    # run main.py or uncomment Authorization:

    # Authorization ->
    auth = Authorization(loop)
    if not (auth.check_token(path_token)):
        auth.request_token(path_credentials)
    # Authorization <-

    path_RESULTS = set_output_path()
    image_search = ImageSearch(loop, path_dataset, path_area_of_interest,
                               path_RESULTS)
    pipelineId = image_search.initialize()
    image_search.retrieve(pipelineId)
    Ragnar_retrieved_results = image_search.retr_results

    loop.close()
Exemple #18
0
'''
"""
    server pubkey: 59be9bbd5224fb4d69a861c3cd934ca07e2e56de148e988fcff7df8f47b98bcac15c0e3427433004e0a650cde005f4d5
    private_key: ae4d632b868f04b9fc9b69898f4a8a555f10c64e35cf7692
    or b'\xaeMc+\x86\x8f\x04\xb9\xfc\x9bi\x89\x8fJ\x8aU_\x10\xc6N5\xcfv\x92'
"""
SERVER_ADDRESS = Address("ae4d632b868f04b9fc9b69898f4a8a555f10c64e35cf7692")

out = Output(
    recipient=
    '59be9bbd5224fb4d69a861c3cd934ca07e2e56de148e988fcff7df8f47b98bcac15c0e3427433004e0a650cde005f4d5',
    start=0,
    end=MAX_DATA_RANGE,
    limit=7)
auth = Authorization(inputs=[],
                     outputs=[out],
                     duration=Duration(0),
                     timestamp=1516156465.8362110)
"""
"genesis block":
{
    'prev_hash': "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
    'now_hash': '00003a3db614a00c0b620518c466a54b827cd756558765d48e887ce0445648c0',
    'timestamp': 1516156465.836211,
    'hash_root': '0c41debab6af9066e687e4df07a212174e112c727922a27c27cfe64c94c547af',
    'nonce': 89734,
    'authorizations':
    [{
        'inputs': [],
        'outputs': [{
            'recipient': '59be9bbd5224fb4d69a861c3cd934ca07e2e56de148e988fcff7df8f47b98bcac15c0e3427433004e0a650cde005f4d5',
            'dataURL': {
Exemple #19
0
import pymongo
from app import create_app
from persistence_gateway import UserRepository, TemplateRepository
import os


def __get_env_variable(env_variable_name, default_value):
    env_variables = os.environ
    env_variable_value = default_value
    if env_variable_name in env_variables.keys():
        env_variable_value = env_variables[env_variable_name]
    return env_variable_value


secret = __get_env_variable('SPICEBLUE_AUTHORIZATION_SECRET', "secret")
authorization = Authorization(secret)

default_uri = "mongodb+srv://test:[email protected]/mydatabase?retryWrites=true&w=majority"
database_uri = __get_env_variable("SPICEBLUE_CONNECTION_STRING", default_uri)
mongo_client = pymongo.MongoClient(database_uri)
templates_db = mongo_client["mydatabase"]
template_repository = TemplateRepository(templates_db)
user_repository = UserRepository(templates_db)

template_service = Business(template_repository, authorization,
                            user_repository)
app = create_app(template_service)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=80)
def authorization() -> Authorization:
    return Authorization(calendar_data=CalendarData("test/fixtures"))
Exemple #21
0
from AccountDAO_DB import AccountMongoDBService
from authorization import Authorization
from AccountOps import AccountOperations
from Machine import Machine
from SessionTimer import SessionTimer

logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
    filename='runtime.log',
    level=logging.DEBUG)
logger = logging.getLogger("main")

#All service initializations
machine = Machine("10000")
data_svc = AccountMongoDBService()
auth_svc = Authorization(data_svc)
ops_svc = AccountOperations(data_svc, auth_svc, machine)


def call(func, args):
    func(args)


def start():

    SESSION_TIMEOUT = 120  #session length is 2 minutes.
    session_timer = None
    """entrypoint to atm demo.  Initializes services and begins the main program loop"""

    #Main loop
    logger.debug("Entering main loop")