Skip to content

Commit

Permalink
import patch from dev
Browse files Browse the repository at this point in the history
  • Loading branch information
delcroip committed May 30, 2024
1 parent 3bc7106 commit fcca4db
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 28 deletions.
30 changes: 13 additions & 17 deletions core/jwt_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,19 @@ class to obtain token from header if it is provided

def authenticate(self, request):
token = get_credentials(request)
if not token:
return

# Do not pass context to avoid to try to get user from request to get his private key.
try:
user = get_user_by_token(token)
except (jwt.PyJWTError, JSONWebTokenError) as exc:
raise exceptions.AuthenticationFailed("INCORRECT_CREDENTIALS") from exc
except Exception as exc:
raise exceptions.AuthenticationFailed(str(exc)) from exc
else:
if CoreConfig.is_valid_health_facility_contract_required:
if not (hasattr(user, 'health_facility') and hasattr(user.health_facility, 'contract_end_date') and
user.health_facility.contract_end_date > date.today()):
raise exceptions.AuthenticationFailed("HF_CONTRACT_INVALID")

return user, None
if token:
try:
user = get_user_by_token(token)
except (jwt.PyJWTError, JSONWebTokenError) as exc:
raise exceptions.AuthenticationFailed("INCORRECT_CREDENTIALS") from exc
except Exception as exc:
raise exceptions.AuthenticationFailed(str(exc)) from exc
else:
if CoreConfig.is_valid_health_facility_contract_required:
if not (hasattr(user, 'health_facility') and hasattr(user.health_facility, 'contract_end_date') and
user.health_facility.contract_end_date > date.today()):
raise exceptions.AuthenticationFailed("HF_CONTRACT_INVALID")
return user, None

def enforce_csrf(self, request):
return # To not perform the csrf during checking auth header
13 changes: 4 additions & 9 deletions core/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
change_user_password,
reset_user_password,
set_user_password,
user_authentication,
)
from core.tasks import openimis_mutation_async
from core import filter_validity
Expand Down Expand Up @@ -1573,15 +1574,9 @@ class OpenimisObtainJSONWebToken(mixins.ResolveMixin, JSONWebTokenMutation):
@classmethod
def mutate(cls, root, info, **kwargs):
username = kwargs.get("username")
# consider auto-provisioning
if username:
# get_or_create will auto-provision from tblUsers if applicable
user = User.objects.get_or_create(username=username)
if not user:
logger.debug("Authentication with %s failed and could not be fetched from tblUsers", username)
else:
kwargs[User.USERNAME_FIELD] = user[0].username

password = kwargs.get("password")
request = info.context
info.context.user = user_authentication(request, username, password)
return super().mutate(cls, info, **kwargs)


Expand Down
2 changes: 1 addition & 1 deletion core/services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
from core.services.userServices import create_or_update_interactive_user, create_or_update_user_roles, \
create_or_update_user_districts, create_or_update_officer_villages, create_or_update_officer, \
create_or_update_claim_admin, create_or_update_core_user, change_user_password, set_user_password, \
reset_user_password
reset_user_password, user_authentication
18 changes: 17 additions & 1 deletion core/services/userServices.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
from django.template import loader
from django.utils.http import urlencode
from django.core.cache import cache

from django.contrib.auth import authenticate
from rest_framework import exceptions
from core.apps import CoreConfig
from core.models import User, InteractiveUser, Officer, UserRole
from core.validation.obligatoryFieldValidation import validate_payload_for_obligatory_fields
Expand Down Expand Up @@ -36,7 +39,10 @@ def create_or_update_interactive_user(user_id, data, audit_user_id, connected):
if i_user.validity_to is not None and i_user.validity_to:
raise ValidationError(_('core.user.edit_historical_data_error'))
else:
i_user = InteractiveUser.objects.filter(validity_to__isnull=True, login_name=data_subset["login_name"] ).first()
i_user = InteractiveUser.objects.filter(
validity_to__isnull=True,
login_name=data_subset["login_name"]
).first()
if i_user:
i_user.save_history()
[setattr(i_user, k, v) for k, v in data_subset.items()]
Expand Down Expand Up @@ -290,3 +296,13 @@ def reset_user_password(request, username):
return email_to_send
except BadHeaderError:
return ValueError("Invalid header found.")


def user_authentication(request, username, password):
if not username or not password:
raise exceptions.ParseError(_("Missing username or password"))
user = authenticate(request, username=username, password=password)
if not user:
logger.debug(f"Authentication failed for username: {username}")
raise exceptions.AuthenticationFailed("INCORRECT_CREDENTIALS")
return user

0 comments on commit fcca4db

Please sign in to comment.