Aller au contenu

Serveur web

handler(req) async

Source code in etuutt_bot/routes/home.py
async def handler(req: web.Request) -> web.Response:
    api_settings: ApiConfig = req.app["bot"].settings.etu_api
    raise web.HTTPFound(  # HTTP 302
        f"{api_settings.url}/oauth/authorize"
        f"?client_id={api_settings.client_id}&response_type=code&state={req.app['api_state']}"
    )

handler(req) async

Source code in etuutt_bot/routes/login.py
async def handler(req: web.Request) -> web.Response:
    # Unauthorized if not code in query string
    api_settings: ApiConfig = req.app["bot"].settings.etu_api
    if not req.query.get("code") or req.query.get("state") != req.app["api_state"]:
        return web.HTTPUnauthorized()  # HTTP 401
    # Request to obtain the access token
    auth = aiohttp.BasicAuth(
        str(api_settings.client_id), api_settings.client_secret.get_secret_value()
    )
    data = {"grant_type": "authorization_code", "code": req.query.get("code")}
    async with req.app["bot"].session.post(
        f"{api_settings.url}/oauth/token", auth=auth, data=data
    ) as response:
        if response.status != 200:
            return web.Response(status=response.status)
        resp = await response.json()
        try:
            token = resp["access_token"]
        except KeyError:
            return web.HTTPBadRequest()  # HTTP 400
    guild_settings: GuildConfig = req.app["bot"].settings.guild
    return await aiohttp_jinja2.render_template_async(
        "form.html.jinja",
        req,
        {
            "token": token,
            "discord_link": guild_settings.invite_link,
            "admin": guild_settings.special_roles.admin,
        },
    )

handler(req) async

Source code in etuutt_bot/routes/role.py
async def handler(req: web.Request) -> web.Response:
    if req.method != "POST":
        return web.HTTPMethodNotAllowed(req.method, ["POST"])  # HTTP 405
    post = await req.post()
    bot: EtuUTTBot = req.app["bot"]

    if not "etu-token" and "discord-username" in post:
        return web.HTTPBadRequest()

    if post.get("check-GDPR") != "on":
        return await aiohttp_jinja2.render_template_async(
            "error.html.jinja",
            req,
            {
                "error": "Vous n'avez pas coché la case de consentement RGPD. "
                "Vos données n'ont pas été traitées."
            },
        )

    params = {"access_token": post.get("etu-token")}
    async with bot.session.get(
        f"{bot.settings.etu_api.url}/public/user/account", params=params
    ) as response:
        if response.status != 200:
            return web.Response(status=response.status)
        try:
            resp = (await response.json()).get("data")
            api_user = ApiUserSchema.model_validate(resp)
        except ValidationError:
            return web.HTTPBadRequest()

    if member := bot.watched_guild.get_member_named(post.get("discord-username")):
        user_service = UserService(bot)
        await user_service.sync(member, api_user)
        return web.Response(text="Roles assigned!")
        # TODO: make better response
    return await aiohttp_jinja2.render_template_async(
        "error.html.jinja",
        req,
        {
            "error": "Utilisateur non trouvé dans le serveur. "
            "Avez-vous bien rejoint le serveur Discord ?<br>"
            "Avez-vous bien rentré votre nom d'utilisateur et pas votre nom d'affichage ?"
        },
    )