-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement forgot/reset password endpoints (#90)
**Implementation:** * add smtp4dev and mail server env vars * add fastapi-mail * add forgot_password and reset_password routes * add fastapi-mail configuration class and templates * create crud function for reset_password * refactor forgot and reset password * implement user_reset_password crud * create basic test for forgot password * Format code with black * Solve some pylint warnings * Move up pylint comment * Remove old TODO comments * Solve pylint warnings * Add docstring to function * Make message more informative * Fix error in raising exeption * Apply black formatting **Tests:** * Get access token in email and redefine password * Fix generator type annotation syntax * Fix imap hostname in docker network for test * Fix host in IMAP connection * Apply black formatter * Test to make sure the password has changed * Fix spelling --------- Co-authored-by: Augusto Herrmann <[email protected]>
- Loading branch information
1 parent
d7f634b
commit f52693a
Showing
7 changed files
with
401 additions
and
71 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,7 +20,6 @@ services: | |
|
||
api-pgd: | ||
image: ghcr.io/gestaogovbr/api-pgd:latest | ||
pull_policy: always | ||
container_name: api-pgd | ||
depends_on: | ||
db: | ||
|
@@ -40,8 +39,24 @@ services: | |
# to new `SECRET` run openssl rand -hex 32 | ||
SECRET: b8a3054ba3457614e95a88cc0807384430c1b338a54e95e4245f41e060da68bc | ||
ACCESS_TOKEN_EXPIRE_MINUTES: 30 | ||
MAIL_USERNAME: '' | ||
MAIL_FROM: [email protected] | ||
MAIL_PORT: 25 | ||
MAIL_SERVER: smtp4dev | ||
MAIL_FROM_NAME: [email protected] | ||
MAIL_PASSWORD: '' | ||
healthcheck: | ||
test: ["CMD", "curl", "-f", "http://0.0.0.0:5057/docs"] | ||
interval: 5s | ||
timeout: 5s | ||
retries: 20 | ||
|
||
smtp4dev: | ||
image: rnwood/smtp4dev:v3 | ||
restart: always | ||
ports: | ||
- '5000:80' | ||
- '25:25' # Change the number before : to the port the SMTP server should be accessible on | ||
- '143:143' # Change the number before : to the port the IMAP server should be accessible on | ||
environment: | ||
- ServerOptions__HostName=smtp4dev |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,3 +8,4 @@ httpx==0.24.1 | |
python-jose[cryptography]==3.3.0 | ||
passlib[bcrypt]==1.7.4 | ||
python-multipart==0.0.6 | ||
fastapi-mail==1.4.1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import os | ||
import logging | ||
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType | ||
from fastapi_mail.errors import DBProvaiderError, ConnectionErrors, ApiError | ||
from starlette.responses import JSONResponse | ||
|
||
conf = ConnectionConfig( | ||
MAIL_USERNAME=os.environ["MAIL_USERNAME"], | ||
MAIL_FROM=os.environ["MAIL_FROM"], | ||
MAIL_PORT=os.environ["MAIL_PORT"], | ||
MAIL_SERVER=os.environ["MAIL_SERVER"], | ||
MAIL_FROM_NAME=os.environ["MAIL_FROM_NAME"], | ||
MAIL_STARTTLS=False, | ||
MAIL_SSL_TLS=False, | ||
MAIL_PASSWORD=os.environ["MAIL_PASSWORD"], | ||
USE_CREDENTIALS=False, | ||
VALIDATE_CERTS=False | ||
) | ||
|
||
async def send_reset_password_mail(email: str, | ||
token: str, | ||
) -> JSONResponse: | ||
"""Envia o e-mail contendo token para redefinir a senha. | ||
Args: | ||
email (str): o email do usuário. | ||
token (str): o token para redefinir a senha. | ||
Raises: | ||
e: exceção gerada pelo FastAPI Mail. | ||
Returns: | ||
JSONResponse: resposta retornada para o endpoint. | ||
""" | ||
token_expiration_minutes = os.environ["ACCESS_TOKEN_EXPIRE_MINUTES"] | ||
body = f""" | ||
<html> | ||
<body> | ||
<h3>Recuperação de acesso</h3> | ||
<p>Olá, {email}.</p> | ||
<p>Foi solicitada a recuperação de sua senha da API PGD. | ||
Caso essa solicitação não tenha sido feita por você, por | ||
favor ignore esta mensagem.</p> | ||
<p>Foi gerado o seguinte token para geração de uma nova | ||
senha.</p> | ||
<dl> | ||
<dt>Token</dt> | ||
<dd><code>{token}</code></dd> | ||
<dt>Prazo de validade</dt> | ||
<dd>{token_expiration_minutes} minutos</dd> | ||
</dl> | ||
<p>Utilize o endpoint <code>/user/reset_password</code> com | ||
este token para redefinir a senha.</p> | ||
</body> | ||
</html> | ||
""" | ||
try: | ||
message = MessageSchema( | ||
subject="Recuperação de acesso", | ||
recipients=[email], | ||
body=body, | ||
subtype=MessageType.html | ||
) | ||
fm = FastMail(conf) | ||
await fm.send_message(message) | ||
return JSONResponse(status_code=200, content={"message": "Email enviado!"}) | ||
except (DBProvaiderError, ConnectionErrors, ApiError) as e: | ||
logging.error("Erro ao enviar o email %e", e) | ||
raise e |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.