コード例 #1
0
async def put_flag_in_deleted_messages(request: PutRequest) -> Verdict:
    async with Api(f'http://{request.hostname}:3000') as api:
        user = User()
        try:
            await api.register(user.get_register_data())
            await api.login(user.username, user.password)
        except InvalidResponseException as e:
            return Verdict.MUMBLE('Could not login or register',
                                  traceback.format_exc())
        except:
            return Verdict.DOWN('Could not connect to service',
                                traceback.format_exc())

        chat_name = utils.generate_random_text()

        try:
            chat_resp = await api.create(chat_name)
            chat_id = chat_resp['chatId']
            message_id_resp = await api.send_message(chat_id, request.flag)
            message_id = message_id_resp['messageId']
            await api.delete_message(message_id)
        except:
            return Verdict.MUMBLE(
                'Could not create chat or invite link or send message',
                traceback.format_exc())

        return Verdict.OK(
            f'{user.username}:{user.password}:{chat_id}:{message_id}')
コード例 #2
0
ファイル: api.py プロジェクト: opendev-jb/jeopardy-trainer
def login():
    user = User(request.form['name'], request.form['password'])
    if(user.login(jeopardyDB)):
        resp = make_response(json.dumps({}))
        resp.set_cookie('session', value=user.session)
        return resp
    return jsonify(user.to_dict())
コード例 #3
0
def setup(env, conf, scenario):
    scenario["containers"] = []

    # Create and setup the resources
    resources = {}
    for i in range(conf["resources"]["number"]):
        id_capacity_conf = random.randint(
            0,
            len(conf["resources"]["capacities"]) - 1)
        resources[i] = Resource(
            i, conf["resources"]["capacities"][id_capacity_conf], env, seed=i)
    scenario["resources"] = resources

    # Create Service Discovery process
    service_discovery = ServiceDiscovery(env, resources, scenario)
    scenario["SD"] = service_discovery

    # Population infrastructure
    for id in range(conf["users"]):
        u = User(id, env, service_discovery, scenario)
        env.process(u.start())

    env.process(execution_context(env, scenario))
    # setup function must be a simpy.generator, not elegant but...
    while True:
        yield env.timeout(10000000)
コード例 #4
0
ファイル: api.py プロジェクト: opendev-jb/jeopardy-trainer
def check_session(request):
    if 'session' not in request.cookies:
        raise Unauthorized('You need to log in')
    user = User(session=request.cookies['session'])
    if user.check_session(jeopardyDB):
        return user
    raise Unauthorized('Invalid session')
コード例 #5
0
def pickup():

    global smart_car
    # Retrieves the cookie header and splits the string so only the value remains
    user_id = request.headers['Cookie'][3:]

    # Parses the JSON payload
    location = node_finder(carpool.graph, request.json["location"][0], request.json["location"][1])
    destination = node_finder(carpool.graph, request.json["destination"][0], request.json["destination"][1])

    # Finds or creates a user
    user = carpool.find_user(user_id)
    if user is None:
        user = User(user_id, location, destination)
        carpool.add_user(user)

    # Updates the user's location with the ones send in the JSON payload
    user.update_location(location)

    car = carpool.logic(location, destination)
    if car:
        # If a car was found for the customer, then this customer is added as a passenger.
        car.add_passenger(user)

        # This returns the location of the car that was found.
        return jsonify({"carLocation": car.location.json()}), 200

    # This return message should be improved.
    # The intention is to return status that no car was found.
    return "no car"
コード例 #6
0
    def setUp(self):
        self.user_repository = UserRepository(test_database_connection())
        self.user_service = UserService(self.user_repository)
        self.user_repository.delete_all()

        self.test_user_one = User('testuser', 'testuser1', 1)
        self.test_user_two = User('secondo', 'testuser2', 2)
コード例 #7
0
ファイル: user.py プロジェクト: afeef200/ionicandflask
def signIn(username, password):
    user = users_table.find_one(username=username)
    if (user):
        user = User(**(user))
        if (password == user.password):
            user.password = ''
    return user
コード例 #8
0
ファイル: main.py プロジェクト: Rout222/tecprime
def updateUser(id):
    # montar o usuário
    posted_user = UserSchema(only=('email', 'first_name', 'last_name',
                                   'avatar')).load(request.get_json())

    user = User(**posted_user.data)

    #bom, temos dois casos aqui, se for pra editar um usuário da API, então salva ele editado no banco de dados, caso contrário edite ele.
    #pegando os dados da API web
    req = urllib.request.Request(API_URL.format(id, 1), headers=headers)
    with urllib.request.urlopen(req) as response:
        data = json.loads(response.read().decode())
        api_user = data['data']

        if (len(api_user) > 0):  #se existe é na APIWEB
            # caso a API fosse integrada
            #deleteFromAPI(id)

            # salvar no banco de dados local
            db.table('users').insert(user.save())

        else:  #caso contrário edita no banco
            api_total = int(data['total'])
            idtinyDB = id - api_total
            db.table('users').update(user.save(), doc_ids=[idtinyDB])

    return ('', 200)
コード例 #9
0
    def post(self):
        try:
            email = self.request.get('email')
            hkey = self.request.get('hkey')
            
            tenant_id = tenant.get_tenant_id(email)
            namespace_manager.set_namespace(tenant_id)

            if User.get_by_key_name(email):
                raise AppError(u'このメールアドレスは、既に登録されています。')

            if self.request.get('button') == 'Send Activate Key':
                key = ActivateKey.make(email)
                self.send_activate_key(email, key[:12])
                hkey = key[12:]
                self.render_template('signup.html', {'email': email, 'hkey': hkey})
                return
            else:
                key = self.request.get('key1') + self.request.get('key2') + self.request.get('key3') + self.request.get('hkey')
                if not ActivateKey.validate(email, key):
                    raise AppError(u'不正な Activate Key です。')
                password = self.request.get('password')
                if not string.strip(password):
                    raise AppError(u'パスワードが未入力です。')
                user = User(key_name=email, email=email, password=hashlib.md5(email + password).hexdigest())
                user.put()
                self.redirect('/')

        except AppError, e:
            self.render_template('signup.html', {'error_msg': e.message, 'email': email, 'hkey': hkey})
コード例 #10
0
    def post(self):
        """
        Creates a user entry if user date is valid, 
        if no sends an error message
        :return: 
        """
        user = self.request.get('user')
        fullname = self.request.get('fullname')
        password = self.request.get('password')

        params = dict()
        have_error = SignInValidator\
            .user_data_are_valid(fullname, user, password, params)

        if have_error:
            self.render('signin.html', **params)
        else:
            salt = HashUtils.gen_salt()
            hash = HashUtils.crypt(password, salt)

            u = User(user=user,
                     fullname=fullname,
                     hash=hash,
                     salt=salt,
                     created=datetime.datetime.now())
            u.put()

            time.sleep(2)

            self.response.set_cookie('user_id', u.hash)
            self.response.set_cookie('user_desc', u.user)

            self.redirect('/main')
コード例 #11
0
ファイル: main.py プロジェクト: vaultboy324/ExecBot
def check_user(message):
    user = User(message.from_user.id)

    if Registration.check_user(user):
        bot.send_message(user.get_id(), "Id привязан")
    else:
        bot.send_message(user.get_id(), "Id не привязан")
        pass
コード例 #12
0
    def setUp(self):
        self.i_o = test_io()
        self.repository = UserRepository(self.i_o)

        self.test_user1 = User("Paavo", "Pesusieni666_", 1)
        self.test_user2 = User("MacGyver", "_käpyKranaatti13", 2)

        self.repository.empty_users_table()
コード例 #13
0
    def _prepare_users(cls):
        users = []

        users.append(User("Paavo", "Pesusieni666_", 1))
        users.append(User("MacGyver", "_Käpykranaatti13", 2))
        users.append(User("Gunnar", "Surströmming<3", 3))

        return users
コード例 #14
0
    def setUp(self):
        todo_repository.delete_all()
        user_repository.delete_all()

        self.todo_a = Todo('testing a')
        self.todo_b = Todo('testing b')
        self.user_kalle = User('kalle', 'kalle123')
        self.user_matti = User('matti', 'matti123')
コード例 #15
0
ファイル: actions.py プロジェクト: vaultboy324/ExecBot
    def create_task_for_user(user: User, task_id=''):
        task = {
            Constants.telegram_id: str(user.get_id()),
            Constants.task_id: task_id,
            Constants.cdate: user.get_chosen_date(),
            Constants.role_id: user.get_role()
        }

        user.set_current_task(task)
コード例 #16
0
    def setUp(self):
        self.user_repository = UserRepository(test_database_connection())
        self.user_repository.delete_all()

        self.test_user_one = User('test_user_one', 'testpw')
        self.test_user_two = User('test_user_two', 'test')

        self.user_repository.create_user(self.test_user_one)
        self.user_repository.create_user(self.test_user_two)
コード例 #17
0
ファイル: actions.py プロジェクト: vaultboy324/ExecBot
    def write_time(user: User, task_time, err_list=[]):
        role_id = ODataRequests.get_role_id(user)
        user.set_role(role_id)

        try:
            Actions.add_node(user, ActionsEnum.A_FILL_TYPE_TIME, task_time)
        except TimeError as e:
            raise e
        except ValueError as e:
            raise e
コード例 #18
0
def login_user():
    email = request.form['email']
    password = request.form['password']

    if User.login_valid(email, password):
        User.login(email)
    else:
        session['email'] = None
    

    return render_template("profile.html", email = session['email'] )
コード例 #19
0
    def setUpClass(cls):
        cls.i_o = test_io()
        cls.meal_repository = MealRepository()
        cls.menu_repository = MenuRepository(cls.meal_repository, cls.i_o)
        cls.meal_set = test_set(cls.meal_repository)

        cls.meal_repository.empty_tables()

        cls.test_user1 = User("Paavo", "Pesusieni", 1)
        cls.test_user2 = User("Matti", "Meikäläinen", 2)

        cls.meals = cls.meal_set.create_meals(cls.test_user1)
コード例 #20
0
    def setUpClass(cls):
        cls.i_o = test_io()
        cls.repository = MealRepository(cls.i_o)
        cls.meal_set = test_set(cls.repository)

        cls.repository.empty_tables()

        cls.test_user = User("Paavo", "Pesusieni", 1)
        cls.false_user = User("Darth", "Vader", 666)

        cls.meals = cls.meal_set.create_meals(cls.test_user)
        cls.ingredients = cls.meal_set.create_ingredients()
コード例 #21
0
class UserTest(TestCase):
    def setUp(self):
        # Initialise an empty User instance
        self.user = User()

    def test_can_retrieve_name(self):
        self.assertEqual(self.user.getName(), None, 'Name should not be set')

    def test_can_set_name(self):
        self.user.setName('Matthew')
        self.assertEqual(self.user.getName(), 'Matthew',
                         'Name should have been set to "Matthew"')
コード例 #22
0
    def setUp(self):
        self.password_repository = PasswordRepository(test_database_connection())
        self.password_service = PasswordService(self.password_repository)
        self.password_repository.delete_all_passwords()

        self.user_repository = UserRepository(test_database_connection())
        self.user_service = UserService(self.user_repository)

        self.test_user_one = User("test_user_one", "test_pw1")
        self.test_user_two = User("test_user_two", "test_pw2")
        self.user_service.create_user(self.test_user_one)
        self.user_service.create_user(self.test_user_two)
コード例 #23
0
def load_entities():
    # load areas
    with open('definitions/areas.json') as json_file:
        ars = json.load(json_file)
        for a in ars:
            add_area(
                Area(a['id'], a['name'], a['coordinates'], a['sqmt'],
                     a['avg_temp'], a['price']))
    # load building types
    with open('definitions/building_types.json') as json_file:
        building_types = json.load(json_file)
    # load rack types
    with open('definitions/rack_types.json') as json_file:
        rack_types = json.load(json_file)
    # load rack switch types
    with open('definitions/rack_switch_types.json') as json_file:
        rack_switch_types = json.load(json_file)
    # load rack pdus
    with open('definitions/rack_pdu_types.json') as json_file:
        rack_pdu_types = json.load(json_file)
    # load cpu types
    with open('definitions/cpu_types.json') as json_file:
        cpu_types = json.load(json_file)
    # load memory types
    with open('definitions/memory_types.json') as json_file:
        memory_types = json.load(json_file)
    # load accelerator types
    with open('definitions/accelerator_types.json') as json_file:
        accelerator_types = json.load(json_file)
    # load psu types
    with open('definitions/psu_types.json') as json_file:
        psu_types = json.load(json_file)
    # load server cooling types
    with open('definitions/server_cooling_types.json') as json_file:
        server_cooling_types = json.load(json_file)
    # load server types
    with open('definitions/server_types.json') as json_file:
        server_types = json.load(json_file)
    # load companies
    with open('definitions/companies.json') as json_file:
        cmp = json.load(json_file)
        for c in cmp:
            add_company(Company(c['id'], c['name'], c['initial_balance']))
    # load users
    with open('definitions/users.json') as json_file:
        usrs = json.load(json_file)
        for u in usrs:
            company = find_company_by_user_id(u['id']).manager_id = u['id']
            usr = User(u['id'], u['name'], u['role'], u['username'],
                       u['password'], u['company_id'], u['is_admin'])
            usr.company = c
            add_user(usr)
コード例 #24
0
async def get_flag_from_messages(request: GetRequest) -> Verdict:
    chat_id, inv_link, message_id = request.flag_id.split(':')
    async with Api(f'http://{request.hostname}:3000') as api:
        user = User()
        try:
            await api.register(user.get_register_data())
            await api.login(user.username, user.password)
            await api.join(chat_id, inv_link)
        except InvalidResponseException as e:
            return Verdict.MUMBLE('Could not login or register',
                                  traceback.format_exc())
        except:
            return Verdict.DOWN('Could not connect to service',
                                traceback.format_exc())
        try:
            resp = await api.read_messages(chat_id)
            if 'messages' not in resp:
                return Verdict.MUMBLE('Invalid contract in message getting',
                                      '')
            messages = resp['messages']
            message = list(
                filter(lambda m: int(m['id']) == int(message_id), messages))
            if len(message) != 1:
                return Verdict.CORRUPT('Invalid messages count',
                                       f'with id: {message_id}')
            if 'text' not in message[0]:
                return Verdict.MUMBLE('Invalid contract in message getting',
                                      '')
            message_content = message[0]['text']
        except:
            return Verdict.DOWN('Invalid response from service',
                                traceback.format_exc())

        try:
            resp = await api.get_chats()
            if 'chats' not in resp:
                return Verdict.MUMBLE('Invalid contract in chats listing',
                                      'invalid data')
            chats = resp['chats']
            if not chat_in_chats(chats, chat_id):
                return Verdict.MUMBLE('Can not find chat in chats',
                                      'invalid /chats')
        except:
            return Verdict.DOWN('Invalid response from service',
                                traceback.format_exc())
        if message_content != request.flag:
            return Verdict.CORRUPT(
                'Invalid flag',
                f'{request.flag}, chat id: {chat_id}, invite link: {inv_link}')

        return Verdict.OK()
コード例 #25
0
ファイル: main.py プロジェクト: Rout222/tecprime
def addUser():
    # montar o usuário
    posted_user = UserSchema(only=('email', 'first_name', 'last_name',
                                   'avatar')).load(request.get_json())

    user = User(**posted_user.data)

    # salvar
    db.table('users').insert(user.save())

    # retornar
    novo_user = UserSchema().dump(user).data

    return jsonify(novo_user), 201
コード例 #26
0
    def execute(self, user_name, password):
        if user_name and password:
            user_entity = User(user_name=user_name, password=password)

            if not user_entity.validate_user_name():
                raise ValueError("Invalid user name")

            if not user_entity.validate_password():
                raise ValueError("Invalid password")

            # create user if data satisfies enterprise wide policy validations
            password = user_entity.get_encrypted_password()

            return self.db_repo.create(user_name=user_name, password=password)
コード例 #27
0
async def check_service(request: CheckRequest) -> Verdict:
    async with Api(f'http://{request.hostname}:3000') as api:
        first_user = User()
        second_user = User()
        try:
            resp = await api.register(first_user.get_register_data())
            if 'userId' not in resp:
                return Verdict.MUMBLE('Invalid contract in user login', '')
            first_user.user_id = resp['userId']
            resp = await api.register(second_user.get_register_data())
            if 'userId' not in resp:
                return Verdict.MUMBLE('Invalid contract in user login', '')
            second_user.user_id = resp['userId']
        except InvalidResponseException:
            return Verdict.MUMBLE('Could not register login.',
                                  traceback.format_exc())
        except:
            return Verdict.DOWN('Could not connect to service.',
                                traceback.format_exc())

        verdict = await check_user_info(api, first_user)
        if verdict:
            return verdict

        verdict = await check_chats(api, first_user, second_user)
        if verdict:
            return verdict

        verdict = await check_users_searching(api, first_user)
        if verdict:
            return verdict

    return Verdict.OK()
コード例 #28
0
def login():
    form = LoginForm()
    error = None
    if request.method == 'POST' and form.validate_on_submit():
        user = app.config['USERS_COLLECTION'].find_one(
            {"_id": form.username.data})
        if user and User.validate_login(user['password'], form.password.data):
            user_obj = User(user['_id'])
            login_user(user_obj)
            flash("Logged in successfully", category='success')

            return redirect(request.args.get("next") or url_for("play_page"))
        error = "Wrong username or password"

    return render_template('login.html', title='login', error=error, form=form)
コード例 #29
0
    def tuple_to_user(self, user):
        """Apufunktio, joka muuttaa tuple-syötteen User-olioksi

        Args:
            user: Tuple, joka sisältää halutun User-olion kentät
        Returns:
            User-olio, joka muodostetaan parametristä user
        """
        if not user:
            return None

        user_to_return = User(user[1], user[2])
        user_to_return.set_user_id(user[0])

        return user_to_return
コード例 #30
0
    def user(uno=None, email=None, password=None):
        db = UserDB.db()

        if uno:
            return User(db.get(uno))

        elif email:
            for doc in db:
                if doc['email'] == email:
                    if password:
                        if doc['password'] != authhelper.crypt(password):
                            return User()
                    return User(doc)

        return User()
コード例 #31
0
ファイル: test_user.py プロジェクト: JaakkoTulkki/api-example
def test_tojson_user_ok():
    init_data = {
        'uuid': 'xyz',
        'email': '*****@*****.**',
        'password': '******'
    }
    user = User(**init_data)

    # execute
    json_user = user.toJSONDict()

    # assert
    assert len(json_user) == 2
    assert 'email' in json_user
    assert 'uuid' in json_user
    assert json_user['email'] == init_data['email']
    assert json_user['uuid'] == init_data['uuid']
コード例 #32
0
ファイル: list_book.py プロジェクト: noc06140728/bookshare
 def get(self):
     try:
         user = basic_auth.get_current_user()
         email = self.request.get('email')
         if email:
             if user.email == email:
                 self.redirect('/list_book')
                 return
             else:
                 friend = User.get_by_key_name(email)
                 if not friend:
                     raise AppError(u'指定されたメールアドレスに該当するユーザはいません。')
                 ubooks = UsersBook.get_by_user(friend)
         else:
             friend = None
             ubooks = UsersBook.get_by_user(user)
         books = [Book.get_by_key_name(ubook.book_id) for ubook in ubooks]
         self.render_template('list_book.html', {'books': books, 'friend': friend})
     except AppError, e:
         self.render_template('list_book.html', {'error_msg': e.message})
コード例 #33
0
ファイル: basic_auth.py プロジェクト: noc06140728/bookshare
 def handler(self, *args, **kw):
     try:
         (method, encoded) = self.request.headers['AUTHORIZATION'].split()
         if method.lower() == 'basic':
             (login_id, password) = base64.b64decode(encoded).split(':')
             
             tenant_id = tenant.get_tenant_id(login_id)
             namespace_manager.set_namespace(tenant_id)
             
             user = User.get_by_key_name(login_id)
             if not user:
                 raise BasicAuthError
             if user.password == hashlib.md5(login_id + password).hexdigest():
                 globals()['get_current_user'] = lambda : user
                 return func(self, *args, **kw)
             raise BasicAuthError
     except (KeyError, BasicAuthError), e:
         self.response.set_status(401)
         self.response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % (realm or 'Default')
         self.response.write(e)
         return