Beispiel #1
0
    def wants_to_not_be_friends_with(origin_username, destiny_username):
        """Declares an intention from origin to not be friends with destiny, being that a rejection
        of a previously received friendship request or the deletion of an existing friendship.
        Returns a FriendshipState which can be request_received or friends depending on the previous
        state."""
        Logger(__name__).info(
            'Username {} wants to NOT be friends with {}.'.format(
                origin_username, destiny_username))
        # retrieve the DB user representations
        origin_user = User._get_one({'username': origin_username})
        destiny_user = User._get_one({'username': destiny_username})

        # if one of them was not found raise exception
        if origin_user is None or destiny_user is None:
            raise UserNotFoundException

        # if origin doesnt know destiny or origin was the one requesting raise exception
        if destiny_username not in origin_user['friends'] or \
                origin_user['friends'][destiny_username] == FRIENDSHIP_STATE_SENT:
            raise NotFriendsException

        # if here they were already friends or destiny had sent request to origin, so delete
        assert Friendship._are_friends(origin_username, destiny_username) or \
            Friendship._had_sent_request(destiny_username, origin_username)

        return Friendship._reject_friendship(origin_username, destiny_username)
Beispiel #2
0
def login():
    req_data = request.get_json()

    msg = ""

    if not req_data['username'] or not req_data['password']:
        msg = {"status": {"type": "failure", "message": "somethings is wrong"}}
        return jsonify(msg), 200

    user = User(req_data['username'], req_data['password'], None, None, None)

    if user.check_username():
        if user.check_password(req_data['password']):
            token_data = {'username': user.username, 'admin': user.admin}

            token = jwt.encode(token_data, app.config['SECRET_KEY'])

            return jsonify({
                'token': token.decode('UTF-8'),
                "username": user.username,
                "status": {
                    "type": "success"
                }
            }), 200
        else:
            msg = {"status": {"type": "failure", "message": "wrong password"}}
            return jsonify(msg), 200
    else:
        msg = {"status": {"type": "failure", "message": "user not found"}}
        return jsonify(msg), 200
Beispiel #3
0
    def test_initialization(self):
        email = '*****@*****.**'
        name = 'some name'
        user = User(email, name)

        self.assertEqual(user.get_name(), name)
        self.assertEqual(user.get_email(), email)
def create() -> Tuple[str, int]:
    """
    create user
    :return:
    """
    data = request.json
    id = data.get("id")
    email = data.get("email")

    user = User.query.filter_by(id=id).first()

    if not user:
        try:
            user = User(id, email)
            user.save()
            response = jsonify(message="User created")
            response.headers["location"] = f"user/{user.id}"
            return response, 201

        except Exception as e:
            response = jsonify(message=str(e))
            return response, 401

    else:
        response = jsonify(message="This user already exists.")
        return response, 422
Beispiel #5
0
    def wants_to_be_friends_with(origin_username, destiny_username):
        """Declares an intention from origin to be friends with destiny, sending a request to
        destiny or confirming the relation if the inverse had been previously stated.
        Returns a FriendshipState which can be request_sent or friends depending on the previous."""
        Logger(__name__).info(
            'Username {} wants to be friends with {}.'.format(
                origin_username, destiny_username))
        # retrieve the DB user representations
        origin_user = User._get_one({'username': origin_username})
        destiny_user = User._get_one({'username': destiny_username})

        # if one of them was not found raise exception
        if origin_user is None or destiny_user is None:
            raise UserNotFoundException

        # if destiny had NOT already wanted to be friends with origin
        if origin_username not in destiny_user['friends']:
            return Friendship._send_request_from_to(origin_username,
                                                    destiny_username)

        # if destiny is already friends with origin
        if Friendship._are_friends(origin_username, destiny_username):
            raise AlreadyFriendsException

        # only other cases are: invitation already sent or needed confirmation
        # and this first case should not be possible
        assert _user(destiny_username
                     )['friends'][origin_username] == FRIENDSHIP_STATE_SENT
        assert _user(origin_username)['friends'][
            destiny_username] == FRIENDSHIP_STATE_RECEIVED

        # so now it should be confirmed
        return Friendship._confirm_friends(origin_username, destiny_username)
Beispiel #6
0
    def test_validate_confirm_password(self):
        password = "******"
        confirm_password = '******'
        self.assertEqual("password and confirm password arent the same",
                         User.validate_confirm_password(password, confirm_password)[0])

        confirm_password = '******'
        self.assertTrue(User.validate_confirm_password(password, confirm_password) == [])
Beispiel #7
0
    def test_validate_email(self):
        email = "0001"
        self.assertEqual("email format error", User.validate_email(email)[0])

        email = "0222.com.tw"
        self.assertEqual("email format error", User.validate_email(email)[0])

        email = '*****@*****.**'
        self.assertTrue(User.validate_email(email) == [])
Beispiel #8
0
    def test_get_profile_preview_not_found(self):
        with patch.object(Persistence, "get_one") as mocked_user_get, \
             self.assertRaises(UserNotFoundException) as context:
            mocked_user_get.side_effect = MagicMock(return_value=None)

            User.get_profile_preview("pepe")

        exc = context.exception
        self.assertEqual(exc.error_code, 404)
class UserService(object):
    def __init__(self, user_id, table_name):
        self.__table = DynamoDBRepository(table_name)
        self.__user = User(self.__table.get_by_id({"userID": user_id}))
        self.__set_service = SetService(self.__user.get_user_sets())

    def __str__(self):
        return str(self.__user)

    def __have_set(self, object):
        return self.get_set_by_element(object)

    def __update_sets(self):
        self.__set_service = SetService(self.__user.get_user_sets())

    def __save(self):
        self.__update_sets()
        self.__table.update(str(self))

    def get_set_by_element(self, set_item):
        return self.__set_service.get_set_by_element(set_item)

    def get_set_by_reference(self, set_id):
        return self.__set_service.get_set_by_reference(set_id)

    def get_user_sets(self):
        return json.dumps(self.__user.get_user_sets())

    def add_user_set(self, object):
        incoming_set = self.__have_set(object)

        if incoming_set:
            return None
        else:
            self.__user.add_user_set(object)
            self.__save()
            return object

    def update_user_set(self, object, set_id):
        incoming_set = self.__have_set(object)

        if incoming_set:

            if json.loads(incoming_set)["setReference"] == set_id:
                self.__user.update_user_set(object)
                self.__save()
                return object

        return None

    def delete_user_set(self, set_id):
        incoming_set = self.get_set_by_reference(set_id)

        if incoming_set:
            self.__user.delete_user_set(incoming_set)
            self.__save()
            return incoming_set

        return None
Beispiel #10
0
def create_indexes():
    Logger(__name__).debug('Creating indexes for DB')

    # indexes for User
    User._get_coll().create_index("username")

    # indexes for Story
    Story._get_coll().create_index("username")

    # indexes for Comments
    StoryComment._get_coll().create_index("story_id")
def return_new_users_correctly():
    new_users_correct = [User(name='Edoardo', surname='Casiraghi', birth_date='25/04/1993', birth_place='Merate',
                              instruction_level='University'),
                         User(name='Veronica', surname='Lanzi', birth_date='01/05/1994', birth_place='Lecco',
                              instruction_level='University'),
                         User(name='Danilo', surname='Casiraghi', birth_date='11/10/1961', birth_place='Vimercate',
                              instruction_level='High School'),
                         User(name='Daniela', surname='Bonalume', birth_date='18/02/1963', birth_place='Merate',
                              instruction_level='Middle School')]

    return new_users_correct
Beispiel #12
0
    def test_save_new_user_not_found(self):
        with patch.object(Persistence, "get_one") as mocked_user_get, \
             patch.object(Story, "save_new") as mocked_story_save, \
             self.assertRaises(UserNotFoundException):
            mocked_story_save.side_effect = self.mocked_story_insert_one
            mocked_user_get.side_effect = MagicMock(return_value=None)

            story_data = dict(story_data_mock_with_title_and_description)
            story_data['username'] = "******"

            User.save_new_story(story_data)
Beispiel #13
0
def test_compute_age_from_birth_date(input_birth_date, expected_age):
    user = User(name='Edoardo', surname='Casiraghi', birth_date=input_birth_date,
                birth_place='Merate', instruction_level='University')

    if isinstance(expected_age, int):
        # Compute the age given the birth date of a user
        computed_age = user.compute_age_from_birth_date(birth_date=input_birth_date)
        assert( computed_age == expected_age )
    elif isinstance(expected_age, Exception):
        with pytest.raises(ValueError):
            # Compute the age given the birth date of a user
            user.compute_age_from_birth_date(birth_date=input_birth_date)
Beispiel #14
0
def test_convert_date_to_standard_format(input_birth_date, expected_birth_date):
    user = User(name='Edoardo', surname='Casiraghi', birth_date='25/04/1993',
                birth_place='Merate', instruction_level='University')

    if isinstance(expected_birth_date, str):
        # Compute the age given the birth date of a user
        computed_birth_date = user.convert_date_to_standard_format(birth_date=input_birth_date)
        assert(computed_birth_date == expected_birth_date)
    else:
        with pytest.raises(ValueError):
            # Compute the age given the birth date of a user
            _ = user.convert_date_to_standard_format(birth_date=input_birth_date)
Beispiel #15
0
def test_step1_empty_checkbox():
    with allure.step('Переход на страницу регистрации'):
        Header().open_register_page().title_text.should(have.exact_text('Регистрация'))
    with allure.step('Ввод корректного незарегистрированного номера 1й чекбокс не отмечен'):
        RegisterPage().register_step1(
            User(phone='9201239746', approve1=0, approve2=1), browser.driver())
    with allure.step('Проверка отсутствия перехода на второй шаг'):
        RegisterPage().code_input.should_not(be.visible)
    with allure.step("Ввод корректного незарегистрированного номера 2й чекбокс не отмечен"):
        RegisterPage().register_step1(
            User(phone='9201239746', approve1=0, approve2=1), browser.driver())
    with allure.step('Проверка отсутствия перехода на второй шаг'):
        RegisterPage().code_input.should_not(be.visible)
Beispiel #16
0
    def test_validate_username(self):
        username = '******'
        self.assertEqual("length of username needs to bigger than 6", User.validate_username(username)[0])

        username = '******'
        self.assertEqual("username cant use symbol", User.validate_username(username)[0])

        username = "******"
        res = User.validate_username(username)
        self.assertTrue("username cant use symbol" in res)
        self.assertTrue('length of username needs to bigger than 6' in res)
        #
        username = '******'
        self.assertTrue(User.validate_username(username) == [])
Beispiel #17
0
    def handle_add(self, username: str):
        """
        Handle adding of the user record.

        :param username:
        :return:
        """
        user = db.session.query(User).filter(
            User.username == username).one_or_none()

        if isinstance(user, User):
            return user

        response, userdata = BggApi().get_json('user?name=' + username)

        if not userdata['user']['@id']:
            return {"status": 404}

        user = User(username=userdata['user']['@name'],
                    bgg_id=userdata['user']['@id'])

        user_exists = db.session.query(User).filter(
            User.username == user.username).one_or_none()

        if user_exists:
            return user

        db.session.add(user)
        db.session.commit()

        return user
Beispiel #18
0
 def test_step3_differents_passwords(self):
     with allure.step('Переход на страницу регистрации'):
         Header().open_register_page().title_text.should(
             have.exact_text('Регистрация'))
     with allure.step(
             'Корректно заполненные поля с разными данными в полях с паролем'
     ):
         RegisterPage().register_step3(
             User(approve1=1,
                  approve2=1,
                  sms='1111',
                  email="*****@*****.**",
                  fio="test",
                  data_day="4",
                  data_month="10",
                  data_year="1993",
                  sex="male",
                  password="******",
                  confirm_password="******",
                  rand=True), browser.driver())
     with allure.step("Проверка вализации поля Повторите пароль"):
         RegisterPage().confirm_password_error.should(
             have.exact_text(
                 'Новый пароль и подтверждение пароля должны совпадать'))
     with allure.step(
             "Проверка отсутствие перехода на сраницу зарегистрированного пользователя"
     ):
         RegisterPage().title_text.should_not(
             have.exact_text('Добро пожаловать!'))
Beispiel #19
0
 def put(self, username):
     """
         Update existed user
     """
     data = request.json
     user = User.update_user(username, data)
     return user
Beispiel #20
0
    def get(self, username):
        try:
            # get token from header
            token = self._get_token_from_header()

            # identify with token
            callee_user = Token.identify(token)

            # get profile info from user username
            profile = User.get_profile(username, callee_user)

            # generate response
            self.logger.info('User profile found for: {}'.format(username))
            output = profile

            # return response
            return ResponseBuilder.build_response(output)

        except UserNotFoundException as e:
            err_msg = "No user found with that name"
            self.logger.info(err_msg)
            return ResponseBuilder.build_error_response(err_msg, e.error_code)
        except (ExpiredTokenException, MissingFieldException,
                InvalidTokenException) as e:
            return ResponseBuilder.build_error_response(
                e.message, e.error_code)
Beispiel #21
0
 def test_step3_empty_fieldes(self):
     with allure.step('Переход на страницу регистрации'):
         Header().open_register_page().title_text.should(
             have.exact_text('Регистрация'))
     with allure.step('Ввод корректного номера'):
         RegisterPage().register_step3(
             User(phone='9231239747', approve1=1, approve2=1, sms='1111'),
             browser.driver())
     with allure.step("Проверка валидации поля ИМЯ"):
         RegisterPage().name_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля E-mail"):
         RegisterPage().email_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Придумайте пароль"):
         RegisterPage().password_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Повторите пароль"):
         RegisterPage().confirm_password_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля День"):
         RegisterPage().data_day_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Месяц"):
         RegisterPage().data_month_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Год"):
         RegisterPage().data_year_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Пол"):
         RegisterPage().sex_error.should(
             have.exact_text('Обязательное поле'))
Beispiel #22
0
    def test_step3_uncorrect_email(self):
        with allure.step('Переход на страницу регистрации'):
            Header().open_register_page().title_text.should(
                have.exact_text('Регистрация'))
        with allure.step('Корректно заполненные поля и невалидная почты'):
            RegisterPage().register_step3(
                User(phone='9241239742',
                     approve1=1,
                     approve2=1,
                     sms='1111',
                     email="alpikin",
                     fio="test",
                     data_day="4",
                     data_month="10",
                     data_year="1993",
                     sex="male",
                     password="******",
                     confirm_password="******"), browser.driver())
        with allure.step('Проверка валидации поля e-mail'):
            RegisterPage().email_error.should(
                have.exact_text('Введите корректный email'))

        with allure.step(
                "Проверка отсутствие перехода на сраницу зарегистрированного пользователя"
        ):
            RegisterPage().title_text.should_not(
                have.exact_text('Добро пожаловать!'))
        RegisterPage().check_email('a`lpikin@')
        RegisterPage().check_email('@alpikin')
        RegisterPage().check_email('asd@alpikin')
        RegisterPage().check_email('lpikin.ru')
        RegisterPage().check_email('@lpikin.ru')
        RegisterPage().check_email('asd@lpikin.')
Beispiel #23
0
def post():
    body = request.json
    required_parameters = [
        'first_name', 'last_name', 'email', 'username', 'password'
    ]
    if not all(x in body for x in required_parameters):
        return response.build(
            error=True,
            error_message='All request body parameters are required.')

    user = db_session().query(User).filter_by(
        username=body['username']).first()
    if user:
        return response.build(error=True,
                              error_message='The user already exists.')

    user = User(username=body['username'],
                first_name=body['first_name'],
                last_name=body['last_name'],
                email=body['email'],
                password=body['password'])
    db_session().add(user)
    db_session().commit()

    return response.build(error=False, response=user.username)
Beispiel #24
0
    def __init__(self):
        global code
        code = 1

        try:

            while code == 1:
                print('\nNew user registration\n')

                name = str(input('Name: '))
                last_name = str(input('Last name: '))

                print('1: admin')
                print('2: common')
                option = str(input('Type of account[admin or common user: '******'1':
                    tp = 'admin'
                else:
                    tp = 'common'

                login = str(input('Login: '******'Password: '******'Email: '))

                new_user = User(name, last_name, tp, email, login, password)

                query = ("INSERT INTO USER (LOGADO, TYPE, LOGIN, PASSWORD, NAME, LASTNAME, EMAIL) VALUES(0, '%s', '%s',"
                         "'%s', '%s', '%s','%s')" % (str(new_user.tp), str(new_user.login), str(new_user.password),
                                                     str(new_user.name), str(new_user.last_name), str(new_user.email)))

                con.insert_data(query)
                code = 0

        except KeyboardInterrupt:
            code = 0
Beispiel #25
0
def login_verify(bot, update):
    user = update.message.from_user
    chatid = update.message.chat.id
    userinput = html.escape(update.message.text.strip())
    logger.info(userinput)

    USERTOKEN = userinput
    
    if User.login(USERTOKEN): #TEST IF USERTOKEN IS IN DATABASE HERE
        # INFO_STORE[user.id]['user_token'] = USERTOKEN # only record usertoken if success login match
        INFO_STORE['user_token'] = USERTOKEN   ## only record usertoken if success login match
        button_list = [InlineKeyboardButton(text='Go to Dashboard', callback_data = 'login_success')]
        replytext = "<b>Great! You have successfully logged in.</b>"

    else: 
        button_list = [InlineKeyboardButton(text='FILL UP AGAIN', callback_data = 'login_fail')]
        replytext = "<b>ERROR. Your User Token is not found. Please try again or register first.</b>"

    menu = build_menu(button_list, n_cols = 1, header_buttons = None, footer_buttons = None)
    
    # deletes message sent previously by bot
    bot.delete_message(chat_id=chatid, message_id=INFO_STORE[user.id]["BotMessageID"][-1])

    msgsent = bot.send_message(text = replytext,
                                chat_id = chatid,
                                reply_markup = InlineKeyboardMarkup(menu),
                                parse_mode=ParseMode.HTML)
    
    #appends message sent by bot itself - the very first message: start message
    INFO_STORE[user.id]["BotMessageID"].append(msgsent['message_id'])

    return VERIFY_LOGIN  
Beispiel #26
0
    def get_feed_for_username(username):
        Logger(__name__).info('Getting feed for user {}.'.format(username))

        # get all stories by iterating over usernames, use username to filter private, non-friend ones
        stories_feed_data = User.get_feed_data(username)

        Logger(__name__).info(
            'Prioritizing {} stories for user {}\'s feed.'.format(
                len(stories_feed_data), username))

        # calculate priorities
        for story_feed_data in stories_feed_data:
            set_score(story_feed_data, INITIAL_SCORE)

            run_all(rule_list=rules,
                    stop_on_first_trigger=False,
                    defined_actions=StoryActions(story_feed_data),
                    defined_variables=StoryVariables(story_feed_data))

        prioritized_stories = [
            story_feed_data['story_id']
            for story_feed_data in sorted(stories_feed_data,
                                          key=lambda sfd: get_score(sfd),
                                          reverse=True)
        ]

        Logger(__name__).info('Serving feed for user {}.'.format(username))
        # get stories in according order, add feed-specific fields of user's name and profile pic
        return [
            FeedBuilder._format_feed_story(story_id)
            for story_id in prioritized_stories
        ]
Beispiel #27
0
    def _format_feed_flash(srz_flash):
        uploader = srz_flash['username']
        profile_preview = User.get_profile_preview(uploader)

        srz_flash['name'] = profile_preview['name']
        srz_flash['profile_pic'] = profile_preview['profile_pic']
        return srz_flash
Beispiel #28
0
 def delete(self, user_id):
     """
         Update existed user
     """
     user = User.get(user_id, error_out=True)
     user.delete()
     return wrap_response(None, 'ok', 200)
Beispiel #29
0
 def post(self):
     """
         Create new user
     """
     data = request.json
     # user: User = flask_login.current_user
     return User.create(data)
Beispiel #30
0
 def setUp(self):
     """
     test fixture, preparation needed for test cases.
     setUp will be executed before each test case
     """
     print("setUp")
     self.user = User("Tim", "Berners - Lee", "www", "333333")
     print(self.user)
Beispiel #31
0
 def put(self, user_id):
     """
         Update existed user
     """
     data = request.json
     user = User.get(user_id, error_out=True)
     user.update(data)
     return user
Beispiel #32
0
class UserTest(unittest.TestCase):
    """
    @author: s52748
    @contact: [email protected]
    @version: 13.06.2016
    @summary: Test case for class User, using PyUnit test framework.
              Every new test case has the base class TestCase.
              A test case is an individual unit of testing.
              A test suite is a collection of test cases, test
              suites, or both.
    @see: https://docs.python.org/3/library/unittest.html#module-unittest
    """
    def setUp(self):
        """
        test fixture, preparation needed for test cases.
        setUp will be executed before each test case
        """
        print("setUp")
        self.user = User("Tim", "Berners - Lee", "www", "333333")
        print(self.user)

    def tearDown(self):
        """
        clean-up steps, after each test case
        """
        print("tearDown")
        del self.user
        self.assertRaises(AttributeError, lambda: print(self.user))

    def test_information_hiding(self):
        """
        test method, testing properties, get_md5 method and string
        representation of User instance
        """
        self.assertIsInstance(self.user, User)
        self.assertIsNotNone(self.user)
        self.assertRaises(AttributeError, lambda: self.user.__first_name)
        self.assertRaises(AttributeError, lambda: self.user.__last_name)
        self.assertRaises(AttributeError, lambda: self.user.__nickname)
        self.assertRaises(AttributeError, lambda: self.user.__password)
        self.assertIs(self.user.user_id_property, None)
        self.assertIsNone(self.user.user_id_property)
        self.assertEqual(self.user.first_name_property, "Tim")
        self.assertEqual(self.user.last_name_property, "Berners - Lee")
        self.assertEqual(self.user.nickname_property, "www")
        self.assertEqual(self.user.password_property, "333333")
        self.assertEqual(md5(bytes(self.user.password_property, "utf-8")).hexdigest(),
                         self.user.get_md5())
        self.assertEqual(str(self.user), "None Tim Berners - Lee www 333333")