Example #1
0
def get_app():
    app = Quart(__name__)

    app.secret_key = b"%\xe0'\x01\xdeH\x8e\x85m|\xb3\xffCN\xc9g"
    os.environ[
        "OAUTHLIB_INSECURE_TRANSPORT"] = "true"  # !! Only in development environment.

    # app.config["DISCORD_CLIENT_ID"] = 490732332240863233
    app.config["DISCORD_CLIENT_SECRET"] = os.getenv("DISCORD_CLIENT_SECRET")
    app.config["DISCORD_BOT_TOKEN"] = os.getenv("DISCORD_BOT_TOKEN")
    app.config["DISCORD_REDIRECT_URI"] = "http://127.0.0.1:5000/callback"

    app.discord = DiscordOAuth2Session(app, client_id=490732332240863233)

    return app
Example #2
0
from quart import Quart, render_template, request, session, redirect, url_for, flash, flask_patch
from quart_discord import DiscordOAuth2Session, Unauthorized, configs
from quart_discord.utils import requires_authorization as req_auth
from modules import *
from dotenv import load_dotenv
from os import getenv
load_dotenv()

app = Quart(__name__)
app.config["SECRET_KEY"] = getenv('SECRET_KEY')
app.config["DISCORD_CLIENT_ID"] = getenv('CLIENT_ID')
app.config["DISCORD_CLIENT_SECRET"] = getenv('CLIENT_SECRET')
app.config["DISCORD_REDIRECT_URI"] = getenv('REDIRECT_URI')

ipc_client = None
discord = DiscordOAuth2Session(app)


@app.route("/")
async def home():
    try:
        user = await discord.fetch_user()
    except Unauthorized:
        user = None
    return await render_template("index.html", user=user)


@app.route("/login")
async def login():
    try:
        await discord.fetch_user()
Example #3
0
sahasrahbotapi.secret_key = bytes(os.environ.get("APP_SECRET_KEY"), "utf-8")

RACETIME_CLIENT_ID_OAUTH = os.environ.get('RACETIME_CLIENT_ID_OAUTH')
RACETIME_CLIENT_SECRET_OAUTH = os.environ.get('RACETIME_CLIENT_SECRET_OAUTH')
RACETIME_URL = os.environ.get('RACETIME_URL', 'https://racetime.gg')
APP_URL = os.environ.get('APP_URL', 'https://sahasrahbotapi.synack.live')

sahasrahbotapi.config["DISCORD_CLIENT_ID"] = int(
    os.environ.get("DISCORD_CLIENT_ID"))
sahasrahbotapi.config["DISCORD_CLIENT_SECRET"] = os.environ.get(
    "DISCORD_CLIENT_SECRET")
sahasrahbotapi.config["DISCORD_REDIRECT_URI"] = os.environ.get(
    "APP_URL") + "/callback/discord/"
sahasrahbotapi.config["DISCORD_BOT_TOKEN"] = os.environ.get("DISCORD_TOKEN")

discord = DiscordOAuth2Session(sahasrahbotapi)


@sahasrahbotapi.route("/login/")
async def login():
    return await discord.create_session(
        scope=[
            'identify',
        ],
        data=dict(redirect=session.get("login_original_path", "/me")))


@sahasrahbotapi.route("/callback/discord/")
async def callback():
    data = await discord.callback()
    redirect_to = data.get("redirect", "/me/")
Example #4
0
File: server.py Project: UOAF/ATO
def create_app(config_file_name='config.py'):
    asyncio.set_event_loop(asyncio.new_event_loop())
    dbFile = os.path.join(os.path.dirname(__file__), 'db.json')
    db = Store(dbFile)
    app = Quart(__name__)
    app.config.from_pyfile('config.py')
    discord_auth = DiscordOAuth2Session(app)
    bot = Bot(app.config["ATO_PRIMARY_GUILD_ID"])

    try:
        verbose_debug = app.config["VERBOSE_DEBUG"]
    except KeyError:
        verbose_debug = False
    if verbose_debug:
        LOG_FORMAT = "[%(levelname)-8s][%(filename)24s:%(lineno)-4s "
        LOG_FORMAT += "%(funcName)32s() ]%(name)s: %(message)s"
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)

    app.secret_key = b"random bytes representing Quart secret key"

    # Prevent us from spamming discord's API when authenticating
    discord_oauth_lock = Lock()

    def requires_role(role_name):
        def decorator(view_func):
            @functools.wraps(view_func)
            async def wrapper(*args, **kwargs):
                async with discord_oauth_lock:
                    if not await discord_auth.authorized():
                        raise Unauthorized()
                    user = await discord_auth.fetch_user()
                    roles = bot.get_roles_of_user(user.id)
                    role_names = [r.name for r in roles]
                    if role_name not in role_names:
                        raise MissingMembership()
                    else:
                        return await view_func(*args, **kwargs)
            return wrapper
        return decorator

    @app.before_serving
    async def startup():
        discord_oauth_lock.create()
        asyncio.create_task(bot.run())

    @app.route("/login/")
    async def login():
        result = await discord_auth.create_session()
        return result

    @app.route("/logout/")
    async def logout():
        discord_auth.revoke()
        return redirect("/")

    @app.route("/callback/")
    async def callback():
        await discord_auth.callback()
        return redirect(url_for(".index"))

    @app.errorhandler(Unauthorized)
    async def redirect_unauthorized(e):
        return redirect(url_for("login"))

    @app.errorhandler(MissingMembership)
    async def render_missing_membership(e):
        return await render_template('unauthorized.html'), 401

    @app.route("/all_events/", methods=["GET"])
    @requires_membership(discord_oauth_lock)
    async def all_events():
        return {'events': db.get_all_events()}

    @app.route('/upcoming_events/', defaults={'n': 4})
    @app.route("/upcoming_events/<n>")
    @requires_membership(discord_oauth_lock)
    async def getLatestEvents(n=4):
        n = int(n)
        return {'events': db.get_upcoming_events(n)}

    @app.route("/event/")
    @app.route("/event/<event_id>", methods=["GET", "PUT", "POST", "DELETE"])
    @requires_membership(discord_oauth_lock)
    async def event(event_id=None):
        event_id = int(event_id) if event_id else None

        if request.method == "GET":
            event = db.get_event(event_id)
            if event is None:
                await abort(404, "Event not found.")
            return event

        elif request.method == "PUT":
            event = db.get_event(event_id)
            if event is None:
                await abort(404, "Event not found.")
            event_data = await request.get_json()
            db.update_event(event_id, event_data)

        elif request.method == "POST":
            event_data = await request.get_json()
            db.update_event(event_data)

        elif request.method == "DELETE":
            db.delete_event(event_id)

    @app.route("/user/")
    @requires_membership(discord_oauth_lock)
    async def get_user_info():
        user = await discord_auth.fetch_user()
        roles = bot.get_roles_of_user(user.id)
        role_names = [r.name for r in roles]

        return {
            'username': user.name,
            'avatar_url': str(user.avatar_url),
            'id': user.id,
            'roles': role_names,
            'admin': ('Roster' in role_names)
        }

    @app.route("/user/<user_id>")
    async def get_other_user(user_id):
        user_id = int(user_id)
        user = bot.get_member_by_id(user_id)
        roles = bot.get_roles_of_user(user_id)
        role_names = [r.name for r in roles]

        return {
            'username': user.display_name,
            'avatar_url': str(user.avatar_url),
            'id': user.id,
            'roles': role_names,
            'admin': ('Roster' in role_names)
        }

    @app.route("/all_users/")
    @requires_membership(discord_oauth_lock)
    async def get_all_users():
        users = bot.get_all_users()
        return {
            'Users': [{'id': u.id, 'name': u.display_name} for u in users]
        }

    @app.route("/admin_test/")
    @requires_role('Roster')
    async def admin_test():
        return "You are an admin!!!"

    @app.route("/admin_test_negative/")
    @requires_role('Rooster')
    async def admin_test_negative():
        return "You are an admin!!!"

    @app.route("/")
    @requires_authorization
    async def index():
        x = await send_file('static/index.html')
        return x

    return app
Example #5
0
async def key_func():
    ip = request.headers.get("X-Forwarded-For", request.remote_addr)
    return ip


app = Quart(import_name=__name__,
            template_folder='website/templates',
            static_folder='website/static')
app.secret_key = secrets.token_hex(16)
app.config["DISCORD_CLIENT_ID"] = 667117267405766696
app.config["DISCORD_CLIENT_SECRET"] = config.SECRET
app.config["DISCORD_REDIRECT_URI"] = "https://dredd-bot.xyz/callback"
app.config["DISCORD_BOT_TOKEN"] = config.MAIN_TOKEN

discord_session = DiscordOAuth2Session(app)
rate_limiter = RateLimiter(app, key_function=key_func)

app.register_blueprint(site)
app.register_blueprint(api)

AVATARS_FOLDER = os.path.join('/static/images')
not_found_icon = os.path.join(AVATARS_FOLDER, 'not_found.png')
image = os.path.join(AVATARS_FOLDER, WebsiteTheme.icon)

db_client = MongoClient(config.MONGO)
db = db_client.get_database('website')


@app.before_serving
async def run():
Example #6
0
    },
})

template_folder_path = os.path.abspath('Website/src')
static_folder_path = os.path.abspath('Website/static')
app = Quart(__name__,
            template_folder=template_folder_path,
            static_folder=static_folder_path)
ipc_client = ipc.Client(secret_key=bot.env_vars["IPC_SECRET"])
app.config["SECRET_KEY"] = str(bot.env_vars["SECRET_KEY"])
app.config["DISCORD_CLIENT_ID"] = int(
    bot.env_vars["DISCORD_CLIENT_ID"])  # Discord client ID.
app.config["DISCORD_CLIENT_SECRET"] = str(
    bot.env_vars["DISCORD_CLIENT_SECRET"])  # Discord client secret.
app.config["DISCORD_REDIRECT_URI"] = str(bot.env_vars["DISCORD_REDIRECT_URI"])
discord_auth = DiscordOAuth2Session(app)


class DiscordClient:
    def __init__(self):
        self.bot = discord.Client(intents=discord.Intents.all())

    async def get_guild(self, id):
        await self.bot.wait_until_ready()

        return self.bot.get_guild(id)

    async def get_channel(self, id):
        await self.bot.wait_until_ready()

        return self.bot.get_channel(id)
Example #7
0
from quart_discord import DiscordOAuth2Session
from quart import render_template, redirect, url_for
from discord.ext import ipc

from main import app
from Data import config
from . import blueprint

discord = DiscordOAuth2Session(app)  # figure out why this isn't working.
ipc_client = ipc.Client(secret_key="Swas")


@blueprint.route("/")
async def home():
    print("tried")
    return await render_template("index.html",
                                 authorized=await discord.authorized,
                                 discord=discord)


@blueprint.route("/login")
async def login():
    return await discord.create_session()


@blueprint.route("/callback")
async def callback():
    try:
        await discord.callback()
    except Exception:
        pass