Esempio n. 1
0
def signin():
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    if not username or not password:
        return jsonify({"message": "Format does not match"}), 400

    sql = "SELECT user_id, username, password FROM authinfo WHERE username=?;"
    try:
        user = db(sql, [username])
        logger.debug(f'username={username}')
        if not user:
            return jsonify({"message": "Bad username or password"}), 401

        logger.debug(f'{user}')
        if bcrypt.checkpw(password.encode(), user["password"].encode()):
            sql = "UPDATE authinfo SET updated_at=? WHERE username=?;"
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
            db(sql, [timestamp, username])
        else:
            return jsonify({"message": "Bad username or password"}), 401
    except Exception as e:
        logger.error(traceback.format_exc())
        return jsonify({"message": "An error occurred"}), 500

    access_token = create_access_token(identity=user["user_id"])
    sql = "UPDATE authinfo SET jti=? WHERE username=?;"
    db(sql, [get_jti(access_token), username])

    return jsonify(access_token=access_token), 200
Esempio n. 2
0
    async def link_social_media(self, ctx, media, name):

        data = module.db("socialMedias").getDb()
        if media.lower() not in data["emojis"].keys():
            await ctx.send("That social media is not allowed to be linked")
            return

        link = {media.lower(): name}

        users = module.db("users").getDb()["users"]

        userInDb = False

        for user in users:
            if user["id"] == str(ctx.author.id):
                userInDb = True

        if not userInDb:
            users.append({
                "id": str(ctx.author.id),
                "links": [],
                "description": "No special description for this user",
                "infractions": 0
            })

        for user in users:
            if str(user["id"]) == str(ctx.author.id):
                if (link in user["links"]):
                    user["links"].pop(user["links"].index(link))
                    await ctx.send("Removed link")
                else:
                    try:
                        user["links"].append(link)
                    except:
                        user["links"] = [link]
                    break
                    await ctx.send("Added link")

        module.db("users").saveDb({"users": users})
Esempio n. 3
0
def signup():
    if not request.is_json:
        return jsonify({"message": "Missing JSON in request"}), 400
    data = request.get_json()
    username = data["username"]
    password = data["password"]
    password_conf = data["passwordConf"]

    print(f'signup request: username={username}, password={password}, password_conf={password_conf}')

    if username and username.encode().isalnum() and password != password_conf:
        return jsonify({"mode": "signup", "status": "error", "message": "Format does not match"}), 400

    sql = "SELECT * FROM authinfo WHERE username=?;"
    if db(sql, [ username ]):
        return jsonify({"mode": "signup", "status": "error", "message": "This username cannot be used"}), 400

    salt = bcrypt.gensalt(rounds=10, prefix=b"2a")
    hashed_pass = bcrypt.hashpw(password.encode(), salt).decode()
    sql = "INSERT INTO authinfo (username, password) VALUES (?, ?);"
    db(sql, [username, hashed_pass])
    return jsonify({"mode": "signup", "status": "success", "message": "Completed"}), 200
Esempio n. 4
0
    async def records(self, ctx, user: discord.Member):
        userJson = {}

        users = module.db("users").getDb()["users"]
        for dbUser in users:
            if dbUser["id"] == str(user.id):
                userJson = dbUser

        if userJson == {}:
            print("No user found")
            userJson = {
                "id": str(ctx.author.id),
                "description": "No special info about user",
                "links": [],
                "infractions": 0
            }

        embed = discord.Embed(
            color=discord.Color.from_rgb(254, 254, 254),
            title=f"{user.name}#{user.discriminator}",
            description=userJson["description"] + "\n",
        )
        embed.add_field(name="Infractions", value=str(userJson["infractions"]))

        smString = ""

        for sm in userJson["links"]:
            data = module.db("socialMedias").getDb()
            index = list(data["emojis"].keys()).index(list(sm.keys())[0])
            emoji = list(data["emojis"].values())[index]
            smString += f"{emoji}{list(sm.values())[0]}\n"

        if smString != "":
            embed.add_field(name="Social Media", value=smString, inline=False)

        embed.set_thumbnail(url=user.avatar_url)

        await ctx.send(embed=embed)
Esempio n. 5
0
    async def unmute(self, ctx, user: discord.Member):
        db = module.db("users")
        data = db.getDb()
        found_user = -1
        for i, db_user in enumerate(data["users"]):
            if db_user["id"] == str(user.id):
                found_user = i
        if found_user == -1:
            await ctx.send("User is not in the database")
            return

        for role in data["users"][found_user]["roles"]:
            role = get(ctx.guild.roles, id=role)
            if role.name != "@everyone":
                await user.add_roles(role)

        role = get(ctx.guild.roles, name="Muted")
        try:
            await user.remove_roles(role)
        except:
            await ctx.send("User isn't muted")
        await ctx.send(f"{user} has been unmuted")
Esempio n. 6
0
    async def mute(self,
                   ctx,
                   user: discord.Member,
                   *,
                   reason: Optional[str] = "None provided"):
        db = module.db("users")
        data = db.getDb()
        found_user = -1
        for i, db_user in enumerate(data["users"]):
            if db_user["id"] == user.id:
                found_user = i

        if found_user == -1:
            roles = []
            for role in user.roles:
                roles.append(role.id)
            data["users"].append({
                "id": str(user.id),
                "links": [],
                "description": [],
                "infractions": 0,
                "roles": roles
            })

        db.saveDb(data)

        try:
            for owned_role in user.roles:
                if owned_role.name != "@everyone":
                    await user.remove_roles(owned_role, reason=reason)

            role = get(ctx.guild.roles, name="Muted")
            await user.add_roles(role, reason=reason)
        except:
            await ctx.send("User is already muted")
        await ctx.send(f"{user} has been muted for reason: `{reason}`")