Example #1
0
def send_msg(params):
    """
    Sends message in chat.
    """
    client = get_client_manager().get_client(int(params.GET.get("id")))
    if client is None:
        return {"status": False, "err": "Not a client"}
    msg = base64.b64decode(params.GET.get("msg")).replace('%u', r'\u').decode('unicode-escape')
    get_chat().send(msg, client)
    return {"status": True}
Example #2
0
def chat(id):
    # Check that user is logged in
    if "logged_in" not in session or "user" not in session:
        return redirect(url_for("login"))
    user_id = session["user"]["id"]
    username = session["user"]["username"]

    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Not found"), 404)
    chat_id = chat.id
    session["chat_id"] = chat_id

    other_userid = chat.user1_id
    other_username = chat.user1_name
    encrypted_symmetric_key = chat.user2_sk_sym
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name
        encrypted_symmetric_key = chat.user1_sk_sym

    messages = [message.to_dict() for message in models.get_chat_messages(id)]
    return render_template(
        "chat.html",
        chat_id=chat_id,
        enc_sym_key=encrypted_symmetric_key,
        messages=messages,
        user_id=user_id,
        username=username,
        other_user=other_username,
    )
Example #3
0
def chat(id):
    # Check that user is logged in
    if 'logged_in' not in session or 'user' not in session:
        return redirect(url_for('login'))
    user_id = session['user']['id']
    username = session['user']['username']
    # Check that this chat exists and user is valid participant
    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Not found"), 404)
    chat_id = chat.id
    session['chat_id'] = chat_id
    # Get the 'other' user in the chat
    other_userid = chat.user1_id
    other_username = chat.user1_name
    encrypted_symmetric_key = chat.user2_sk_sym
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name
        encrypted_symmetric_key = chat.user1_sk_sym
    # Get messages for this chat and render the chat view
    messages = [message.to_dict() for message in models.get_chat_messages(id)]
    return render_template('chat.html',
                           chat_id=chat_id,
                           enc_sym_key=encrypted_symmetric_key,
                           messages=messages,
                           user_id=user_id,
                           username=username,
                           other_user=other_username)
Example #4
0
def delete_chat(id):
    user_id = current_user().id
    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Chat not found"), 404)
    models.delete_chat(id)
    return jsonify(success=f"Chat {id} deleted successfully")
Example #5
0
def chat(id):
    username = current_user().username
    user_id = current_user().id
    # Check that this chat exists and user is valid participant
    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Chat not found"), 404)
    chat_id = chat.id
    active_chats[user_id] = chat_id

    # Get the 'other' user in the chat
    other_userid = chat.user1_id
    other_username = chat.user1_name
    encrypted_symmetric_key = chat.user2_sk_sym
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name
        encrypted_symmetric_key = chat.user1_sk_sym
    # Get messages for this chat and render the chat view
    messages = [message.to_dict() for message in models.get_chat_messages(id)]
    return jsonify(
        chat_id=chat_id,
        enc_sym_key=encrypted_symmetric_key,
        messages=messages,
        user_id=user_id,
        username=username,
        other_user=other_username,
    )
Example #6
0
def joined(data):
    username = session["user"]["username"]
    chat_id = session["chat_id"]
    if username is None or chat_id is None:
        return False
    chat = models.get_chat(chat_id)
    if username != chat.user1_name and username != chat.user2_name:
        return False
    join_room(chat_id)
Example #7
0
def delete_chat(id):
    # Check that user is logged in
    if "logged_in" not in session or "user" not in session:
        return redirect(url_for("login"))
    user_id = session["user"]["id"]

    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Not found"), 404)
    models.delete_chat(id)
    return redirect(url_for("home"))
Example #8
0
def search_results(id):

    if request.method == "POST":
        if "logged_in" not in session or "user" not in session:
            return jsonify(error="Unauthorized request.")

        search_token = request.form.get("token", "")
        result_count = request.form.get("count", "")

        if "" in [search_token, result_count]:
            return jsonify(
                error="Bad request. No search token or result count found.")
        else:
            search_token = unicode(search_token).encode("utf8")
            if result_count == "":
                result_count = 0
            result_count = int(result_count)

        message_ids = models.get_message_ids(search_token, result_count)

        session["search_ids"] = message_ids
        return jsonify(success="DB search successful.")
    elif request.method == "GET":
        # Check that user is logged in
        if "logged_in" not in session or "user" not in session:
            return redirect(url_for("login"))
        if "search_ids" not in session:
            return redirect(url_for("chat", id=id))
        else:
            message_ids = session["search_ids"]
            messages = models.get_messages(message_ids)

            chat = models.get_chat(id)
            chat_id = chat.id
            user_id = session["user"]["id"]
            username = session["user"]["username"]
            # Get the 'other' user in the chat
            other_userid = chat.user1_id
            other_username = chat.user1_name
            encrypted_symmetric_key = chat.user2_sk_sym
            if user_id == chat.user1_id:
                other_userid = chat.user2_id
                other_username = chat.user2_name
                encrypted_symmetric_key = chat.user1_sk_sym

            return render_template(
                "chat_search.html",
                chat_id=chat_id,
                enc_sym_key=encrypted_symmetric_key,
                messages=messages,
                user_id=user_id,
                username=username,
                other_user=other_username,
            )
Example #9
0
def delete_chat(id):
    # Check that user is logged in
    if 'logged_in' not in session or 'user' not in session:
        return redirect(url_for('login'))
    user_id = session['user']['id']
    # Check that this chat exists and user is valid participant
    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Not found"), 404)
    models.delete_chat(id)
    return redirect(url_for('home'))
Example #10
0
def get_msg(_):
    """
    :return: Last messages in chat.
    """
    result = []
    for msg in get_chat().get_messages():
        result.append({
            "id": msg.get_msg_id(),
            "sender": msg.get_sender(),
            "text": msg.get_msg()
        })
    return result
Example #11
0
def search_results(id):

    if request.method == 'POST':
        # Check that user is logged in
        if 'logged_in' not in session or 'user' not in session:
            return jsonify(error="Unauthorized request.")

        search_token = request.form.get('token', '')
        result_count = request.form.get('count', '')

        if '' in [search_token, result_count]:
            return jsonify(
                error="Bad request. No search token or result count found.")
        else:
            search_token = unicode(search_token).encode('utf8')
            if result_count == '':
                result_count = 0
            result_count = int(result_count)

        message_ids = models.get_message_ids(search_token, result_count)

        session['search_ids'] = message_ids
        return jsonify(success="DB search successful.")
    elif request.method == 'GET':
        # Check that user is logged in
        if 'logged_in' not in session or 'user' not in session:
            return redirect(url_for('login'))
        if 'search_ids' not in session:
            return redirect(url_for('chat', id=id))
        else:
            message_ids = session['search_ids']
            messages = models.get_messages(message_ids)

            chat = models.get_chat(id)
            chat_id = chat.id
            user_id = session['user']['id']
            username = session['user']['username']
            # Get the 'other' user in the chat
            other_userid = chat.user1_id
            other_username = chat.user1_name
            encrypted_symmetric_key = chat.user2_sk_sym
            if user_id == chat.user1_id:
                other_userid = chat.user2_id
                other_username = chat.user2_name
                encrypted_symmetric_key = chat.user1_sk_sym

            return render_template('chat_search.html',
                                   chat_id=chat_id,
                                   enc_sym_key=encrypted_symmetric_key,
                                   messages=messages,
                                   user_id=user_id,
                                   username=username,
                                   other_user=other_username)
Example #12
0
def joined(data):
    """Sent by clients when they enter a chat.
    A status message is broadcast to all people in the chat."""
    username = session['user']['username']
    chat_id = session['chat_id']
    # Safety check
    if username is None or chat_id is None:
        return False
    chat = models.get_chat(chat_id)
    # Check that user is valid participant in chat
    if username != chat.user1_name and username != chat.user2_name:
        return False
    # Join chat room
    join_room(chat_id)
Example #13
0
def left(data):
    chat_id = session["chat_id"]
    # Safety check
    if chat_id is None:
        return False

    chat = models.get_chat(chat_id)
    username = session["user"]["username"]
    # Safety check
    if chat is None or username is None:
        return False

    if username != chat.user1_name and username != chat.user2_name:
        return False

    leave_room(session["chat_id"])
    session["chat_id"] = None
Example #14
0
def left(data):
    """Sent by clients when they leave a chat.
    A status message is broadcast to both people in the chat."""
    chat_id = session['chat_id']
    # Safety check
    if chat_id is None:
        return False
    # Fetch chat from database
    chat = models.get_chat(chat_id)
    username = session['user']['username']
    # Safety check
    if chat is None or username is None:
        return False
    # Check that user is valid participant in chat
    if username != chat.user1_name and username != chat.user2_name:
        return False
    # Leave room and reset session variable for chat id
    leave_room(session['chat_id'])
    session['chat_id'] = None
Example #15
0
def new_message(data):
    """Sent by a client when the user entered a new message.
    The message is sent to both people in the chat."""
    message = data["msg"]
    print("New received message bro! was {}".format(message), file=sys.stdout)
    username = current_user().username
    user_id = current_user().id
    chat_id = active_chats[user_id]
    # Safety check
    if None in [message, user_id, chat_id
                ] or len(message) == 0 or len(message) > 500:
        return False
    chat = models.get_chat(chat_id)
    # Check that user is valid participant in chat
    if username != chat.user1_name and username != chat.user2_name:
        return False
    # Get the 'other' user in the chat
    other_userid = chat.user1_id
    other_username = chat.user1_name
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name
    # Insert message into db
    msg = models.add_message(message, user_id, username, other_userid,
                             other_username, chat_id)
    # Safety check
    if msg is None:
        return False
    # Update the chat's last message time
    models.update_chat_last_message_time(chat_id, msg.dt)
    # Send message back to client
    emit(
        "message",
        {
            "sender": msg.sender_username,
            "receiver": msg.receiver_username,
            "msg": msg.text,
            "id": msg.id,
            "dt": msg.dt.isoformat(),
        },
        room=chat_id,
    )
Example #16
0
def left(data):
    """Sent by clients when they leave a chat.
    A status message is broadcast to both people in the chat."""
    username = current_user().username
    user_id = current_user().id
    chat_id = active_chats[user_id]
    # Safety check
    if chat_id is None:
        return False
    # Fetch chat from database
    chat = models.get_chat(chat_id)
    # Safety check
    if chat is None or username is None:
        return False
    # Check that user is valid participant in chat
    if username != chat.user1_name and username != chat.user2_name:
        return False
    # Leave room and reset session variable for chat id
    leave_room(chat_id)
    active_chats[user_id] = None
Example #17
0
def joined(data):
    """
    Sent by clients when they enter a chat.
    A status message is broadcast to all people in the chat.
    """
    # we hope that preview token auth is still saved in flask_pretorian
    # without passing an preatorian auth decorator here
    print("User now is joined to chat", file=sys.stdout)
    username = current_user().username
    user_id = current_user().id
    chat_id = active_chats[user_id]
    # Safety check
    if username is None or user_id is None or chat_id is None:
        return False

    chat = models.get_chat(chat_id)
    # Check that user is valid participant in chat
    if username != chat.user1_name and username != chat.user2_name:
        return False
    # Join chat room
    join_room(chat_id)
Example #18
0
def new_message(data):
    message = data["msg"]
    user_id = session["user"]["id"]
    username = session["user"]["username"]
    chat_id = session["chat_id"]
    # Safety check
    if None in [message, user_id, chat_id
                ] or len(message) == 0 or len(message) > 500:
        return False
    chat = models.get_chat(chat_id)

    if username != chat.user1_name and username != chat.user2_name:
        return False

    other_userid = chat.user1_id
    other_username = chat.user1_name
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name

    msg = models.add_message(message, user_id, username, other_userid,
                             other_username, chat_id)

    if msg is None:
        return False

    models.update_chat_last_message_time(chat_id, msg.dt)

    emit(
        "message",
        {
            "sender": msg.sender_username,
            "receiver": msg.receiver_username,
            "msg": msg.text,
            "id": msg.id,
            "dt": msg.dt.isoformat(),
        },
        room=chat_id,
    )
Example #19
0
def new_message(data):
    """Sent by a client when the user entered a new message.
    The message is sent to both people in the chat."""
    message = data['msg']
    user_id = session['user']['id']
    username = session['user']['username']
    chat_id = session['chat_id']
    # Safety check
    if None in [message, user_id, chat_id
                ] or len(message) == 0 or len(message) > 500:
        return False
    chat = models.get_chat(chat_id)
    # Check that user is valid participant in chat
    if username != chat.user1_name and username != chat.user2_name:
        return False
    # Get the 'other' user in the chat
    other_userid = chat.user1_id
    other_username = chat.user1_name
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name
    # Insert message into DB
    msg = models.add_message(message, user_id, username, other_userid,
                             other_username, chat_id)
    # Safety check
    if msg is None:
        return False
    # Update the chat's last message time
    models.update_chat_last_message_time(chat_id, msg.dt)
    # Send message back to client
    emit('message', {
        'sender': msg.sender_username,
        'receiver': msg.receiver_username,
        'msg': msg.text,
        'id': msg.id,
        'dt': msg.dt.isoformat()
    },
         room=chat_id)