authentification.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import typing
  2. from pyramid.request import Request
  3. from sqlalchemy.orm.exc import NoResultFound
  4. from tracim_backend import TracimRequest
  5. from tracim_backend.exceptions import UserDoesNotExist
  6. from tracim_backend.lib.core.user import UserApi
  7. from tracim_backend.models import User
  8. BASIC_AUTH_WEBUI_REALM = "tracim"
  9. ###
  10. # Pyramid HTTP Basic Auth
  11. ###
  12. def basic_auth_check_credentials(
  13. login: str,
  14. cleartext_password: str,
  15. request: TracimRequest
  16. ) -> typing.Optional[list]:
  17. """
  18. Check credential for pyramid basic_auth
  19. :param login: login of user
  20. :param cleartext_password: user password in cleartext
  21. :param request: Pyramid request
  22. :return: None if auth failed, list of permissions if auth succeed
  23. """
  24. # Do not accept invalid user
  25. user = _get_basic_auth_unsafe_user(request)
  26. if not user \
  27. or user.email != login \
  28. or not user.is_active \
  29. or not user.validate_password(cleartext_password):
  30. return None
  31. return []
  32. def _get_basic_auth_unsafe_user(
  33. request: Request,
  34. ) -> typing.Optional[User]:
  35. """
  36. :param request: pyramid request
  37. :return: User or None
  38. """
  39. app_config = request.registry.settings['CFG']
  40. uapi = UserApi(None, session=request.dbsession, config=app_config)
  41. try:
  42. login = request.unauthenticated_userid
  43. if not login:
  44. return None
  45. user = uapi.get_one_by_email(login)
  46. except UserDoesNotExist:
  47. return None
  48. return user