config.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. from datetime import datetime
  2. from datetime import timedelta
  3. from datetime import timezone
  4. from typing import Iterable
  5. from typing import List
  6. from typing import Optional
  7. from typing import Sequence
  8. from typing import Type
  9. from typing import Union
  10. from flask import current_app
  11. from flask.json import JSONEncoder
  12. from jwt.algorithms import requires_cryptography
  13. from flask_jwt_extended.typing import ExpiresDelta
  14. class _Config(object):
  15. """
  16. Helper object for accessing and verifying options in this extension. This
  17. is meant for internal use of the application; modifying config options
  18. should be done with flasks ```app.config```.
  19. Default values for the configuration options are set in the jwt_manager
  20. object. All of these values are read only. This is simply a loose wrapper
  21. with some helper functionality for flasks `app.config`.
  22. """
  23. @property
  24. def is_asymmetric(self) -> bool:
  25. return self.algorithm in requires_cryptography
  26. @property
  27. def encode_key(self) -> str:
  28. return self._private_key if self.is_asymmetric else self._secret_key
  29. @property
  30. def decode_key(self) -> str:
  31. return self._public_key if self.is_asymmetric else self._secret_key
  32. @property
  33. def token_location(self) -> Sequence[str]:
  34. locations = current_app.config["JWT_TOKEN_LOCATION"]
  35. if isinstance(locations, str):
  36. locations = (locations,)
  37. elif not isinstance(locations, Iterable):
  38. raise RuntimeError("JWT_TOKEN_LOCATION must be a sequence or a set")
  39. elif not locations:
  40. raise RuntimeError(
  41. "JWT_TOKEN_LOCATION must contain at least one "
  42. 'of "headers", "cookies", "query_string", or "json"'
  43. )
  44. for location in locations:
  45. if location not in ("headers", "cookies", "query_string", "json"):
  46. raise RuntimeError(
  47. "JWT_TOKEN_LOCATION can only contain "
  48. '"headers", "cookies", "query_string", or "json"'
  49. )
  50. return locations
  51. @property
  52. def jwt_in_cookies(self) -> bool:
  53. return "cookies" in self.token_location
  54. @property
  55. def jwt_in_headers(self) -> bool:
  56. return "headers" in self.token_location
  57. @property
  58. def jwt_in_query_string(self) -> bool:
  59. return "query_string" in self.token_location
  60. @property
  61. def jwt_in_json(self) -> bool:
  62. return "json" in self.token_location
  63. @property
  64. def header_name(self) -> str:
  65. name = current_app.config["JWT_HEADER_NAME"]
  66. if not name:
  67. raise RuntimeError("JWT_ACCESS_HEADER_NAME cannot be empty")
  68. return name
  69. @property
  70. def header_type(self) -> str:
  71. return current_app.config["JWT_HEADER_TYPE"]
  72. @property
  73. def query_string_name(self) -> str:
  74. return current_app.config["JWT_QUERY_STRING_NAME"]
  75. @property
  76. def query_string_value_prefix(self) -> str:
  77. return current_app.config["JWT_QUERY_STRING_VALUE_PREFIX"]
  78. @property
  79. def access_cookie_name(self) -> str:
  80. return current_app.config["JWT_ACCESS_COOKIE_NAME"]
  81. @property
  82. def refresh_cookie_name(self) -> str:
  83. return current_app.config["JWT_REFRESH_COOKIE_NAME"]
  84. @property
  85. def access_cookie_path(self) -> str:
  86. return current_app.config["JWT_ACCESS_COOKIE_PATH"]
  87. @property
  88. def refresh_cookie_path(self) -> str:
  89. return current_app.config["JWT_REFRESH_COOKIE_PATH"]
  90. @property
  91. def cookie_secure(self) -> bool:
  92. return current_app.config["JWT_COOKIE_SECURE"]
  93. @property
  94. def cookie_domain(self) -> str:
  95. return current_app.config["JWT_COOKIE_DOMAIN"]
  96. @property
  97. def session_cookie(self) -> bool:
  98. return current_app.config["JWT_SESSION_COOKIE"]
  99. @property
  100. def cookie_samesite(self) -> str:
  101. return current_app.config["JWT_COOKIE_SAMESITE"]
  102. @property
  103. def json_key(self) -> str:
  104. return current_app.config["JWT_JSON_KEY"]
  105. @property
  106. def refresh_json_key(self) -> str:
  107. return current_app.config["JWT_REFRESH_JSON_KEY"]
  108. @property
  109. def csrf_protect(self) -> bool:
  110. return self.jwt_in_cookies and current_app.config["JWT_COOKIE_CSRF_PROTECT"]
  111. @property
  112. def csrf_request_methods(self) -> Iterable[str]:
  113. return current_app.config["JWT_CSRF_METHODS"]
  114. @property
  115. def csrf_in_cookies(self) -> bool:
  116. return current_app.config["JWT_CSRF_IN_COOKIES"]
  117. @property
  118. def access_csrf_cookie_name(self) -> str:
  119. return current_app.config["JWT_ACCESS_CSRF_COOKIE_NAME"]
  120. @property
  121. def refresh_csrf_cookie_name(self) -> str:
  122. return current_app.config["JWT_REFRESH_CSRF_COOKIE_NAME"]
  123. @property
  124. def access_csrf_cookie_path(self) -> str:
  125. return current_app.config["JWT_ACCESS_CSRF_COOKIE_PATH"]
  126. @property
  127. def refresh_csrf_cookie_path(self) -> str:
  128. return current_app.config["JWT_REFRESH_CSRF_COOKIE_PATH"]
  129. @property
  130. def access_csrf_header_name(self) -> str:
  131. return current_app.config["JWT_ACCESS_CSRF_HEADER_NAME"]
  132. @property
  133. def refresh_csrf_header_name(self) -> str:
  134. return current_app.config["JWT_REFRESH_CSRF_HEADER_NAME"]
  135. @property
  136. def csrf_check_form(self) -> bool:
  137. return current_app.config["JWT_CSRF_CHECK_FORM"]
  138. @property
  139. def access_csrf_field_name(self) -> str:
  140. return current_app.config["JWT_ACCESS_CSRF_FIELD_NAME"]
  141. @property
  142. def refresh_csrf_field_name(self) -> str:
  143. return current_app.config["JWT_REFRESH_CSRF_FIELD_NAME"]
  144. @property
  145. def access_expires(self) -> ExpiresDelta:
  146. delta = current_app.config["JWT_ACCESS_TOKEN_EXPIRES"]
  147. if type(delta) is int:
  148. delta = timedelta(seconds=delta)
  149. if delta is not False:
  150. try:
  151. # Basically runtime typechecking. Probably a better way to do
  152. # this with proper type checking
  153. delta + datetime.now(timezone.utc)
  154. except TypeError as e:
  155. err = (
  156. "must be able to add JWT_ACCESS_TOKEN_EXPIRES to datetime.datetime"
  157. )
  158. raise RuntimeError(err) from e
  159. return delta
  160. @property
  161. def refresh_expires(self) -> ExpiresDelta:
  162. delta = current_app.config["JWT_REFRESH_TOKEN_EXPIRES"]
  163. if type(delta) is int:
  164. delta = timedelta(seconds=delta)
  165. if delta is not False:
  166. # Basically runtime typechecking. Probably a better way to do
  167. # this with proper type checking
  168. try:
  169. delta + datetime.now(timezone.utc)
  170. except TypeError as e:
  171. err = (
  172. "must be able to add JWT_REFRESH_TOKEN_EXPIRES to datetime.datetime"
  173. )
  174. raise RuntimeError(err) from e
  175. return delta
  176. @property
  177. def algorithm(self) -> str:
  178. return current_app.config["JWT_ALGORITHM"]
  179. @property
  180. def decode_algorithms(self) -> List[str]:
  181. algorithms = current_app.config["JWT_DECODE_ALGORITHMS"]
  182. if not algorithms:
  183. return [self.algorithm]
  184. if self.algorithm not in algorithms:
  185. algorithms.append(self.algorithm)
  186. return algorithms
  187. @property
  188. def _secret_key(self) -> str:
  189. key = current_app.config["JWT_SECRET_KEY"]
  190. if not key:
  191. key = current_app.config.get("SECRET_KEY", None)
  192. if not key:
  193. raise RuntimeError(
  194. "JWT_SECRET_KEY or flask SECRET_KEY "
  195. "must be set when using symmetric "
  196. 'algorithm "{}"'.format(self.algorithm)
  197. )
  198. return key
  199. @property
  200. def _public_key(self) -> str:
  201. key = current_app.config["JWT_PUBLIC_KEY"]
  202. if not key:
  203. raise RuntimeError(
  204. "JWT_PUBLIC_KEY must be set to use "
  205. "asymmetric cryptography algorithm "
  206. '"{}"'.format(self.algorithm)
  207. )
  208. return key
  209. @property
  210. def _private_key(self) -> str:
  211. key = current_app.config["JWT_PRIVATE_KEY"]
  212. if not key:
  213. raise RuntimeError(
  214. "JWT_PRIVATE_KEY must be set to use "
  215. "asymmetric cryptography algorithm "
  216. '"{}"'.format(self.algorithm)
  217. )
  218. return key
  219. @property
  220. def cookie_max_age(self) -> Optional[int]:
  221. # Returns the appropiate value for max_age for flask set_cookies. If
  222. # session cookie is true, return None, otherwise return a number of
  223. # seconds 1 year in the future
  224. return None if self.session_cookie else 31540000 # 1 year
  225. @property
  226. def identity_claim_key(self) -> str:
  227. return current_app.config["JWT_IDENTITY_CLAIM"]
  228. @property
  229. def exempt_methods(self) -> Iterable[str]:
  230. return {"OPTIONS"}
  231. @property
  232. def error_msg_key(self) -> str:
  233. return current_app.config["JWT_ERROR_MESSAGE_KEY"]
  234. @property
  235. def json_encoder(self) -> Type[JSONEncoder]:
  236. return current_app.json_encoder
  237. @property
  238. def decode_audience(self) -> Union[str, Iterable[str]]:
  239. return current_app.config["JWT_DECODE_AUDIENCE"]
  240. @property
  241. def encode_audience(self) -> Union[str, Iterable[str]]:
  242. return current_app.config["JWT_ENCODE_AUDIENCE"]
  243. @property
  244. def encode_issuer(self) -> str:
  245. return current_app.config["JWT_ENCODE_ISSUER"]
  246. @property
  247. def decode_issuer(self) -> str:
  248. return current_app.config["JWT_DECODE_ISSUER"]
  249. @property
  250. def leeway(self) -> int:
  251. return current_app.config["JWT_DECODE_LEEWAY"]
  252. @property
  253. def encode_nbf(self) -> bool:
  254. return current_app.config["JWT_ENCODE_NBF"]
  255. config = _Config()