Skip to content

Commit

Permalink
wip. working tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Leobouloc committed Oct 24, 2023
1 parent e0c13ba commit bb2c356
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 39 deletions.
31 changes: 6 additions & 25 deletions src/ralph/api/auth/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import bcrypt
from cachetools import TTLCache, cached
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials, SecurityScopes
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel, root_validator
from starlette.authentication import AuthenticationError

Expand Down Expand Up @@ -102,17 +102,15 @@ def get_stored_credentials(auth_file: Path) -> ServerUsersCredentials:
@cached(
TTLCache(maxsize=settings.AUTH_CACHE_MAX_SIZE, ttl=settings.AUTH_CACHE_TTL),
lock=Lock(),
key=lambda credentials, security_scopes: (
key=lambda credentials: (
credentials.username,
credentials.password,
security_scopes.scope_str,
)
if credentials is not None
else None,
)
def get_basic_auth_user(
credentials: Union[HTTPBasicCredentials, None] = Depends(security),
security_scopes: SecurityScopes = SecurityScopes([]),
credentials: Union[HTTPBasicCredentials, None] = Depends(security)
) -> AuthenticatedUser:
"""Checks valid auth parameters.
Expand All @@ -121,7 +119,6 @@ def get_basic_auth_user(
Args:
credentials (iterator): auth parameters from the Authorization header
security_scopes: scopes requested for access
Raises:
HTTPException
Expand Down Expand Up @@ -152,6 +149,7 @@ def get_basic_auth_user(
)
hashed_password = None
except AuthenticationError as exc:
return None
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
Expand All @@ -163,11 +161,7 @@ def get_basic_auth_user(
bcrypt.checkpw(
credentials.password.encode(settings.LOCALE_ENCODING), UNUSED_PASSWORD
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Basic"},
)
return None

# Check password validity
if not bcrypt.checkpw(
Expand All @@ -178,21 +172,8 @@ def get_basic_auth_user(
"Authentication failed for user %s",
credentials.username,
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Basic"},
)
return None

user = AuthenticatedUser(scopes=user.scopes, agent=dict(user.agent))

# Restrict access by scopes
if settings.LRS_RESTRICT_BY_SCOPES:
for requested_scope in security_scopes.scopes:
if not user.scopes.is_authorized(requested_scope):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f'Access not authorized to scope: "{requested_scope}".',
headers={"WWW-Authenticate": "Basic"},
)
return user
24 changes: 12 additions & 12 deletions src/ralph/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,18 +215,18 @@ def LOCALE_ENCODING(self) -> str: # pylint: disable=invalid-name
"""Returns Ralph's default locale encoding."""
return self._CORE.LOCALE_ENCODING

# @root_validator(allow_reuse=True)
# @classmethod
# def check_restriction_compatibility(cls, values):
# """Raise an error if scopes are being used without authority restriction."""
# if values.get("LRS_RESTRICT_BY_SCOPES") and not values.get(
# "LRS_RESTRICT_BY_AUTHORITY"
# ):
# raise ConfigurationException(
# "LRS_RESTRICT_BY_AUTHORITY must be set to True if using "
# "LRS_RESTRICT_BY_SCOPES=True"
# )
# return values
@root_validator(allow_reuse=True)
@classmethod
def check_restriction_compatibility(cls, values):
"""Raise an error if scopes are being used without authority restriction."""
if values.get("LRS_RESTRICT_BY_SCOPES") and not values.get(
"LRS_RESTRICT_BY_AUTHORITY"
):
raise ConfigurationException(
"LRS_RESTRICT_BY_AUTHORITY must be set to True if using "
"LRS_RESTRICT_BY_SCOPES=True"
)
return values


settings = Settings()
2 changes: 0 additions & 2 deletions tests/api/test_statements_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,8 +835,6 @@ def test_api_statements_get_scopes(
"/xAPI/statements/",
headers=headers,
)
print('on est làà')
print(response.content)
if is_authorized:
assert response.status_code == 200
assert response.json() == {"statements": [statements[1], statements[0]]}
Expand Down

0 comments on commit bb2c356

Please sign in to comment.