Skip to content

Commit f6096c7

Browse files
Merge pull request #8 from C216-Distribuid-System-Project/feat/MF-auth_register
Authentication Register Implementation
2 parents 5e94ea9 + 039c192 commit f6096c7

File tree

13 files changed

+376
-25
lines changed

13 files changed

+376
-25
lines changed
Lines changed: 60 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
# 📌 API Project Architecture
22

33
## Overview
4-
This document provides an initial explanation of the **API Project** architecture.
4+
This document provides an initial explanation of the **API Project Architecture**.
55
It covers the directory structure, the purpose of each folder and file, and how the project is organized.
6-
The goal is to ensure clarity and maintainability for developers working on the project.
6+
The goal is to ensure clarity and facilitate maintenance for developers working on the project.
77

8-
This backend is built using **FastAPI** and follows a modular structure to enhance scalability and maintainability.
9-
It includes schemas, routes, modules, and utility functions to provide a clear separation of concerns.
8+
This backend is built using **FastAPI** and follows a modular structure to improve scalability and maintainability.
9+
It includes schemas, routes, modules, and utility functions to ensure a clear separation of concerns.
1010

1111
---
1212

13-
## Index
13+
## Table of Contents
1414
- [Project Structure](#project-structure)
15-
- [Folder & File Descriptions](#folder--file-descriptions)
15+
- [Folders and Files Description](#folders-and-files-description)
16+
- [models](#models)
1617
- [modules](#modules)
1718
- [routes](#routes)
1819
- [schemas](#schemas)
@@ -29,13 +30,20 @@ graph TD;
2930
A1[main.py]
3031
A2[__init__.py]
3132
33+
subgraph models
34+
B1[__init__.py]
35+
B2[user_model.py]
36+
end
37+
3238
subgraph modules
3339
M1[__init__.py]
3440
M2[modules_api.py]
41+
M3[database_conection.py]
3542
end
3643
3744
subgraph routes
3845
R1[__init__.py]
46+
R2[authentication_routes.py]
3947
end
4048
4149
subgraph schemas
@@ -51,6 +59,11 @@ graph TD;
5159
subgraph users
5260
S5[__init__.py]
5361
S6[users_schema.py]
62+
subgraph CRUD
63+
C1[__init__.py]
64+
C2[create.py]
65+
C3[read.py]
66+
end
5467
end
5568
end
5669
@@ -63,51 +76,76 @@ graph TD;
6376

6477
---
6578

66-
## Folder & File Descriptions
79+
## Folders and Files Description
80+
81+
### `models/`
82+
Defines ORM models using SQLAlchemy.
83+
84+
- **`user_model.py`** → Contains the `User` class, representing the `users` table in the database, with columns such as `id`, `name`, `email`, `password_hash`, `birth_date`, `phone`, `created_at`, etc.
6785

6886
### `modules`
6987
Contains modular functionalities that extend the backend.
7088

71-
- **`modules_api.py`** → Defines reusable API components and logic.
72-
- **`__init__.py`** → Initializes the modules package.
89+
- **`database_conection.py`** → Responsible for configuring the MySQL database connection using `SQLAlchemy`, and creating the `engine`, `SessionLocal`, and `Base` instances.
90+
- **`modules_api.py`** → Defines reusable API components and logic.
91+
- **`__init__.py`** → Initializes the modules package.
7392

7493
---
7594

7695
### `routes`
77-
Defines all API endpoints for the application.
96+
Defines all API endpoints of the application.
7897

7998
- **`__init__.py`** → Initializes the routes module.
80-
(Additional route files will be added here as the project evolves.)
99+
- **`authentication_routes.py`**
100+
Contains the endpoints:
101+
- `POST /auth/register` → Registers a new user.
102+
- `POST /auth/login` → Authenticates and returns a JWT token.
81103

82104
---
83105

84106
### `schemas`
85107
Contains all **Pydantic schemas** used for validation and data modeling.
86108

109+
#### `users/`
110+
- **`users_schema.py`**
111+
Contains Pydantic models:
112+
- `UserCreate` (input data for registration)
113+
- `UserLogin` (input data for login)
114+
- `UserResponse` (API response)
115+
- Uses `from_attributes = True` for compatibility with SQLAlchemy (equivalent to the former `orm_mode = True`).
116+
117+
- **`CRUD/create.py`**
118+
Defines functions for:
119+
- `create_user()` → creates and persists a new user.
120+
- Uses `bcrypt` with `passlib` to hash passwords.
121+
122+
- **`CRUD/read.py`**
123+
Defines functions for:
124+
- `authenticate_user()` → validates email and password.
125+
- `get_user_by_email()` → retrieves a user by email.
126+
87127
#### `projects`
88-
- **`projects_schema.py`** → Defines schemas related to projects.
89-
- **`__init__.py`** → Initializes the projects schemas package.
128+
- **`projects_schema.py`** → Defines schemas related to projects.
129+
- **`__init__.py`** → Initializes the project schemas package.
90130

91131
#### `tasks`
92-
- **`tasks_schema.py`** → Defines schemas related to tasks.
93-
- **`__init__.py`** → Initializes the tasks schemas package.
132+
- **`tasks_schema.py`** → Defines schemas related to tasks.
133+
- **`__init__.py`** → Initializes the task schemas package.
94134

95135
#### `users`
96-
- **`users_schema.py`** → Defines schemas related to users.
97-
- **`__init__.py`** → Initializes the users schemas package.
136+
- **`users_schema.py`** → Defines schemas related to users.
137+
- **`__init__.py`** → Initializes the user schemas package.
98138

99139
---
100140

101141
### `utils`
102142
Contains helper functions and utility scripts.
103143

104-
- **`utils.py`** → General utility functions used across the project.
105-
- **`__init__.py`** → Initializes the utils package.
144+
- **`utils.py`** → General-purpose functions used in different parts of the project.
145+
- **`__init__.py`** → Initializes the utilities package.
106146

107147
---
108148

109149
### `main.py`
110150
The **entry point** of the application.
111-
Responsible for initializing FastAPI, including routes, modules, and configurations.
112-
113-
---
151+
Responsible for initializing FastAPI, including routes, modules, and configurations.

docs/pt-br/api_project_architecture.md

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Inclui schemas, rotas, módulos e funções utilitárias para garantir uma clara
1313
## Índice
1414
- [Estrutura do Projeto](#estrutura-do-projeto)
1515
- [Descrição das Pastas e Arquivos](#descrição-das-pastas-e-arquivos)
16+
- [models](#models)
1617
- [modules](#modules)
1718
- [routes](#routes)
1819
- [schemas](#schemas)
@@ -29,13 +30,20 @@ graph TD;
2930
A1[main.py]
3031
A2[__init__.py]
3132
33+
subgraph models
34+
B1[__init__.py]
35+
B2[user_model.py]
36+
end
37+
3238
subgraph modules
3339
M1[__init__.py]
3440
M2[modules_api.py]
41+
M3[database_conection.py]
3542
end
3643
3744
subgraph routes
3845
R1[__init__.py]
46+
R2[authentication_routes.py]
3947
end
4048
4149
subgraph schemas
@@ -51,6 +59,11 @@ graph TD;
5159
subgraph users
5260
S5[__init__.py]
5361
S6[users_schema.py]
62+
subgraph CRUD
63+
C1[__init__.py]
64+
C2[create.py]
65+
C3[read.py]
66+
end
5467
end
5568
end
5669
@@ -65,9 +78,15 @@ graph TD;
6578

6679
## Descrição das Pastas e Arquivos
6780

81+
### `models/`
82+
Define os modelos ORM com SQLAlchemy.
83+
84+
- **`user_model.py`** → Contém a classe `User`, que representa a tabela `users` no banco de dados, com colunas como `id`, `name`, `email`, `password_hash`, `birth_date`, `phone`, `created_at`, etc.
85+
6886
### `modules`
6987
Contém funcionalidades modulares que estendem o backend.
7088

89+
- **`database_conection.py`** → Responsável por configurar a conexão com o banco MySQL usando `SQLAlchemy`, e criar a instância `engine`, `SessionLocal`, e `Base`.
7190
- **`modules_api.py`** → Define componentes e lógicas de API reutilizáveis.
7291
- **`__init__.py`** → Inicializa o pacote de módulos.
7392

@@ -77,13 +96,34 @@ Contém funcionalidades modulares que estendem o backend.
7796
Define todos os endpoints da API da aplicação.
7897

7998
- **`__init__.py`** → Inicializa o módulo de rotas.
80-
(Arquivos adicionais de rotas serão adicionados aqui conforme o projeto evoluir.)
81-
99+
- **`authentication_routes.py`**
100+
Contém os endpoints de:
101+
- `POST /auth/register` → Cadastra novo usuário.
102+
- `POST /auth/login` → Autentica e retorna o token JWT.
103+
82104
---
83105

84106
### `schemas`
85107
Contém todos os **schemas do Pydantic** usados para validação e modelagem de dados.
86108

109+
#### `users/`
110+
- **`users_schema.py`**
111+
Contém os modelos Pydantic:
112+
- `UserCreate` (entrada de dados no cadastro)
113+
- `UserLogin` (entrada de dados no login)
114+
- `UserResponse` (resposta da API)
115+
- Usa `from_attributes = True` para compatibilidade com SQLAlchemy (equivalente ao antigo `orm_mode = True`).
116+
117+
- **`CRUD/create.py`**
118+
Define as funções de:
119+
- `create_user()` → cria e persiste novo usuário.
120+
- Usa `bcrypt` com `passlib` para hashear senhas.
121+
122+
- **`CRUD/read.py`**
123+
Define as funções de:
124+
- `authenticate_user()` → valida email e senha.
125+
- `get_user_by_email()` → busca usuário por email.
126+
87127
#### `projects`
88128
- **`projects_schema.py`** → Define os schemas relacionados a projetos.
89129
- **`__init__.py`** → Inicializa o pacote de schemas de projetos.

requirements.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
annotated-types==0.7.0
22
anyio==4.10.0
33
certifi==2025.8.3
4+
cffi==2.0.0
45
click==8.1.8
56
colorama==0.4.6
7+
cryptography==46.0.1
68
dnspython==2.7.0
79
email-validator==2.3.0
810
exceptiongroup==1.3.0
911
fastapi==0.117.1
1012
fastapi-cli==0.0.13
1113
fastapi-cloud-cli==0.2.0
14+
greenlet==3.2.4
1215
h11==0.16.0
1316
httpcore==1.0.9
1417
httptools==0.6.4
@@ -18,9 +21,12 @@ Jinja2==3.1.6
1821
markdown-it-py==3.0.0
1922
MarkupSafe==3.0.2
2023
mdurl==0.1.2
24+
passlib==1.7.4
25+
pycparser==2.23
2126
pydantic==2.11.9
2227
pydantic_core==2.33.2
2328
Pygments==2.19.2
29+
PyMySQL==1.1.2
2430
python-dotenv==1.1.1
2531
python-multipart==0.0.20
2632
PyYAML==6.0.2
@@ -30,6 +36,7 @@ rignore==0.6.4
3036
sentry-sdk==2.38.0
3137
shellingham==1.5.4
3238
sniffio==1.3.1
39+
SQLAlchemy==2.0.43
3340
starlette==0.48.0
3441
typer==0.19.1
3542
typing-inspection==0.4.1

src/models/__init__.py

Whitespace-only changes.

src/models/user_model.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from sqlalchemy import Column, Integer, String, Date, TIMESTAMP
2+
from sqlalchemy.sql import func
3+
from modules.database_conection import Base
4+
5+
class User(Base):
6+
"""
7+
Represents a user in the system.
8+
Attributes:
9+
id (int): Unique identifier for the user.
10+
name (str): Full name of the user.
11+
email (str): Email address of the user. Must be unique.
12+
phone (str, optional): Phone number of the user.
13+
birth_date (date, optional): Birth date of the user.
14+
password_hash (str): Hashed password for authentication.
15+
created_at (datetime): Timestamp when the user was created.
16+
updated_at (datetime): Timestamp when the user was last updated.
17+
"""
18+
__tablename__ = "users"
19+
20+
id = Column(Integer, primary_key=True, index=True)
21+
name = Column(String(255), nullable=False)
22+
email = Column(String(255), nullable=False, unique=True, index=True)
23+
phone = Column(String(20), nullable=True)
24+
birth_date = Column(Date, nullable=True)
25+
password_hash = Column(String(255), nullable=False)
26+
created_at = Column(TIMESTAMP, server_default=func.now(), nullable=False)
27+
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now(), nullable=False)

src/modules/database_conection.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from sqlalchemy import create_engine
2+
from sqlalchemy.ext.declarative import declarative_base
3+
from sqlalchemy.orm import sessionmaker
4+
import os
5+
6+
"""
7+
Database connection module using SQLAlchemy.
8+
9+
This module sets up the database connection configuration,
10+
including the creation of the engine, session, and declarative base for ORM models.
11+
The database URL is retrieved from the 'DATABASE_URL' environment variable.
12+
If not defined, a default MySQL connection string is used.
13+
14+
Attributes:
15+
DATABASE_URL (str): Database connection URL.
16+
engine (Engine): SQLAlchemy Engine instance connected to the database.
17+
SessionLocal (sessionmaker): Class for creating database sessions.
18+
Base (DeclarativeMeta): Base class for defining ORM models.
19+
"""
20+
21+
# Get the database URL from environment variable or use the default value
22+
DATABASE_URL = os.getenv("DATABASE_URL", "mysql+pymysql://app:app_pass@localhost:3307/todolist")
23+
24+
# Create the SQLAlchemy engine
25+
engine = create_engine(DATABASE_URL)
26+
27+
# Create a configured "Session" class
28+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
29+
30+
# Create a base class for ORM models
31+
Base = declarative_base()

src/modules/modules_api.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
from fastapi import APIRouter
2+
from routes.authentication_routes import authentication_router
23

34
# -------------------- API ROUTES -------------------- #
4-
router = APIRouter()
5+
router = APIRouter()
6+
7+
router.include_router(authentication_router)

0 commit comments

Comments
 (0)