add integration

This commit is contained in:
2025-08-06 18:46:21 -03:00
parent e08f16bbaa
commit ff25ade76e
16 changed files with 314 additions and 132 deletions

View File

@@ -1,33 +1,84 @@
from uuid import uuid4
from http import HTTPStatus
from http.cookies import SimpleCookie
from urllib.parse import ParseResult, quote, urlencode, urlunparse
from authlib.oauth2 import OAuth2Error
from authlib.oauth2.rfc6749 import errors
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import Response
from aws_lambda_powertools.event_handler.api_gateway import Router
from jose_ import verify_jwt
from oauth2 import authorization
router = Router()
logger = Logger(__name__)
@router.get('/authorize')
def authorize():
user = {
'id': str(uuid4()),
'sub': 'sergio@somosbeta.com.br',
}
current_event = router.current_event
cookies = _parse_cookies(current_event.get('cookies', [])) # type: ignore
id_token = cookies.get('id_token')
continue_url = quote(
urlunparse(
ParseResult(
scheme='',
netloc='',
path=current_event.path,
params='',
query=urlencode(current_event.query_string_parameters),
fragment='',
)
),
safe='',
)
login_url = f'/login?continue={continue_url}'
if not id_token:
return Response(
status_code=HTTPStatus.FOUND,
headers={'Location': login_url},
)
try:
user = verify_jwt(id_token)
except Exception as exc:
logger.exception(exc)
return Response(
status_code=HTTPStatus.FOUND,
headers={'Location': login_url},
)
try:
grant = authorization.get_consent_grant(
request=router.current_event,
end_user=user,
end_user={'id': user['sub']},
)
except OAuth2Error as err:
logger.exception(err)
return dict(err.get_body())
try:
return authorization.create_authorization_response(
request=router.current_event,
grant_user=user,
grant_user={'id': user['sub']},
grant=grant,
)
except errors.OAuth2Error:
except errors.OAuth2Error as err:
logger.exception(err)
return {}
def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
parsed_cookies = {}
if not cookies:
return parsed_cookies
for s in cookies:
c = SimpleCookie()
c.load(s)
parsed_cookies.update({k: morsel.value for k, morsel in c.items()})
return parsed_cookies

View File

@@ -1,62 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>
<body
class="font-sans antialiased bg-black text-white flex items-center justify-center min-h-screen"
>
<div class="w-full max-w-sm relative">
<div
aria-hidden="true"
class="absolute inset-0 grid grid-cols-2 opacity-20"
>
<div
class="blur-[106px] h-56 bg-gradient-to-br to-lime-400 from-lime-700"
></div>
<div
class="blur-[106px] h-42 bg-gradient-to-r from-lime-400 to-lime-600"
></div>
</div>
<form method="POST" action="/login" class="space-y-6 relative z-1">
<div class="grid gap-2">
<label for="username" class="text-sm leading-none font-medium">
Email ou CPF
</label>
<input
type="text"
id="username"
name="username"
class="border border-white/15 bg-white/8 w-full rounded-lg px-3 py-1.5 shadow-sm outline-none focus-visible:border-white/30 focus-visible:ring-white/20 focus-visible:ring-3 transition"
required
/>
</div>
<div class="grid gap-2">
<div class="flex justify-between items-center">
<label for="password" class="text-sm leading-none font-medium">
Senha
</label>
<a href="#" class="text-sm" tabindex="-1">Esqueceu sua senha?</a>
</div>
<input
type="password"
id="password"
name="password"
class="border border-white/15 bg-white/8 w-full rounded-lg px-3 py-1.5 shadow-sm outline-none focus-visible:border-white/30 focus-visible:ring-white/20 focus-visible:ring-3 transition"
required
/>
</div>
<button
type="submit"
class="w-full text-sm font-medium text-black bg-lime-400 rounded-lg px-4 py-2 h-9"
>
Entrar
</button>
</form>
</div>
</body>
</html>

View File

@@ -1,5 +1,4 @@
from http import HTTPStatus
from pathlib import Path
from typing import Annotated
from aws_lambda_powertools.event_handler import (
@@ -7,8 +6,9 @@ from aws_lambda_powertools.event_handler import (
)
from aws_lambda_powertools.event_handler.api_gateway import Router
from aws_lambda_powertools.event_handler.exceptions import ForbiddenError, NotFoundError
from aws_lambda_powertools.event_handler.openapi.params import Form
from aws_lambda_powertools.event_handler.openapi.params import Form, Param
from aws_lambda_powertools.shared.cookies import Cookie
from jinja2 import Environment, PackageLoader, select_autoescape
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
from passlib.hash import pbkdf2_sha256
@@ -18,15 +18,20 @@ from jose_ import generate_jwt
router = Router()
oauth2_layer = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
templates = Environment(
loader=PackageLoader('app'),
autoescape=select_autoescape(['html']),
)
@router.get('/login')
def login_form():
html = Path(__file__).with_name('login.html').read_text(encoding='utf-8')
@router.get('/login', compress=True)
def login_form(continue_: Annotated[str, Param(alias='continue')]):
template = templates.get_template('login.html')
html = template.render(**{'continue': continue_})
return Response(
body=html,
status_code=HTTPStatus.OK.value,
status_code=HTTPStatus.OK,
content_type='text/html',
)
@@ -35,6 +40,7 @@ def login_form():
def login(
username: Annotated[str, Form()],
password: Annotated[str, Form()],
continue_: Annotated[str, Form(alias='continue')],
):
user_id, password_hash = _get_user(username)
@@ -44,7 +50,10 @@ def login(
jwt_token = generate_jwt(user_id, username)
return Response(
status_code=HTTPStatus.OK,
status_code=HTTPStatus.FOUND,
headers={
'Location': continue_,
},
cookies=[
Cookie(
name='id_token',