add session route

This commit is contained in:
2025-08-16 23:53:09 -03:00
parent a53f37393a
commit 21f6eb030f
21 changed files with 311 additions and 599 deletions

View File

@@ -9,15 +9,15 @@ from aws_lambda_powertools.utilities.typing import LambdaContext
from routes.authorize import router as authorize
from routes.jwks import router as jwks
from routes.login import router as login
from routes.openid_configuration import router as openid_configuration
from routes.session import router as session
from routes.token import router as token
from routes.userinfo import router as userinfo
logger = Logger(__name__)
tracer = Tracer()
app = APIGatewayHttpResolver(enable_validation=True)
app.include_router(login)
app.include_router(session)
app.include_router(authorize)
app.include_router(jwks)
app.include_router(token)

View File

@@ -1,52 +0,0 @@
from datetime import timedelta
from aws_lambda_powertools.event_handler.exceptions import ForbiddenError
from jose import jwt
from layercake.dateutils import now
from config import (
ISSUER,
JWT_ALGORITHM,
JWT_EXP_SECONDS,
JWT_SECRET,
OAUTH2_REFRESH_TOKEN_EXPIRES_IN,
)
def generate_jwt(user_id: str, email: str) -> str:
now_ = now()
payload = {
'sub': user_id,
'email': email,
'iat': int(now_.timestamp()),
'exp': int((now_ + timedelta(seconds=JWT_EXP_SECONDS)).timestamp()),
'iss': ISSUER,
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def generate_refresh_token(user_id: str) -> str:
now_ = now()
exp = now_ + timedelta(seconds=OAUTH2_REFRESH_TOKEN_EXPIRES_IN)
payload = {
'sub': user_id,
'iat': int(now_.timestamp()),
'exp': int(exp.timestamp()),
'iss': ISSUER,
'typ': 'refresh',
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def verify_jwt(token: str) -> dict:
payload = jwt.decode(
token,
JWT_SECRET,
algorithms=[JWT_ALGORITHM],
issuer=ISSUER,
options={
'require': ['exp', 'sub', 'iss'],
'leeway': 60,
},
)
return payload

View File

@@ -1,49 +1,40 @@
from http import HTTPStatus
from http.cookies import SimpleCookie
from urllib.parse import ParseResult, quote, urlencode, urlunparse
import jwt
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.exceptions import JWTError
from aws_lambda_powertools.event_handler.exceptions import BadRequestError
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
from jose_ import verify_jwt
from boto3clients import dynamodb_client
from config import ISSUER, JWT_ALGORITHM, JWT_SECRET, OAUTH2_TABLE
from oauth2 import server
router = Router()
logger = Logger(__name__)
oauth2_layer = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
@router.get('/authorize')
def authorize():
current_event = router.current_event
cookies = _parse_cookies(current_event.get('cookies', []))
id_token = cookies.get('id_token')
continue_url = _build_continue_url(
current_event.path,
current_event.query_string_parameters,
)
session_id = cookies.get('session_id')
login_url = f'/login?continue={continue_url}'
try:
if not id_token:
raise ValueError('Missing id_token')
user = verify_jwt(id_token)
except (ValueError, JWTError):
return Response(
status_code=HTTPStatus.FOUND,
headers={'Location': login_url},
)
if not session_id:
raise BadRequestError('Missing session_id')
try:
user_id = verify_session(session_id)
grant = server.get_consent_grant(
request=router.current_event,
end_user={'id': user['sub']},
end_user={'id': user_id},
)
except jwt.exceptions.InvalidTokenError as err:
logger.exception(err)
raise BadRequestError(str(err))
except OAuth2Error as err:
logger.exception(err)
return dict(err.get_body())
@@ -51,7 +42,7 @@ def authorize():
try:
return server.create_authorization_response(
request=router.current_event,
grant_user={'id': user['sub']},
grant_user={'id': user_id},
grant=grant,
)
except errors.OAuth2Error as err:
@@ -59,6 +50,29 @@ def authorize():
return {}
def verify_session(session_id: str) -> str:
payload = jwt.decode(
session_id,
JWT_SECRET,
algorithms=[JWT_ALGORITHM],
issuer=ISSUER,
options={
'require': ['exp', 'sub', 'iss', 'sid'],
'leeway': 60,
},
)
oauth2_layer.collection.get_item(
KeyPair(
pk='SESSION',
sk=payload['sid'],
),
exc_cls=SessionRevokedError,
)
return payload['sub']
def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
parsed_cookies = {}
@@ -73,9 +87,6 @@ def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
return parsed_cookies
def _build_continue_url(
path: str,
query_string_parameters: dict,
) -> str:
query = urlencode(query_string_parameters)
return quote(urlunparse(ParseResult('', '', path, '', query, '')), safe='')
class SessionRevokedError(BadRequestError):
def __init__(self, *_):
super().__init__('Session revoked')

View File

@@ -1,91 +0,0 @@
from http import HTTPStatus
from typing import Annotated
from aws_lambda_powertools.event_handler import (
Response,
)
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, 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
from boto3clients import dynamodb_client
from config import OAUTH2_TABLE
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', 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,
content_type='text/html',
)
@router.post('/login')
def login(
username: Annotated[str, Form()],
password: Annotated[str, Form()],
continue_: Annotated[str, Form(alias='continue')],
):
user_id, password_hash = _get_user(username)
if not pbkdf2_sha256.verify(password, password_hash):
raise ForbiddenError('Invalid credentials')
jwt_token = generate_jwt(user_id, username)
return Response(
status_code=HTTPStatus.FOUND,
headers={
'Location': continue_,
},
cookies=[
Cookie(
name='id_token',
value=jwt_token,
http_only=True,
same_site=None,
),
],
)
def _get_user(username: str) -> tuple[str, str]:
r = oauth2_layer.collection.get_item(
# Post-migration: uncomment the following line
# KeyPair('EMAIL', username),
KeyPair('email', username),
exc_cls=EmailNotFoundError,
)
password = oauth2_layer.collection.get_item(
KeyPair(r['user_id'], 'PASSWORD'),
exc_cls=UserNotFoundError,
)
return r['user_id'], password['hash']
class EmailNotFoundError(NotFoundError):
def __init__(self, *_):
super().__init__('Email not found')
class UserNotFoundError(NotFoundError):
def __init__(self, *_):
super().__init__('User not found')

View File

@@ -0,0 +1,107 @@
from http import HTTPStatus
from typing import Annotated
from uuid import uuid4
import jwt
from aws_lambda_powertools.event_handler import (
Response,
)
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 Body
from aws_lambda_powertools.shared.cookies import Cookie
from layercake.dateutils import now, ttl
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey
from passlib.hash import pbkdf2_sha256
from boto3clients import dynamodb_client
from config import ISSUER, JWT_ALGORITHM, JWT_EXP_SECONDS, JWT_SECRET, OAUTH2_TABLE
router = Router()
oauth2_layer = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
@router.post('/session')
def session(
username: Annotated[str, Body()],
password: Annotated[str, Body()],
):
user_id, password_hash = _get_user(username)
if not pbkdf2_sha256.verify(password, password_hash):
raise ForbiddenError('Invalid credentials')
return Response(
status_code=HTTPStatus.FOUND,
cookies=[
Cookie(
name='session_id',
value=new_session(user_id),
http_only=True,
secure=True,
same_site=None,
)
],
)
def _get_user(username: str) -> tuple[str, str]:
sk = SortKey(username, path_spec='user_id')
user = oauth2_layer.collection.get_items(
KeyPair(pk='email', sk=sk, rename_key=sk.path_spec)
+ KeyPair(pk='cpf', sk=sk, rename_key=sk.path_spec),
flatten_top=False,
)
if not user:
raise UserNotFoundError()
password = oauth2_layer.collection.get_item(
KeyPair(user['user_id'], 'PASSWORD'),
exc_cls=UserNotFoundError,
)
return user['user_id'], password['hash']
def new_session(sub: str) -> str:
now_ = now()
sid = str(uuid4())
exp = ttl(start_dt=now_, seconds=JWT_EXP_SECONDS)
token = jwt.encode(
{
'sid': sid,
'sub': sub,
'iss': ISSUER,
'iat': int(now_.timestamp()),
'exp': exp,
},
JWT_SECRET,
algorithm=JWT_ALGORITHM,
)
with oauth2_layer.transact_writer() as transact:
transact.put(
item={
'id': 'SESSION',
'sk': sid,
'user_id': sub,
'ttl': exp,
'created_at': now_,
}
)
transact.put(
item={
'id': sub,
'sk': f'SESSION#{sid}',
'ttl': exp,
'created_at': now_,
}
)
return token
class UserNotFoundError(NotFoundError):
def __init__(self, *_):
super().__init__('User not found')

View File

@@ -1,115 +0,0 @@
<!doctype html>
<html>
<head>
<title>EDUSEG®</title>
<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 px-3"
>
<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>
<div class="grid gap-5 relative z-1">
<div class="text-center space-y-1">
<span
class="border border-white/15 bg-white/5 px-2.5 py-3 rounded-xl inline-block"
><svg
width="18"
height="24"
viewBox="0 0 18 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="size-12"
>
<path
d="M16.2756 23.4353L8.93847 20.1298C8.7383 20.0015 8.48167 20.0015 8.27893 20.1298L0.941837 23.4353C0.533793 23.6945 0 23.4019 0 22.9194V1.12629C0.00256631 0.787535 0.277162 0.512939 0.615915 0.512939H16.6066C16.9454 0.512939 17.22 0.787535 17.22 1.12629V22.9194C17.22 23.4019 16.6862 23.6945 16.2781 23.4353H16.2756Z"
fill="#8CD366"
></path>
<path
d="M10.7274 3.71313H3.34668V6.41803H10.7274V3.71313Z"
fill="#2E3524"
></path>
<path
d="M9.42115 8.4939H3.34668V10.6496H9.42115V8.4939Z"
fill="#2E3524"
></path>
<path
d="M10.7274 12.7263H3.34668V15.4312H10.7274V12.7263Z"
fill="#2E3524"
></path>
<path
d="M12.9984 13.6731H12.9958C12.5111 13.6731 12.1182 14.066 12.1182 14.5508V14.5533C12.1182 15.0381 12.5111 15.431 12.9958 15.431H12.9984C13.4831 15.431 13.8761 15.0381 13.8761 14.5533V14.5508C13.8761 14.066 13.4831 13.6731 12.9984 13.6731Z"
fill="#2E3524"
></path></svg
></span>
<h1 class="text-3xl mt-6 font-semibold font-display text-balance">
Faça login
</h1>
<p class="text-white/50 text-sm">
Não tem uma conta?
<a href="" class="font-medium text-white">Cadastre-se</a>.
</p>
</div>
<form method="POST" action="/login" class="space-y-6">
<input name="continue" type="hidden" value="{{ continue }}" />
<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-2.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-2.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>
<p class="text-xs text-white/50 text-center">
Ao fazer login, você concorda com nossa
<a href="#" class="underline hover:no-underline" target="_blank">
política de privacidade </a
>.
</p>
</div>
</div>
</body>
</html>