Beispiel #1
0
def handle_login_message(conn, data):
    """
	Gets socket and message data of login message. Checks  user and pass exists and match.
	If not - sends error and finished. If all ok, sends OK message and adds user and address to logged_users
	Receives: socket, message code and data
	Returns: None (sends answer to client)
	"""
    global users  # This is needed to access the same users dictionary from all functions
    global logged_users
    user_data = chatlib.split_data(
        data,
        2)  # Splitting the data field. For login message, there are two fields
    # [username, password]
    if user_data[0] in users.keys():  # check if the username exists
        if user_data[1] == users[
                user_data[0]]["password"]:  # check given password
            build_and_send_message(conn,
                                   chatlib.PROTOCOL_SERVER["login_ok_msg"], "")
            logged_users[conn.getpeername()] = user_data[0]
            print_debug(user_data)
            print_debug(logged_users)
        else:
            build_and_send_message(conn,
                                   chatlib.PROTOCOL_SERVER["login_failed_msg"],
                                   "Error! Wrong Password")

    else:
        build_and_send_message(conn,
                               chatlib.PROTOCOL_SERVER["login_failed_msg"],
                               "Error! User does not exists")
Beispiel #2
0
def handle_login_message(conn, data):
    """
    Gets socket and message data of login message. Checks  user and pass exists and match.
    If not - sends error and finished. If all ok, sends OK message and adds user and address to logged_users
    Receives: socket, message code and data
    Returns: None (sends answer to client)
    """
    fail_message = False

    try:
        user, password = chatlib.split_data(data)
    except ValueError:
        send_error(conn, 'Data field incorrect')
    else:
        for key in users:
            if key == user:
                fail_message = True
                if password == users[user]['password']:
                    build_and_send_message(
                        conn, chatlib.PROTOCOL_SERVER['login_ok_msg'], '')
                    logged_users[conn] = user
                    break
                else:
                    build_and_send_message(
                        conn, chatlib.PROTOCOL_SERVER['login_failed_msg'],
                        'Password does not match!')

        if not fail_message:
            build_and_send_message(conn,
                                   chatlib.PROTOCOL_SERVER['login_failed_msg'],
                                   'Username does not exist')
def handle_login_message(conn, data):
    global users, logged_users
    user_info = chatlib.split_data(data, 2)
    if user_info is None:
        build_and_send_message(
            conn, chatlib.PROTOCOL_SERVER["error_msg"],
            "Username and/or password cannot contain the # character")
    else:
        username = user_info[0]
        if username in users:
            password = user_info[1]
            right_password = (users.get(username)).get("password")
            if password == right_password:
                if username not in logged_users.values():
                    logged_users[str(conn.getpeername())] = username
                    build_and_send_message(
                        conn, chatlib.PROTOCOL_SERVER["login_ok_msg"], "")
                else:
                    build_and_send_message(
                        conn, chatlib.PROTOCOL_SERVER["error_msg"],
                        "The user is already connected to the server")
            else:
                build_and_send_message(conn,
                                       chatlib.PROTOCOL_SERVER["error_msg"],
                                       "Wrong password!")
        else:
            build_and_send_message(conn, chatlib.PROTOCOL_SERVER["error_msg"],
                                   "Username does not exist")
def handle_answer_message(conn, data):
    global questions, logged_users, users
    username = logged_users[str(conn.getpeername())]
    answer = chatlib.split_data(data, 2)
    question_id = int(answer[0])

    # need to add check if it his hacker(send protocol message) -- compare with user history questions...
    user_history_question = (users.get(username))["questions_asked"]
    if question_id in user_history_question:
        build_and_send_message(conn, chatlib.PROTOCOL_SERVER["error_msg"],
                               "Hacker")
        # handle_logout_message(conn)
        # hacker
    else:
        ((users.get(username))["questions_asked"]).append(question_id)

    user_choice = answer[1]
    correct_answer = str((questions[question_id]).get("correct"))
    if user_choice == correct_answer:
        (users.get(username))["score"] = (users.get(username))["score"] + 5
        build_and_send_message(conn,
                               chatlib.PROTOCOL_SERVER["correct_answer_msg"],
                               "")
    else:
        build_and_send_message(conn,
                               chatlib.PROTOCOL_SERVER["wrong_answer_msg"],
                               correct_answer)
Beispiel #5
0
def play_question(conn):
    # question[0] = id, question[1] = question_msg , question[2/3/4/5] = opt[1/2/3/4]
    cmd, data = get_question(conn)
    if cmd == chatlib.PROTOCOL_SERVER["question_msg"]:
        question_data = chatlib.split_data(data, 6)
        return question_data[0], print_question(question_data)
        # question[0] = id, question[1] = question_msg , question[n] = opt[n]
    return None, data
Beispiel #6
0
def play_question():
    flush_console()
    global question_data
    # question_data[0] = question_id, question_data[1] = question_msg , question_data[2/3/4/5] = opt[1/2/3/4]
    cmd, data = get_question()
    if cmd == chatlib.PROTOCOL_SERVER["question_msg"]:
        try:
            question_data = chatlib.split_data(data, 6)
            top.server_msg.configure(text=question_data[1])
            for i in range(len(opt_buttons)):  # 0 < i < 3
                opt_buttons[i].configure(text=question_data[i + 2])
        except TypeError:
            question_data = [-1]
            top.server_msg.configure(text="ERROR get question, try again")
    else:
        top.server_msg.configure(text=data)
Beispiel #7
0
def play_question(conn):
    (command, data) = build_send_recv_parse(conn, chatlib.PROTOCOL_CLIENT["get_question_msg"], "")
    if command in chatlib.PROTOCOL_SERVER["no_question_ans_msg"]:
        print("No questions available")
    elif command in chatlib.PROTOCOL_SERVER["send_question_msg"]:
        recv_data_parsed = chatlib.split_data(data, 6)
        print(recv_data_parsed[1])  # prints the question
        helpers.format_list_print(recv_data_parsed, 2)
        ans = input("Enter the number of the answer: ")
        (ans_cmd, ans_data) = build_send_recv_parse(conn, chatlib.PROTOCOL_CLIENT["send_ans_msg"],
                                                    recv_data_parsed[0] + "#" + ans)
        if ans_cmd in chatlib.PROTOCOL_SERVER["correct_ans_msg"]:
            print("Correct answer")
        else:
            print("Nope, correct answer is #" + ans_data)
    else:
        error_and_exit(-1)
def handle_register_message(conn, data):
    global users  # This is needed to access the same users dictionary from all functions
    user_info = chatlib.split_data(data, 2)
    if user_info is None:
        build_and_send_message(
            conn, chatlib.PROTOCOL_SERVER["error_msg"],
            "Username and/or password cannot contain the # character")
    else:
        username = user_info[0]
        if username not in users:
            password = user_info[1]
            add_user(username, password)
            build_and_send_message(conn,
                                   chatlib.PROTOCOL_SERVER["register_ok_msg"],
                                   "")
        else:
            build_and_send_message(conn, chatlib.PROTOCOL_SERVER["error_msg"],
                                   "Username already exist")
Beispiel #9
0
def handle_answer_message(conn, username, data):
    """
    The function receives an answer from the user and checks it.
    :param conn: open socket
    :param username: player's name
    :param data: information from the socket
    :return:
    """
    global users
    answer = chatlib.split_data(
        data, 2)  # Two fields: question_id#user_answer according to protocol
    print_debug(answer)
    if str(questions[answer[0]][2]) == str(answer[1]):  # check the answer
        users[username]["score"] += CORRECT_ANSWER_SCORE  # updating user score
        build_and_send_message(conn,
                               chatlib.PROTOCOL_SERVER["correct_ans_msg"], "")
    else:
        build_and_send_message(conn, chatlib.PROTOCOL_SERVER["wrong_ans_msg"],
                               str(questions[answer[0]][2]))
Beispiel #10
0
def handle_login_message(conn, data):
    """
    Gets socket and message data of login message. Checks  user and pass exists and match.
    If not - sends error and finished. If all ok, sends OK message and adds user and address to logged_users
    Recieves: socket, message code and data
    Returns: None (sends answer to client)
    """
    global users  # This is needed to access the same users dictionary from all functions
    global logged_users  # To be used later
    msg_fields = chatlib.split_data(data, 2)
    user_name = msg_fields[0]
    user_password = msg_fields[1]
    if user_name in users:
        if users[user_name]["password"] == user_password:
            build_and_send_message(conn,
                                   chatlib.PROTOCOL_SERVER["login_ok_msg"], "")
            logged_users.update({conn.getpeername(): user_name})
        else:
            send_error(conn, "Password does not match!")
    else:
        send_error(conn, "Username does not exist!")
Beispiel #11
0
def play_question(conn):
    cmd, data = build_send_recv_parse(conn,
                                      chatlib.PROTOCOL_CLIENT["get_question"],
                                      "")
    msg_fields = chatlib.split_data(data, 6)
    if msg_fields == chatlib.ERROR_RETURN:
        print("Server message: ", data)
    else:
        print("Q: " + msg_fields[1] + ":")
        for i in range(1, 5):
            print(str(i) + ". " + msg_fields[i + 1])
        answer = input("Please choose an answer [1-4]: ")
        cmd, data = build_send_recv_parse(
            conn, chatlib.PROTOCOL_CLIENT["send_answer"],
            msg_fields[0] + "#" + answer)
        if cmd == chatlib.PROTOCOL_SERVER["correct_answer"]:
            print("Yes!! correct answer")
        elif cmd == chatlib.PROTOCOL_SERVER["wrong_answer"]:
            print("Nope, the number of the corrent answer is: " + data)
        elif cmd == chatlib.PROTOCOL_SERVER["error_msg"]:
            print("Server message: ", data)
        else:
            error_and_exit(data)
Beispiel #12
0
def handle_answer_message(conn, username, data):
    question_num, answer = chatlib.split_data(data)

    if username in in_question and in_question[username] == int(question_num):
        del in_question[username]

        try:
            correct_answer = questions[int(question_num)]['correct']
        except:
            correct_answer = 0
            print('[EXCEPT] correct_answer = 0')

        if correct_answer == int(answer):
            build_and_send_message(
                conn, chatlib.PROTOCOL_SERVER['correct_answer_msg'], '')
            users[username]['score'] += 5
            users[username]['questions_asked'] += [int(question_num)]
            load_user_database(write=True)  # TODO move to somewhere else
        else:
            build_and_send_message(conn,
                                   chatlib.PROTOCOL_SERVER['wrong_answer_msg'],
                                   str(correct_answer))
    else:
        send_error(conn, 'You are not able to get answer to this question')
Beispiel #13
0
def handle_answer_message(conn, username, data):
    global questions
    global users
    answer_fields = chatlib.split_data(data, 2)
    if answer_fields:
        question_id = answer_fields[0]
        user_answer = answer_fields[1]
        if question_id in questions.keys():
            correct_answer = str(questions[question_id]["correct"])
            if users[username]["questions_asked"][
                    -1] == question_id and correct_answer == user_answer:
                users[username]["score"] = users[username]["score"] + 5
                build_and_send_message(
                    conn, chatlib.PROTOCOL_SERVER["correct_answer"], "")
            else:
                build_and_send_message(conn,
                                       chatlib.PROTOCOL_SERVER["wrong_answer"],
                                       correct_answer)
        else:
            build_and_send_message(conn, chatlib.PROTOCOL_SERVER["error_msg"],
                                   "worng input")
    else:
        build_and_send_message(conn, chatlib.PROTOCOL_SERVER["error_msg"],
                               "worng input")