Ejemplo n.º 1
0
def patch_session(_id):
    user = User(request.form['user'])
    if request.args['update'] == 'add-user':
        try:
            Session(_id).add_user(User(request.form['user']),
                                  request.form['password'])
        except PermissionError as e:
            return e.args[0], 403
        except ValueError as e:
            return e.args[0], 400
        return Messages.USER_ADDED_SUCCESS.value, 200
    elif request.args['update'] == 'set-score':
        score = int(request.form['score'])
        try:
            Session(_id).set_users_score(user, score)
            user.add_total_score(score)
        except ValueError as e:
            return e.args[0], 400
        return Messages.SCORE_SET_SUCCESS.value, 200
    elif request.args['update'] == 'close':
        try:
            Session(_id).close_api(user)
        except PermissionError as e:
            return e.args[0], 403
        except ValueError as e:
            return e.args[0], 400
        return 'session successfully closed', 200
    else:
        return Errors.NO_VALID_UPDATE_PARAM.value, 400
Ejemplo n.º 2
0
    def open(self):
        print("SERVER: On new connection!")
        newUser = User()
        newUser.socket = self
        UserList.append(newUser)

        self.askForName()
Ejemplo n.º 3
0
Archivo: ATM.py Proyecto: cuixd/ATMBank
    def addUser(self, username, password, isAdmin):
        if isAdmin == 1:
            u = User(username, password, None, 1, 1)
        else:
            u = User(username, None,
                     Card(abs(username.__hash__()), password, 0, 1), 0, 1)

        self.userdict[username] = u
Ejemplo n.º 4
0
def get(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps(User(event).get(), cls=DecimalEncoder)
    }

    return response
Ejemplo n.º 5
0
def get(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps(
            User(event).get()['watchlist'],
            cls=DecimalEncoder)
    }
Ejemplo n.º 6
0
 def setUpClass(cls):
     cls.userList = UserList()
     cls.setUpUser = User()
     cls.setUpUser.name = "June"
     cls.setUpUser.socket = "fake websocket"
     cls.setUpUser.setUUID(str(uuid.uuid4()))
     cls.userList.append(cls.setUpUser)
Ejemplo n.º 7
0
Archivo: ATM.py Proyecto: cuixd/ATMBank
    def __init__(self, bankname, userdict):

        self.bankname = bankname
        self.userdict = userdict  # type:dict
        if len(userdict) == 0:
            admin = User("admin", "admin", None, 1, 1)
            self.userdict["admin"] = admin
Ejemplo n.º 8
0
def getAll(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps(
            User(event).investments,
            cls=DecimalEncoder
        )
    }
Ejemplo n.º 9
0
def check_user_token(user, token):
    try:
        User(user, token=token).check_user_token()
    except PermissionError as e:
        return e.args[0], 401
    except ValueError as e:
        return e.args[0], 400
    return msg.USER_TOKEN_CORRECT.value, 200
Ejemplo n.º 10
0
 def test_write_many_receivers(self):
     self.subject = self.add_random_number('Subject_write_many_receivers ')
     TEXT = 'Text_write_many_receivers'
     receivers = [
         User(self.login, self.password),
         User(self.login2, self.password2),
     ]
     receivers_emails = [receiver.login for receiver in receivers]
     letter_manager = self.main_page.letter_manager
     letter_manager.write_letter_many_receivers(receivers_emails,
                                                self.subject, TEXT)
     for receiver in receivers:
         self.main_page.relogin(receiver.login, receiver.password)
         letter_manager.letter_selector.find_letter_subject_real(
             self.subject)
         # For the last receiver we use tearDown
         if receiver != receivers[-1]:
             self.main_page.letter_manager.remove_letter(self.subject)
Ejemplo n.º 11
0
 def save(self, user: UserInput):
     try:
         db_item = User(**user.dict())
         self.db.add(db_item)
         self.db.commit()
         self.db.refresh(db_item)
         return {"data": db_item}
     except Exception as error:
         print(error)
         return { "error": error }
Ejemplo n.º 12
0
def patch_login_user(user):
    try:
        User(user,
             password=request.form['password'],
             token=request.form['token']).login()
    except PermissionError as e:
        return e.args[0], 401
    except ValueError as e:
        return e.args[0], 400
    return msg.USER_LOGIN_SUCCESS.value, 200
Ejemplo n.º 13
0
def post_user(user):
    try:
        User(user, password=request.form['password'], token=request.form['token'],
             display_name=request.form['display_name'])\
            .register()
    except ValueError as e:
        return e.args[0], 400
    except errors.DuplicateKeyError as e:
        return e.args[0], 400
    return msg.USER_REGISTERED_SUCCESS.value, 200
Ejemplo n.º 14
0
 def close_api(self, user: User):
     if not user.exists():
         raise ValueError(err.NOT_EXISTING_USER.value)
     is_admin = session_coll.find_one({primary_key: ObjectId(self.id)}, {
         primary_key: 0,
         'admin': 1
     })['admin']
     if not is_admin:
         raise PermissionError(err.PERMISSION_DENIED.value)
     self.close()
     return user
Ejemplo n.º 15
0
    def test_receive_new_letter_from_another_account(self):
        self.subject = self.add_random_number(
            'Subj_receive_from_another_account ')
        TEXT = 'Txt_receive_from_another_account'

        receiver = User(self.login2, self.password2)
        letter_manager = self.main_page.letter_manager
        letter_manager.write_letter(receiver.login, self.subject, TEXT)
        self.main_page.relogin(receiver.login, receiver.password)

        letter_manager.letter_selector.find_letter_subject_real(self.subject)
Ejemplo n.º 16
0
def read_all_users():
    result = []
    if os.stat(USERS_FILE).st_size > 0:
        events = open(USERS_FILE, 'r')
        json_loads = json.load(events)
        for json_load in json_loads:
            event = User(None, None)
            event.__dict__.update(json_load)
            result.append(event)
        events.close()
    return result
Ejemplo n.º 17
0
 def create_user(self, name):
     """
         Method that create a new user.
         
         Parameters:
         
         name : string
             The name of the user.
     """
     self._countUsers += 1
     self.users.append(
         User(name, "guiagent" + str(self._countUsers) + "@616.pub"))
Ejemplo n.º 18
0
def put(event, context):
    post = json.loads(event['body'])
    user = User(event)

    if "investment" in event['pathParameters']:
        investment_name = unquote(event['pathParameters']['investment'])
    else:
        raise Exception("investment name not valid")

    if "transactions" in post:
        transactions = post["transactions"]
    else:
        raise Exception("transactions object required in post")

    user.setTransactions(investment_name, transactions)
    user.save()

    return {
        "statusCode":
        200,
        "body":
        json.dumps({
            "success": True,
            "transactions": transactions
        },
                   cls=DecimalEncoder)
    }
Ejemplo n.º 19
0
 def set_users_score(self, user: User, score: int):
     if user.get() is None:
         raise ValueError(err.USER_NOT_FOUND.value)
     return session_coll.update_one(
         {
             '$and': [{
                 primary_key: ObjectId(self.id)
             }, {
                 'users.user': user.id
             }]
         }, {'$set': {
             'users.$.score': score
         }})
Ejemplo n.º 20
0
def patch_user(user):
    if request.args['update'] == 'password':
        try:
            User(user).update_password_api(request.form['new_password'],
                                           request.form['old_password'])
        except ValueError as e:
            return e.args[0], 400
        return msg.PW_CHANGED_SUCCESS.value, 200
    elif request.args['update'] == 'display_name':
        try:
            User(user, display_name=request.form['display_name']
                 ).update_display_name()
        except ValueError as e:
            return e.args[0], 400
        return msg.DISPLAY_NAME_CHANGED_SUCCESS.value, 200
    elif request.args['update'] == 'total_score':
        try:
            User(user).add_total_score(int(request.form['score']))
        except ValueError as e:
            return e.args[0], 400
        return msg.SCORE_ADDED_SUCCESS.value, 200
    else:
        return err.NO_VALID_UPDATE_PARAM.value, 400
Ejemplo n.º 21
0
    def test_reply_letter(self):
        self.subject = self.add_random_number('Subject_reply_letter ')
        TEXT = 'Text_reply_letter'
        replied_text = self.add_random_number('Replied text ')

        first_user = User(self.login, self.password)
        receiver = User(self.login2, self.password2)
        letter_manager = self.main_page.letter_manager

        letter_manager.write_letter(receiver.login, self.subject, TEXT)

        self.main_page.relogin(receiver.login, receiver.password)
        letter_manager.reply_letter(self.subject, replied_text)

        self.main_page.relogin(first_user.login, first_user.password)
        letter_manager.letter_selector.open_letter(self.subject)
        actual_replied_text = self.main_page.letter_manager.letter_selector.get_replied_letter_text(
        )
        self.assertEqual(replied_text, actual_replied_text)

        self.main_page.navigation_manager.go_to_inbox()
        self.main_page.letter_manager.remove_letter(self.subject)

        self.main_page.relogin(receiver.login, receiver.password)
Ejemplo n.º 22
0
 def add_user(self, user: User, password: str = ''):
     if not user.exists():
         raise ValueError(err.USER_NOT_FOUND.value)
     self.get_information_to_add_user()
     if self.closed:
         raise ValueError(err.SESSION_ALREADY_CLOSED.value)
     if self.private and self.password != hash_password(password):
         raise PermissionError(err.PW_MISMATCH.value)
     return session_coll.update_one(
         {primary_key: ObjectId(self.id)},
         {'$push': {
             'users': {
                 'user': user.id,
                 'score': 0
             }
         }})
Ejemplo n.º 23
0
    def testAddUser(cls):
        testUser = User()
        testUser.name = "tester1"
        testUser.socket = "fake websocket 1"
        testUser.setUUID(str(uuid.uuid4()))
        cls.userList.append(testUser)
        assert (cls.userList.getSize() == 2)

        # test delete user
        cls.userList.deleteUserByUUID(testUser.uuid)

        assert (cls.userList.getSize() == 1)
Ejemplo n.º 24
0
def get(event, context):

    user = User(event).get()

    if "investment" in event['pathParameters']:
        investment_name = event['pathParameters']['investment']
    else:
        raise Exception("investment name not valid")

    if investment_name in user['investments']:
        transactions = user['investments'][investment_name]['transactions']
    else:
        raise Exception("investment not found")

    return {
        "statusCode": 200,
        "body": json.dumps(transactions, cls=DecimalEncoder)
    }
Ejemplo n.º 25
0
def get(event, context):

    user = User(event).get()
    investment = event['pathParameters']['investment']

    if "investments" in user and investment in user['investments']:
        response = {
            "statusCode": 200,
            "body": json.dumps(
                user['investments'][investment],
                cls=DecimalEncoder
            )
        }
    else:
        raise Exception("investment: {} not found".format(investment))


    return response
Ejemplo n.º 26
0
 def __init__(self):
     super(WallEEGApp, self).__init__()
     self.user = User()
     self.graph = Graph(xlabel='X',
                        ylabel='Y',
                        x_ticks_minor=5,
                        x_ticks_major=25,
                        y_ticks_major=0.001,
                        y_grid_label=True,
                        x_grid_label=True,
                        padding=5,
                        x_grid=True,
                        y_grid=True,
                        xmin=-0,
                        xmax=100,
                        ymin=-0.1,
                        ymax=0.1)
     self.plot = MeshLinePlot(color=[1, 0, 0, 1])
     self.counter = 0
Ejemplo n.º 27
0
def process(message):
    if message.text == '/start':
        markup = types.InlineKeyboardMarkup()
        markup.add(
            types.InlineKeyboardButton(text=subscribe,
                                       url='ya.ru',
                                       callback_data="1"))
        bot.send_message(message.chat.id,
                         'Выберите действие',
                         reply_markup=markup)
    elif message.text == subscribe:
        markup = types.ReplyKeyboardMarkup()
        markup.row(*genres)
        bot.send_message(message.chat.id,
                         'Выберите стиль',
                         reply_markup=markup)
    elif genres.__contains__(message.text):
        save_user(User(message.from_user.id, [message.text]))
        bot.send_message(message.chat.id,
                         'Вы подписаны на ' + message.text,
                         reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 28
0
def upsert(event, context):
    post = json.loads(event['body'])

    if "investment" in event['pathParameters']:
        current_name = unquote(event['pathParameters']['investment'])
    else:
        raise Exception("investment name not valid")

    if "investment" in post:
        investment = post["investment"]
        if "name" not in investment:
            investment["name"] = current_name
    else:
        raise Exception("investment object required in post")

    user = User(event)
    if investment["name"] != current_name:
        if investment["name"] not in user.investments:
            user.deleteInvestment(current_name)
        else:
            raise Exception(
                "error: cannot rename investment, '{}' already exists".format(
                    investment["name"]))

    user.setInvestment(investment)
    user.save()

    return {
        "statusCode":
        200,
        "body":
        json.dumps({
            "success": True,
            "investments": user.investments
        },
                   cls=DecimalEncoder)
    }
Ejemplo n.º 29
0
def upsert(event, context):
    post = json.loads(event['body'])
    if "user" not in post:
        raise Exception('user object required in post')

    user = User(event)

    for (key, val) in post['user'].items():
        user.setItem(key, val)

    user.save()

    return {
        "statusCode":
        200,
        "body":
        json.dumps({
            "success": True,
            "user": user.get()
        }, cls=DecimalEncoder)
    }
Ejemplo n.º 30
0
def delete(event, context):

    if "symbol" in event['pathParameters']:
        symbol = unquote(event['pathParameters']['symbol'])
    else:
        raise Exception("symbol name not valid")

    user = User(event)
    user.deleteFromWatchlist(symbol)
    user.save()

    return {
        "statusCode":
        200,
        "body":
        json.dumps({
            "success": True,
            "watchlist": user.watchlist
        },
                   cls=DecimalEncoder)
    }