-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from btambara/add-security-endpoints
Add security endpoints
- Loading branch information
Showing
23 changed files
with
475 additions
and
9 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
23 changes: 23 additions & 0 deletions
23
api/alembic/versions/fa7218c49f34_create_user_and_token_tables.py
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,23 @@ | ||
"""Create user and token tables | ||
Revision ID: fa7218c49f34 | ||
Revises: e5fa7cab21b2 | ||
Create Date: 2024-04-13 18:03:07.208993 | ||
""" | ||
|
||
from typing import Sequence, Union | ||
|
||
# revision identifiers, used by Alembic. | ||
revision: str = "fa7218c49f34" | ||
down_revision: Union[str, None] = "e5fa7cab21b2" | ||
branch_labels: Union[str, Sequence[str], None] = None | ||
depends_on: Union[str, Sequence[str], None] = None | ||
|
||
|
||
def upgrade() -> None: | ||
pass | ||
|
||
|
||
def downgrade() -> None: | ||
pass |
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
Empty file.
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,13 @@ | ||
from pydantic import BaseModel | ||
from sqlalchemy.orm import declarative_base | ||
|
||
Base = declarative_base() | ||
|
||
|
||
class Token(BaseModel): # type: ignore[misc] | ||
access_token: str | ||
token_type: str | ||
|
||
|
||
class TokenData(BaseModel): # type: ignore[misc] | ||
username: str |
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
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
Empty file.
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,72 @@ | ||
from datetime import datetime, timedelta, timezone | ||
from typing import Annotated, Dict, Literal | ||
|
||
import bcrypt | ||
from api.deps import get_db | ||
from auth_token.token_model import TokenData | ||
from fastapi import Depends, HTTPException, status | ||
from jose import JWTError, jwt | ||
from jose.constants import ALGORITHMS | ||
from security.oauth2 import oauth2_scheme | ||
from settings.config import Settings, get_settings | ||
from sqlalchemy.orm import Session | ||
from user.user_crud import get_user_by_email | ||
from user.user_model import User | ||
|
||
|
||
def verify_password(plain_password: str, hashed_password: str) -> bool: | ||
return bcrypt.checkpw(bytes(plain_password, "utf-8"), bytes(hashed_password, "utf-8")) # type: ignore[no-any-return] | ||
|
||
|
||
def authenticate_user(db: Session, email: str, password: str) -> User | Literal[False]: | ||
user = get_user_by_email(db, email) | ||
if not user: | ||
return False | ||
if not verify_password(password, user.password): | ||
return False | ||
return user | ||
|
||
|
||
def create_access_token( | ||
data: Dict[str, str | datetime], | ||
secret_key: str, | ||
algorithm: str = ALGORITHMS.HS256, | ||
expires_delta: timedelta | None = None, | ||
) -> str: | ||
to_encode = data.copy() | ||
if expires_delta: | ||
expire = datetime.now(timezone.utc) + expires_delta | ||
else: | ||
expire = datetime.now(timezone.utc) + timedelta(minutes=15) | ||
to_encode.update({"exp": expire}) | ||
encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=algorithm) | ||
return encoded_jwt # type: ignore[no-any-return] | ||
|
||
|
||
ret_key: str | ||
|
||
|
||
async def get_current_user( | ||
settings: Annotated[Settings, Depends(get_settings)], | ||
token: Annotated[str, Depends(oauth2_scheme)], | ||
db: Session = Depends(get_db), | ||
) -> User: | ||
credentials_exception = HTTPException( | ||
status_code=status.HTTP_401_UNAUTHORIZED, | ||
detail="Could not validate credentials", | ||
headers={"WWW-Authenticate": "Bearer"}, | ||
) | ||
try: | ||
payload = jwt.decode( | ||
token, settings.secret_key, algorithms=[settings.algorithm] | ||
) | ||
username: str = payload.get("sub") | ||
if username is None: | ||
raise credentials_exception | ||
token_data = TokenData(username=username) | ||
except JWTError: | ||
raise credentials_exception | ||
user = get_user_by_email(db, token_data.username) | ||
if user is None: | ||
raise credentials_exception | ||
return user |
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,3 @@ | ||
from fastapi.security import OAuth2PasswordBearer | ||
|
||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/authenticate/token") |
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 |
---|---|---|
@@ -1,13 +1,58 @@ | ||
from typing import Any, Generator | ||
|
||
import pytest | ||
from auth_token.token_model import Token | ||
from fastapi.testclient import TestClient | ||
from httpx import Headers | ||
from main import app | ||
from settings.config import get_settings, get_settings_override | ||
from user.user_model import User | ||
|
||
test_user_info = {"email": "test@testing.com", "password": "password"} | ||
|
||
|
||
@pytest.fixture # type: ignore[misc] | ||
def test_client() -> Generator[TestClient, Any, None]: | ||
app.dependency_overrides[get_settings] = get_settings_override | ||
client = TestClient(app) | ||
yield client | ||
|
||
|
||
@pytest.fixture # type: ignore[misc] | ||
def get_test_user(test_client: TestClient) -> User: | ||
response = test_client.get("/api/v1/authenticate/email/" + test_user_info["email"]) | ||
|
||
if response.status_code == 404: | ||
response = test_client.post( | ||
"/api/v1/authenticate", | ||
json={ | ||
"email": test_user_info["email"], | ||
"password": test_user_info["password"], | ||
}, | ||
) | ||
|
||
response_json = response.json() | ||
|
||
return User(email=response_json["email"], password=response_json["password"]) | ||
|
||
|
||
@pytest.fixture # type: ignore[misc] | ||
def get_test_user_token(get_test_user: User, test_client: TestClient) -> Token: | ||
headers = Headers({"Content-Type": "application/x-www-form-urlencoded"}) | ||
data = { | ||
"grant_type": "", | ||
"username": get_test_user.email, | ||
"password": test_user_info["password"], | ||
"scope": "", | ||
"client_id": "", | ||
"client_secret": "", | ||
} | ||
response = test_client.post( | ||
"/api/v1/authenticate/token", data=data, headers=headers | ||
) | ||
response_json = response.json() | ||
|
||
return Token( | ||
access_token=response_json["access_token"], | ||
token_type=response_json["token_type"], | ||
) |
Oops, something went wrong.