コード例 #1
0
def approve_person(message, target):
    """Approve a user, if the author of the msg is an admin."""
    users = hf.get_users()
    if target == 'me':
        return
    for user in users:
        if user["name"] == target:
            approver = message._get_user_id()
            admins = hf.get_admins()
            for admin in admins:
                if admin["id"] == approver:
                    if user is not None:
                        if user["approval_level"] == "unapproved":
                            message.reply(
                                "Approved user: <@{}>".format(target))
                            user["approval_level"] = "approved"
                            hf.save_users(users)
                            return
                        elif user["approval_level"] == "denied":
                            message.reply(Strings['MARKED_DENIED'])
                            return
                        else:
                            message.reply(":x: {} is already: {}.".format(
                                target, user["approval_level"]))
                            return
                    else:
                        message.reply(Strings['USER_NOT_FOUND'].format(target))
                        return

    message.reply(Strings['CANT_APPROVE'])
コード例 #2
0
def expireme(message):
    """Expire the user's access right away."""
    users = hf.get_users()
    requester = message._get_user_id()
    for user in users:
        if user["id"] == requester:
            name = user["name"]
            break

    hf.expire_user(name)
コード例 #3
0
def search_user(message, search):
    """Return users found from a search."""
    found = []
    search = search.lower()
    users = hf.get_users()
    for user in users:
        if search in user['name'].lower():
            found.append('{} ({})'.format(user['name'], user["id"]))
    if len(found) == 0:
        message.reply('No user found by that key: {}.'.format(search))
        return
    message.reply('Users found: {}'.format(', '.join(found)))
コード例 #4
0
def approve_me_group(message):
    """Reply to 'approve me' in the group channel (redirect to a DM)."""
    users = hf.get_users()
    sender_id = message._get_user_id()

    for user in users:
        if user["id"] == sender_id:
            if (user["approval_level"] == "unapproved"):
                message.reply(Strings['APPROVE_ME_REQUEST'])
            else:
                self_name = user["approval_level"]
                message.reply(
                    ":x: Your status is already: {}".format(self_name))
コード例 #5
0
def load_slack_users(message):
    """Put Slack users into JSON and dump into users.json.

    NOTE: USING THIS WILL RESET user.json. Uncomment the @respond_to bit
    if you really want to use this."""

    users = hf.get_users()

    for user in users:
        if user["id"] == message._get_user_id():
            if user["approval_level"] != "admin":
                message.reply("Insufficient privileges.")
                return

    with open(user_path) as outfile:
        users = json.load(outfile)

    existing_users = []

    for user in users:
        if (user["metadata"] != "" or user["approval_level"] != "unapproved"):
            existing_users.append(user)

    #print (existing_users)

    user_list = []
    for userid, user in iteritems(message._client.users):
        user_info = {}
        user_info["name"] = user["name"]
        user_info["id"] = user["id"]
        user_info[
            "approval_level"] = "unapproved"  # By default, not approved or denied
        user_info["metadata"] = ""  # Metadata to be edited later on

        user_list.append(user_info)

    if existing_users:
        for user in existing_users:
            for listed_user in user_list:
                if user["id"] == listed_user["id"]:
                    user_list[user_list.index(listed_user)] = user

    with open(user_path, 'w') as outfile:
        json.dump(user_list, outfile)

    message.reply("Successfully loaded users into json file.")
コード例 #6
0
def approve_me(message):
    """Send request to be approved to the approvers/admins."""
    users = hf.get_users()
    for user in users:
        if user["id"] == message._get_user_id():
            if user["approval_level"] == "unapproved":  # Unknown
                message.reply(Strings['APPROVER_REQUEST'])
                admins = hf.get_admins()
                names = []
                for admin in admins:
                    names.append(admin["name"])

                approval_message = Strings['APPROVER_REQUEST_DETAIL'].format(
                    ">, <@".join(names), user["name"])

                #message._client.send_message(config.AUTH_CHANNEL, approval_message)
                message._client.send_message(public_channel, approval_message)
            else:
                message.reply(":x: Your approval level is already: " +
                              str(user["approval_level"]))
コード例 #7
0
def upgrade(message, target, num):
    """Upgrade a user to the specified approval level.

    Commented out for now since this can be abused, usage should be limited."""
    return
    users = hf.get_users()

    for user in users:
        if user["name"] != target:
            continue
        try:
            user["approval_level"] = int(num)
        except Exception:
            message.reply(":x: That's not a number, ya dingus. :)")
            return

    hf.save_users(users)

    message.reply("Successfully upgraded user {} to approval level "
                  "{}.".format(target, num))
コード例 #8
0
def notify(message):
    """Start a minute-by-minute check of user expiration times and notify
       users when their time is almost up.

    Basic flow: iterate through each process every 5 seconds. Processes are:

    Hour = notify the user one hour before their access is to expire
    Tenmins = notify the user ten minutes before their access is to expire
    Deleted = notify the user when their access has expired

    Each one works by looking at notified.json or deleted.json - if the database
    is not listed for the user in question"""
    # TODO: clean up this ugly mess

    global notify_flag

    if not notify_flag:
        notify_flag = True
        message.reply(
            ":gear: Started expiration checking process; users will now "
            "be notified if their access is about to expire.")
    else:
        message.reply(
            "Cannot have more than one running instance of the notify "
            "function.")
        return

    flag = "tenmins"
    while True:
        if flag is "deleted":
            info = sql.notify_users("hour")
            flag = "hour"
        elif flag is "hour":
            info = sql.notify_users("tenmins")
            flag = "tenmins"
        elif flag is "tenmins":
            info = sql.notify_users("deleted")
            flag = "deleted"

        for person in info:
            if len(info[person]) == 0:
                continue
            try:
                users = hf.get_users()
                for user in users:
                    if user["name"] == person:
                        dbs = []
                        servers = []
                        for grant in info[person]:
                            dbs.append(grant["db"])
                            servers.append(grant["server"])
                        chan = hf.find_channel(message._client.channels,
                                               user["id"])

                        if flag is "hour":
                            message._client.send_message(
                                chan, Strings['NOTIFY_EXPIRE_HOUR'].format(
                                    ", ".join(dbs)) + "\n"
                                "" + Strings["NOTIFY_EXPIRE_INFO"])
                            for db, server in zip(dbs, servers):
                                logging.info(
                                    "{} reason=[NOTIFIED OF DATABASE ACCESS EXPIRING IN AN HOUR]\n"
                                    .format(user["name"]), server, db,
                                    "notifyhour")
                        elif flag is "tenmins":
                            message._client.send_message(
                                chan, Strings['NOTIFY_EXPIRE_TENMINS'].format(
                                    ", ".join(dbs)) + "\n"
                                "" + Strings["NOTIFY_EXPIRE_INFO"])
                            for db, server in zip(dbs, servers):
                                logging.info(
                                    "{} reason=[NOTIFIED OF DATABASE ACCESS EXPIRING IN TEN MINUTES]\n"
                                    .format(user["name"]), server, db,
                                    "notifyten")
                        elif flag is "deleted":
                            message._client.send_message(
                                chan, Strings['EXPIRE'].format(", ".join(dbs)))
                            message._client.send_message(
                                public_channel, Strings["EXPIRE_PING"].format(
                                    user["name"], ", ".join(dbs)))
                            for db, server in zip(dbs, servers):
                                logging.info(
                                    "{} reason=[NOTIFIED OF DATABASE ACCESS EXPIRING]\n"
                                    .format(user["name"]), server, db,
                                    "notifyexpire")

            except Exception as e:
                message._client.send_message(errors_channel,
                                             "```{}```".format(e))

        with open("data/jobs.json") as f:
            jobs = json.load(f)

        new_jobs = []
        if len(jobs) > 0:
            for job in jobs:
                if not job.endswith("DONE"):
                    job_string = job.replace("10.132.140.160",
                                             "SQLCLUSTER02").replace(
                                                 "10.132.140.150",
                                                 "SQLCLUSTER01")
                    message._client.send_message(
                        public_channel, Strings["LOGOUT_PLEASE"].format(
                            job_string.split(":")[0],
                            job_string.split(":")[1]))
                    new_jobs.append(job + ":DONE")
                else:
                    new_jobs.append(job)

            with open("data/jobs.json", "w") as f:
                json.dump(new_jobs, f)

        # For use with Datadog
        with open("/opt/opsbot35/data/status.txt", "w") as f:
            f.write(str(datetime.now()))

        time.sleep(5)
コード例 #9
0
def denied(message):
    """Returns list of denied users."""
    hf.query_users(message, hf.get_users(), "denied")
コード例 #10
0
def admins(message):
    """Returns list of admins."""
    hf.query_users(message, hf.get_users(), "admin")
コード例 #11
0
def unapproved(message):
    """Returns list of unapproved users."""
    hf.query_users(message, hf.get_users(), "unapproved")
コード例 #12
0
def users(message):
    """Display number of total Slack users."""
    message.reply(Strings['USERS_FOUND'].format(len(hf.get_users())))