Skip to content

Commit 5d190ff

Browse files
authored
Merge pull request #15 from vcjuliocesar/refactor/feature
refactor
2 parents cbb8bab + 93dec52 commit 5d190ff

File tree

17 files changed

+130
-31
lines changed

17 files changed

+130
-31
lines changed

.env.example

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#Enviroment
2+
#ENVIROMENT=production
3+
ENVIROMENT=development
4+
5+
#Auth
6+
TOKEN_EXPIRE_MINUTES=3600
7+
MY_SECRET_KEY=bb635b7c649162d4623307e6633dfb595437bd7cefe86cc63349156cc52b212c
8+
9+
#Database
10+
DB_NAME=root
11+
DB_USER=root
12+
DB_PASS=6UF4Kie7tzLSeThX78tqBUuptI1th8T6
13+
DB_HOST=localhost
14+
DB_PORT=5432
15+

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ Follow these steps to set up and run the project on your local machine:
1212
```sh
1313
git clone git@github.com:vcjuliocesar/pynotes-api.git
1414
```
15-
rename env.example by .env
15+
**Create enviroment file**
16+
rename .env.example by .env
1617

1718
**Create a Virtual Environment:**
1819
```sh

config/config.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,17 @@
44
settings = Settings()
55

66
class ProductionConfig:
7+
78
DATABASE_URI = f"postgresql://{settings.DB_USER}:{settings.DB_PASS}@{settings.DB_HOST}/{settings.DB_NAME}"
9+
810
DEBUG = False
911

1012
class DevelopmentConfig:
13+
1114
sqlite_file_name = "../database.sqlite"
1215

1316
base_dir = os.path.dirname(os.path.realpath(__file__))
1417

1518
DATABASE_URI = f"sqlite:///{os.path.join(base_dir,sqlite_file_name)}"
19+
1620
DEBUG = True

config/database.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import os
21
from sqlalchemy import create_engine
32
from sqlalchemy.orm.session import sessionmaker
43
from sqlalchemy.ext.declarative import declarative_base
@@ -8,11 +7,13 @@
87
settings = Settings()
98

109
if settings.ENVIROMENT == "production":
10+
1111
conf = ProductionConfig
1212

1313
database_url = conf.DATABASE_URI
1414

1515
else:
16+
1617
conf = DevelopmentConfig
1718

1819
database_url = conf.DATABASE_URI

env.example

Lines changed: 0 additions & 14 deletions
This file was deleted.

main.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
from fastapi import FastAPI,HTTPException,status
2-
from fastapi.security import HTTPBearer
3-
from utils.jwt_manager import validate_token
4-
from starlette.requests import Request
1+
from fastapi import FastAPI
52
from config.database import engine,Base
63
from middlewares.error_handler import ErrorHandler
74
from config.config import ProductionConfig,DevelopmentConfig

middlewares/error_handler.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,15 @@
66
from starlette.responses import Response
77

88
class ErrorHandler(BaseHTTPMiddleware):
9+
910
def __init__(self, app: FastAPI) -> None:
1011
super().__init__(app)
1112

1213
async def dispatch(self, request: Request, call_next) -> Response | JSONResponse:
1314
try:
15+
1416
return await call_next(request)
17+
1518
except Exception as error:
19+
1620
return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,content={"error":str(error)})

middlewares/jwt_bearer.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,34 @@
44
from starlette.requests import Request
55
from services.user import UserService
66
from config.database import Session
7-
from datetime import datetime,timedelta
7+
from datetime import datetime
88

99
class JWTBearer(HTTPBearer):
10+
1011
async def __call__(self, request: Request):
12+
1113
credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Ivalid Credentials")
14+
1215
db = Session()
16+
1317
auth = await super().__call__(request)
18+
1419
data = validate_token(auth.credentials)
20+
1521
expire = datetime.fromtimestamp(data['exp'])
22+
1623
user = UserService(db).get_user_by_email(email=data["email"])
1724

1825
if not user:
26+
1927
raise credentials_exception
2028

2129
if expire is None:
30+
2231
raise credentials_exception
2332

2433
if datetime.utcnow() > expire:
34+
2535
raise credentials_exception
2636

2737
return user

models/note.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ class Note(Base):
77
__tablename__ = "notes"
88

99
id = Column(Integer,primary_key=True)
10+
1011
title = Column(String)
12+
1113
content = Column(String)
14+
1215
owner_id = Column(Integer,ForeignKey("users.id"))
1316

1417
owner = relationship("User",back_populates="notes")

models/user.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ class User(Base):
77
__tablename__ = "users"
88

99
id = Column(Integer,primary_key=True)
10+
1011
email = Column(String,unique=True)
12+
1113
password = Column(String)
14+
1215
is_active = Column(Boolean,default=True)
1316

1417
notes = relationship("Note",back_populates="owner")

0 commit comments

Comments
 (0)