Exemple #1
0
def send(message: str, room_id: int, author_id: int) -> None:
    """Send new message to a room."""
    # Prevent user from sending blank messages
    if message == "\n" or message[0] == " ":
        return

    user = session["special"]
    msg = f"[{time.asctime()}]{user}: " + html.escape(message)

    # Append message to room database.
    utils.call_db(event="append message",
                  return_type=bool,
                  data={
                      "room_id": room_id,
                      "author_id": author_id,
                      "author_ip": request.remote_addr,
                      "message": msg
                  })

    data = {"room_id": room_id, "message": utils.convert_to_html(msg)}

    client_socket.emit("recieve_local_message",
                       data,
                       broadcast=True,
                       include_self=True)
    client_socket.emit("new_messages", data, broadcast=True, include_self=True)
Exemple #2
0
def register():
    """Register user."""
    username = request.form["register-username"]
    password = hashlib.sha256(request.form["register-password"].encode()).hexdigest()
    confirm_password = hashlib.sha256(request.form["register-password-again"].encode()).hexdigest()
    ip = request.remote_addr

    if not password == confirm_password:
        session["register_error"] = "Password and confirmation password do not match."
        return redirect("/")

    data = {
        "filename": "accounts",
        "folder": "server",
        "table": "accounts",
        "select": "username",
        "where": f"username=\"{username}\""
    }

    # Check if user already exists
    ret = utils.call_db(
        event="retrieve table",
        data=data,
        return_type=list
    )

    if not ret:
        # Add user to database.
        utils.call_db(
            event="append table",
            data={
                "filename": "accounts",
                "folder": "server",
                "table": "accounts",
                "columns": "username, password, ip",
                "values": f"\"{username}\", \"{password}\", \"{ip}\"",
                "unique": False
            },
            return_type=bool
        )
        session["username"] = username

        user_utils.online(1, 0)
        chat_utils.autocolor("0")
        return redirect("/room/0")

    session["register_error"] = "Username already taken."
    return redirect("/")
Exemple #3
0
def login():
    """Login user."""
    username = request.form["login-username"]
    password = hashlib.sha256(
        request.form["login-password"].encode()).hexdigest()

    data = {
        "filename": "accounts",
        "folder": "server",
        "table": "accounts",
        "select": "username, password",
        "where": f"username=\"{username}\" and password=\"{password}\""
    }

    # Check if user exists.
    ret = utils.call_db(event="retrieve table", data=data, return_type=list)

    if ret:
        session["username"] = username

        user_utils.online(1, 0)
        chat_utils.autocolor("0")

        return redirect(url_for("room", room_id=0))

    session["login_error"] = "Invalid Username or Password"
    return redirect("/")
Exemple #4
0
def clear_online() -> bool:
    """Truncate online users table."""
    return utils.call_db(event="truncate",
                         return_type=bool,
                         data={
                             "filename": "server_info",
                             "folder": ".",
                             "table": "online"
                         })
Exemple #5
0
def get_account_info(username: str) -> list:
    """Get a user's info excluding their password."""
    return utils.call_db(event="retrieve table",
                         return_type=list,
                         data={
                             "filename": "accounts",
                             "folder": "server",
                             "table": "accounts",
                             "select":
                             "username, ip, status, seen, id, \"server role\"",
                             "where": f"username=\"{username}\""
                         })[0]
Exemple #6
0
def status(username: str, status: str) -> bool:
    """Set the status of a user, including when they were last seen."""
    return utils.call_db(event="update table",
                         data={
                             "filename": "accounts",
                             "folder": "server",
                             "table": "accounts",
                             "set_values":
                             f"status=\"{status}\", seen=\"{time.ctime()}\"",
                             "where": f"username=\"{username}\""
                         },
                         return_type=bool)
Exemple #7
0
def get_online() -> int:
    """Get the amount of users that are online."""
    # TODO Get usernames that are online
    returned = utils.call_db(event="retrieve table",
                             data={
                                 "filename": "server_info",
                                 "folder": ".",
                                 "table": "online",
                                 "select": "*",
                                 "where": ""
                             },
                             return_type=list)

    return len(returned)
Exemple #8
0
def create_room(args: dict) -> bool:
    """Create new room, public or private."""
    name = html.escape(args["name"])
    desc = html.escape(args["desc"])
    public = int(args["public"] == "Public")
    owner = args["owner"]

    owner_id = user_utils.get_account_info(owner)[4]
    new_room_id = base64.b64encode(str(
        secrets.randbits(128)).encode()).decode()

    # Append new room info.
    ret = utils.call_db(
        event="append table",
        return_type=bool,
        data={
            "filename": "rooms",
            "folder": ".",
            "table": "Rooms",
            "columns": "Name, Description, ID, Public",
            "values":
            f"\"{name}\", \"{desc}\", \"{new_room_id}\", \"{public}\"",
            "unique": False
        })

    # Create room database.
    returns = utils.call_db(event="create room",
                            return_type=list,
                            data={
                                "name": name,
                                "owner": owner,
                                "owner_id": owner_id,
                                "room_id": new_room_id
                            })

    return ret and all(r == True for r in returns)
Exemple #9
0
def get_account_server_role(username: str) -> str:
    """Get the user's server role."""
    data = {
        "table": "accounts",
        "filename": "accounts",
        "folder": "server",
        "select": "username, \"server role\"",
        "where": f"username=\"{username}\""
    }

    role = dict(
        utils.call_db(event="retrieve table", data=data, return_type=list))

    if username in role.keys():
        if role[username] == None:
            return ""
        return role[username]

    return ""
Exemple #10
0
def online(num: int,
           room_id: int,
           silent: bool = False,
           testing: bool = False) -> bool:
    """Set the value of whether the user is connected to the server or not."""
    # TODO Server message
    if not testing:
        session = get_session()
    else:
        session = {"username": "******"}

    event = ""
    data = {}

    # Set to Online
    if num == 1:
        event = "append table"

        data = {
            "filename": "server_info",
            "folder": ".",
            "table": "online",
            "columns": "username",
            "values": f"\"{session['username']}\"",
            "unique": True
        }

    # Set to Offline
    elif num == -1:
        event = "delete row"

        data = {
            "filename": "server_info",
            "folder": ".",
            "table": "online",
            "where": f"username=\"{session['username']}\"",
        }

    returned = utils.call_db(event=event, data=data, return_type=bool)

    return returned
Exemple #11
0
def get_account_room_role(username: str, room_id: str) -> str:
    """Get the user's assigned room role."""

    if type(room_id) != str:
        raise TypeError("Invalid type: " + str(room_id))

    data = {
        "table": "Members",
        "filename": room_id,
        "folder": "rooms",
        "select": "Username, Role",
        "where": f"username=\"{username}\""
    }

    role = dict(
        utils.call_db(event="retrieve table", data=data, return_type=list))

    if username in role.keys():
        return role[username]

    return "Member"
Exemple #12
0
    def post(self):
        """Authorize user if username and password match."""
        parser.add_argument("username")
        parser.add_argument("password")

        args = parser.parse_args()
        username = args["username"]
        password = args["password"]

        data = {
            "filename": "accounts",
            "folder": "server",
            "table": "accounts",
            "select": "username, password",
            "where": f"username=\"{username}\" and password=\"{password}\""
        }

        # Check
        ret = utils.call_db(event="retrieve table",
                            data=data,
                            return_type=list)
        return ret
Exemple #13
0
def gateway() -> bool:
    """Check whether the user is banned or not."""
    ip = request.remote_addr

    data = {
        "filename": "blacklist",
        "folder": "server",
        "table": "blacklist",
        "select": "ip",
        "where": f"ip=\"{ip}\""
    }

    is_blacklisted = utils.call_db(function=rss.rss_socket.emit,
                                   event="retrieve table",
                                   data=data,
                                   return_type=list)

    blacklisted_users = [user[0] for user in is_blacklisted]

    if ip in blacklisted_users:
        return True

    return False