oauth2.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """
  2. Authentication backend that checks credentials against an oauth2 server auth endpoint
  3. """
  4. from radicale import auth
  5. from radicale.log import logger
  6. import requests
  7. from requests.utils import quote
  8. class Auth(auth.BaseAuth):
  9. def __init__(self, configuration):
  10. super().__init__(configuration)
  11. self._endpoint = configuration.get("auth", "oauth2_token_endpoint")
  12. logger.warning("Using oauth2 token endpoint: %s" % (self._endpoint))
  13. def login(self, login, password):
  14. """Validate credentials.
  15. Sends login credentials to oauth auth endpoint and checks that a token is returned
  16. """
  17. try:
  18. # authenticate to authentication endpoint and return login if ok, else ""
  19. req_params = {
  20. "username": login,
  21. "password": password,
  22. "grant_type": "password",
  23. "client_id": "radicale",
  24. }
  25. req_headers = {"Content-Type": "application/x-www-form-urlencoded"}
  26. response = requests.post(
  27. self._endpoint, data=req_params, headers=req_headers
  28. )
  29. if (
  30. response.status_code == requests.codes.ok
  31. and "access_token" in response.json()
  32. ):
  33. return login
  34. except OSError as e:
  35. raise RuntimeError(
  36. "Failed to authenticate against oauth server %r: %s"
  37. % (self._endpoint, e)
  38. ) from e
  39. logger.warning("User %s failed to authenticate" % (str(login)))
  40. return ""