authentification.py 1.4KB

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