Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Captcha test #92

Merged
merged 1 commit into from
Mar 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions config/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ APPLICATION_ID=
DEVELOPER_ID=
DEVELOPER_GUILD_ID=

# HTTP Server

TURNSTILE_SITE_KEY=
TURNSTILE_SECRET_KEY=

# Api Keys

CLOUDFLARE_ACCOUNT_ID=
Expand Down
64 changes: 61 additions & 3 deletions src/commands/web/HTTPServer.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
from nextcord.ext.commands import Bot, Cog
from aiohttp import request as aiohttp_request
from aiohttp.web import \
Application, \
AppRunner, \
Response, \
Request, \
RequestHandler, \
TCPSite, \
HTTPFound, \
HTTPTemporaryRedirect, \
middleware
from datetime import datetime, timezone
from os.path import join, abspath
import aiohttp_jinja2 as aiojinja
import jinja2
import asyncio
import base64
import psutil
import json
import ssl
import os

import requests
import hashlib

from utils.terminal import getlogger
from utils.config import config
Expand Down Expand Up @@ -53,6 +61,7 @@ def __init__(self,
self.app.router.add_static('/static/', STAITC_DIR, show_index=True)
aiojinja.setup(self.app, loader=jinja2.FileSystemLoader(TEMPLATES_DIR))
self.app.middlewares.append(self.logger)
self.app.middlewares.append(self.captchaMiddleware)

# user
self.app.router.add_get('/', self.index)
Expand All @@ -66,7 +75,9 @@ def __init__(self,
self.app.router.add_get('/invite', self.invite)
self.app.router.add_get('/contact', self.contact)

self.app.router.add_get('/authorize', self.authorize)
self.app.router.add_get('/captcha', self.captcha)
#self.app.router.add_post('/captcha', self.captcha)
self.app.router.add_get('/authorize', self.authorize)

# api
self.app.router.add_get('/api/status', self.status)
Expand All @@ -78,17 +89,64 @@ def __init__(self,
async def logger(self, request : Request, handler : RequestHandler):
response : Response = await handler(request)

logger.info(request.message)

log = f"{request.remote} - {request.method} ({response.status}) {request.path}"

if response.status < 399: logger.info(log)
else: logger.error(log)

return response

@middleware
async def captchaMiddleware(self, request : Request, handler : RequestHandler):
if request.path.startswith(('/static','/captcha')):
return await handler(request)

loggedin = request.cookies.get('__cf_logged_in')

if not loggedin or loggedin != "1":
raise HTTPFound(f'/captcha{"?r="+request.path if request.path != '/' else ''}')

return await handler(request)

# user

#@aiojinja.template('captcha.html')
async def captcha(self, request : Request):
r = request.query.get('r', '/')

print(request.headers)

if request.method == "POST":
# URL dell'endpoint di verifica di Cloudflare Turnstile
url = "https://challenges.cloudflare.com/turnstile/v0/siteverify"

# Prepara i dati da inviare nella richiesta POST
data = {
'secret': os.environ['TURNSTILE_SECRET_KEY'],
'response': request.headers.get('cf-turnstile-response'),
'remoteip': request.headers.get('CF-Connecting-IP', request.header.get('Referer'))
}

async with aiohttp_request('POST', url, data=data) as response:
outcome = await response.json()

if outcome.get('success', False): raise HTTPFound(r)

return Response(body="An error occured with turnstile")
else:
nonce = os.urandom(16).hex()

response = aiojinja.render_template("captcha.html", request, {
"nonce" : nonce,
"redirect" : r,
"request" : request,
"turnstile_site_key" : os.environ['TURNSTILE_SITE_KEY']
})
response.headers['Content-Security-Policy'] = f"script-src 'self' 'nonce-{nonce}';"

return response


@aiojinja.template('index.html')
async def index(self, request : Request):
return { "request" : request}
Expand Down
Empty file.
19 changes: 19 additions & 0 deletions src/commands/web/public/templates/captcha.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{% extends 'template.html' %}

{% block title %}GGsBot | Captcha {% endblock title %}

{% block style %}
<link rel="stylesheet" href="/static/css/captcha.css">
{% endblock style %}

{% block script %}
<script nonce="{{nonce}}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{% endblock script %}

{% block content %}
<h1>Please complete the CAPTCHA</h1>
<form method="POST" action="/captcha?r={{redirect}}">
<div class="cf-turnstile" data-sitekey="{{turnstile_site_key}}" data-theme="dark"></div>
<button type="submit">Submit</button>
</form>
{% endblock content %}
Loading