Skip to content

Commit f7393bf

Browse files
committed
Замена libs и создание класса PWD в Security
Удалил passlib, теперь использую bcrypt и специально для него создал класс PWD Заменил python-jose на pyjwt
1 parent 21ac5c4 commit f7393bf

File tree

12 files changed

+271
-322
lines changed

12 files changed

+271
-322
lines changed

app/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
root_path=settings.APP_PATH,
1313
version=settings.APP_VERSION,
1414
contact={
15-
"name": "Fast Code",
16-
"url": "https://fast-code.pro/",
17-
"email": "fast.code.auth@gmail.com",
15+
'name': 'Fast Code',
16+
'url': 'https://fast-code.pro/',
17+
'email': 'fast.code.auth@gmail.com',
1818
},
1919
)
2020

app/api/endpoints/users/auth.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
from fastapi import APIRouter
22

33
from app.api import anotations
4-
from app.core import deps, exps
4+
from app.core import exps
55
from app.models.token import AccessToken
66
from app.models.user import UserCreate
77

8-
router = APIRouter(prefix="/auth")
8+
router = APIRouter(prefix='/auth')
99

1010

11-
@router.post("/token/", response_model=AccessToken)
11+
@router.post('/token/', response_model=AccessToken)
1212
async def token(
1313
data: UserCreate, db: anotations.Database, security: anotations.Security
1414
):
1515
"""
1616
Retrieve new access token
1717
"""
1818
if user := await db.user.retrieve_by_email(data.email):
19-
if not deps.pwd_context.verify(data.password, user.password):
19+
if not security.pwd.checkpwd(data.password, user.password):
2020
raise exps.USER_IS_CORRECT
21-
access_token = security.jwt.encode_token({"id": user.id}, 1440)
21+
access_token = security.jwt.encode_token({'id': user.id}, 1440)
2222
return AccessToken(token=access_token)
2323

2424
raise exps.USER_NOT_FOUND

app/api/endpoints/users/create.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
11
from fastapi import APIRouter
22

33
from app.api import anotations
4-
from app.core import deps, exps
4+
from app.core import exps
55
from app.models.user import User, UserCreate, UserRead
66

7-
router = APIRouter(prefix="/create")
7+
router = APIRouter(prefix='/create')
88

99

10-
@router.post("/", response_model=UserRead)
10+
@router.post('/', response_model=UserRead)
1111
async def registration(
12-
data: UserCreate,
13-
db: anotations.Database,
12+
data: UserCreate, db: anotations.Database, security: anotations.Security
1413
):
1514
"""
1615
Create user
1716
"""
1817
if await db.user.retrieve_by_email(data.email):
1918
raise exps.USER_EXISTS
2019

21-
password_hash = deps.pwd_context.hash(data.password)
20+
password_hash = security.pwd.hashpwd(data.password)
2221
model = User(email=data.email, password=password_hash)
2322
user = await db.user.create(model)
2423
return user

app/core/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44

55
from .security import Security
66

7-
__all__ = ["Security"]
7+
__all__ = ['Security']

app/core/db.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
Database
33
"""
44

5-
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
5+
from sqlalchemy.ext.asyncio import (AsyncEngine, async_sessionmaker,
6+
create_async_engine)
67
from sqlmodel.ext.asyncio.session import AsyncSession
78

89
from app import repositories as repos

app/core/deps.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,12 @@
44

55
from fastapi import Depends
66
from fastapi.security import APIKeyHeader
7-
from passlib.context import CryptContext
87
from typing_extensions import Annotated, AsyncGenerator
98

109
from app.models.user import User
1110

1211
from . import Security, db, exps
1312

14-
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')
15-
1613

1714
async def get_db() -> AsyncGenerator[db.Database]:
1815
async with db.SessionLocal() as session:

app/core/exps.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
USER_EXISTS = HTTPException(status.HTTP_409_CONFLICT, 'User is already taken.')
99
USER_NOT_FOUND = HTTPException(status.HTTP_404_NOT_FOUND, 'User not found.')
1010
USER_IS_CORRECT = HTTPException(
11-
status.HTTP_401_UNAUTHORIZED, 'Authorization failed. Please try again'
11+
status.HTTP_401_UNAUTHORIZED, 'User is correct'
1212
)
1313

1414
# Tokens

app/core/security/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
from app.core.settings import settings
22

33
from .jwt import JWT
4+
from .pwd import PWD
45

56

67
class Security:
78
def __init__(self):
89
self.jwt = JWT(settings.APP_SECRET_KEY)
10+
self.pwd = PWD()
911

1012

11-
__all__ = ["Security"]
13+
__all__ = ['Security']

app/core/security/jwt.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import datetime as dt
22

3-
from jose import JWTError, jwt
4-
from jose.constants import ALGORITHMS
3+
import jwt
4+
from jwt import PyJWTError
55

66
from app.core import exps
77

@@ -12,10 +12,8 @@ def __init__(self, secret_key: str):
1212

1313
def decode_token(self, token: str) -> dict | None:
1414
try:
15-
payload = jwt.decode(
16-
token, self.secret_key, algorithms=[ALGORITHMS.HS256]
17-
)
18-
except JWTError:
15+
payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
16+
except PyJWTError:
1917
raise exps.TOKEN_INVALID
2018

2119
exp = payload.get('exp')
@@ -28,4 +26,4 @@ def encode_token(self, payload: dict, minutes: int) -> str:
2826
'payload': payload,
2927
'exp': dt.datetime.now(dt.UTC) + dt.timedelta(minutes=minutes),
3028
}
31-
return jwt.encode(claims, self.secret_key, algorithm=ALGORITHMS.HS256)
29+
return jwt.encode(claims, self.secret_key, algorithm='HS256')

app/core/security/pwd.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import bcrypt
2+
3+
4+
class PWD:
5+
def hashpwd(self, password: str) -> str:
6+
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
7+
8+
def checkpwd(self, password: str, hashed_password: str) -> bool:
9+
return bcrypt.checkpw(password.encode(), hashed_password.encode())

0 commit comments

Comments
 (0)