Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

442 Zeilen
18 KiB

  1. from __future__ import print_function, unicode_literals
  2. import frappe
  3. import pytz
  4. from frappe import _
  5. from frappe.auth import LoginManager
  6. from http import cookies
  7. from oauthlib.oauth2.rfc6749.tokens import BearerToken
  8. from oauthlib.oauth2.rfc6749.grant_types import AuthorizationCodeGrant, ImplicitGrant, ResourceOwnerPasswordCredentialsGrant, ClientCredentialsGrant, RefreshTokenGrant
  9. from oauthlib.oauth2 import RequestValidator
  10. from oauthlib.oauth2.rfc6749.endpoints.authorization import AuthorizationEndpoint
  11. from oauthlib.oauth2.rfc6749.endpoints.token import TokenEndpoint
  12. from oauthlib.oauth2.rfc6749.endpoints.resource import ResourceEndpoint
  13. from oauthlib.oauth2.rfc6749.endpoints.revocation import RevocationEndpoint
  14. from oauthlib.common import Request
  15. from six.moves.urllib.parse import unquote
  16. def get_url_delimiter(separator_character=" "):
  17. return separator_character
  18. class WebApplicationServer(AuthorizationEndpoint, TokenEndpoint, ResourceEndpoint,
  19. RevocationEndpoint):
  20. """An all-in-one endpoint featuring Authorization code grant and Bearer tokens."""
  21. def __init__(self, request_validator, token_generator=None,
  22. token_expires_in=None, refresh_token_generator=None, **kwargs):
  23. """Construct a new web application server.
  24. :param request_validator: An implementation of
  25. oauthlib.oauth2.RequestValidator.
  26. :param token_expires_in: An int or a function to generate a token
  27. expiration offset (in seconds) given a
  28. oauthlib.common.Request object.
  29. :param token_generator: A function to generate a token from a request.
  30. :param refresh_token_generator: A function to generate a token from a
  31. request for the refresh token.
  32. :param kwargs: Extra parameters to pass to authorization-,
  33. token-, resource-, and revocation-endpoint constructors.
  34. """
  35. implicit_grant = ImplicitGrant(request_validator)
  36. auth_grant = AuthorizationCodeGrant(request_validator)
  37. refresh_grant = RefreshTokenGrant(request_validator)
  38. resource_owner_password_credentials_grant = ResourceOwnerPasswordCredentialsGrant(request_validator)
  39. bearer = BearerToken(request_validator, token_generator,
  40. token_expires_in, refresh_token_generator)
  41. AuthorizationEndpoint.__init__(self, default_response_type='code',
  42. response_types={
  43. 'code': auth_grant,
  44. 'token': implicit_grant
  45. },
  46. default_token_type=bearer)
  47. TokenEndpoint.__init__(self, default_grant_type='authorization_code',
  48. grant_types={
  49. 'authorization_code': auth_grant,
  50. 'refresh_token': refresh_grant,
  51. 'password': resource_owner_password_credentials_grant
  52. },
  53. default_token_type=bearer)
  54. ResourceEndpoint.__init__(self, default_token='Bearer',
  55. token_types={'Bearer': bearer})
  56. RevocationEndpoint.__init__(self, request_validator)
  57. class OAuthWebRequestValidator(RequestValidator):
  58. # Pre- and post-authorization.
  59. def validate_client_id(self, client_id, request, *args, **kwargs):
  60. # Simple validity check, does client exist? Not banned?
  61. cli_id = frappe.db.get_value("OAuth Client",{ "name":client_id })
  62. if cli_id:
  63. request.client = frappe.get_doc("OAuth Client", client_id).as_dict()
  64. return True
  65. else:
  66. return False
  67. def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):
  68. # Is the client allowed to use the supplied redirect_uri? i.e. has
  69. # the client previously registered this EXACT redirect uri.
  70. redirect_uris = frappe.db.get_value("OAuth Client", client_id, 'redirect_uris').split(get_url_delimiter())
  71. if redirect_uri in redirect_uris:
  72. return True
  73. else:
  74. return False
  75. def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
  76. # The redirect used if none has been supplied.
  77. # Prefer your clients to pre register a redirect uri rather than
  78. # supplying one on each authorization request.
  79. redirect_uri = frappe.db.get_value("OAuth Client", client_id, 'default_redirect_uri')
  80. return redirect_uri
  81. def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
  82. # Is the client allowed to access the requested scopes?
  83. allowed_scopes = get_client_scopes(client_id)
  84. return all(scope in allowed_scopes for scope in scopes)
  85. def get_default_scopes(self, client_id, request, *args, **kwargs):
  86. # Scopes a client will authorize for if none are supplied in the
  87. # authorization request.
  88. scopes = get_client_scopes(client_id)
  89. request.scopes = scopes #Apparently this is possible.
  90. return scopes
  91. def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):
  92. # Clients should only be allowed to use one type of response type, the
  93. # one associated with their one allowed grant type.
  94. # In this case it must be "code".
  95. allowed_response_types = [client.response_type.lower(),
  96. "code token", "code id_token", "code token id_token",
  97. "code+token", "code+id_token", "code+token id_token"]
  98. return (response_type in allowed_response_types)
  99. # Post-authorization
  100. def save_authorization_code(self, client_id, code, request, *args, **kwargs):
  101. cookie_dict = get_cookie_dict_from_headers(request)
  102. oac = frappe.new_doc('OAuth Authorization Code')
  103. oac.scopes = get_url_delimiter().join(request.scopes)
  104. oac.redirect_uri_bound_to_authorization_code = request.redirect_uri
  105. oac.client = client_id
  106. oac.user = unquote(cookie_dict['user_id'].value)
  107. oac.authorization_code = code['code']
  108. oac.save(ignore_permissions=True)
  109. frappe.db.commit()
  110. def authenticate_client(self, request, *args, **kwargs):
  111. #Get ClientID in URL
  112. if request.client_id:
  113. oc = frappe.get_doc("OAuth Client", request.client_id)
  114. else:
  115. #Extract token, instantiate OAuth Bearer Token and use clientid from there.
  116. if "refresh_token" in frappe.form_dict:
  117. oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", {"refresh_token": frappe.form_dict["refresh_token"]}, 'client'))
  118. elif "token" in frappe.form_dict:
  119. oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.form_dict["token"], 'client'))
  120. else:
  121. oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.get_request_header("Authorization").split(" ")[1], 'client'))
  122. try:
  123. request.client = request.client or oc.as_dict()
  124. except Exception as e:
  125. print("Failed body authentication: Application %s does not exist".format(cid=request.client_id))
  126. cookie_dict = get_cookie_dict_from_headers(request)
  127. user_id = unquote(cookie_dict.get('user_id').value) if 'user_id' in cookie_dict else "Guest"
  128. return frappe.session.user == user_id
  129. def authenticate_client_id(self, client_id, request, *args, **kwargs):
  130. cli_id = frappe.db.get_value('OAuth Client', client_id, 'name')
  131. if not cli_id:
  132. # Don't allow public (non-authenticated) clients
  133. return False
  134. else:
  135. request["client"] = frappe.get_doc("OAuth Client", cli_id)
  136. return True
  137. def validate_code(self, client_id, code, client, request, *args, **kwargs):
  138. # Validate the code belongs to the client. Add associated scopes,
  139. # state and user to request.scopes and request.user.
  140. validcodes = frappe.get_all("OAuth Authorization Code", filters={"client": client_id, "validity": "Valid"})
  141. checkcodes = []
  142. for vcode in validcodes:
  143. checkcodes.append(vcode["name"])
  144. if code in checkcodes:
  145. request.scopes = frappe.db.get_value("OAuth Authorization Code", code, 'scopes').split(get_url_delimiter())
  146. request.user = frappe.db.get_value("OAuth Authorization Code", code, 'user')
  147. return True
  148. else:
  149. return False
  150. def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs):
  151. saved_redirect_uri = frappe.db.get_value('OAuth Client', client_id, 'default_redirect_uri')
  152. return saved_redirect_uri == redirect_uri
  153. def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
  154. # Clients should only be allowed to use one type of grant.
  155. # In this case, it must be "authorization_code" or "refresh_token"
  156. return (grant_type in ["authorization_code", "refresh_token", "password"])
  157. def save_bearer_token(self, token, request, *args, **kwargs):
  158. # Remember to associate it with request.scopes, request.user and
  159. # request.client. The two former will be set when you validate
  160. # the authorization code. Don't forget to save both the
  161. # access_token and the refresh_token and set expiration for the
  162. # access_token to now + expires_in seconds.
  163. otoken = frappe.new_doc("OAuth Bearer Token")
  164. otoken.client = request.client['name']
  165. try:
  166. otoken.user = request.user if request.user else frappe.db.get_value("OAuth Bearer Token", {"refresh_token":request.body.get("refresh_token")}, "user")
  167. except Exception as e:
  168. otoken.user = frappe.session.user
  169. otoken.scopes = get_url_delimiter().join(request.scopes)
  170. otoken.access_token = token['access_token']
  171. otoken.refresh_token = token.get('refresh_token')
  172. otoken.expires_in = token['expires_in']
  173. otoken.save(ignore_permissions=True)
  174. frappe.db.commit()
  175. default_redirect_uri = frappe.db.get_value("OAuth Client", request.client['name'], "default_redirect_uri")
  176. return default_redirect_uri
  177. def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):
  178. # Authorization codes are use once, invalidate it when a Bearer token
  179. # has been acquired.
  180. frappe.db.set_value("OAuth Authorization Code", code, "validity", "Invalid")
  181. frappe.db.commit()
  182. # Protected resource request
  183. def validate_bearer_token(self, token, scopes, request):
  184. # Remember to check expiration and scope membership
  185. otoken = frappe.get_doc("OAuth Bearer Token", token)
  186. token_expiration_local = otoken.expiration_time.replace(tzinfo=pytz.timezone(frappe.utils.get_time_zone()))
  187. token_expiration_utc = token_expiration_local.astimezone(pytz.utc)
  188. is_token_valid = (frappe.utils.datetime.datetime.utcnow().replace(tzinfo=pytz.utc) < token_expiration_utc) \
  189. and otoken.status != "Revoked"
  190. client_scopes = frappe.db.get_value("OAuth Client", otoken.client, 'scopes').split(get_url_delimiter())
  191. are_scopes_valid = True
  192. for scp in scopes:
  193. are_scopes_valid = are_scopes_valid and True if scp in client_scopes else False
  194. return is_token_valid and are_scopes_valid
  195. # Token refresh request
  196. def get_original_scopes(self, refresh_token, request, *args, **kwargs):
  197. # Obtain the token associated with the given refresh_token and
  198. # return its scopes, these will be passed on to the refreshed
  199. # access token if the client did not specify a scope during the
  200. # request.
  201. obearer_token = frappe.get_doc("OAuth Bearer Token", {"refresh_token": refresh_token})
  202. return obearer_token.scopes
  203. def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
  204. """Revoke an access or refresh token.
  205. :param token: The token string.
  206. :param token_type_hint: access_token or refresh_token.
  207. :param request: The HTTP Request (oauthlib.common.Request)
  208. Method is used by:
  209. - Revocation Endpoint
  210. """
  211. otoken = None
  212. if token_type_hint == "access_token":
  213. otoken = frappe.db.set_value("OAuth Bearer Token", token, 'status', 'Revoked')
  214. elif token_type_hint == "refresh_token":
  215. otoken = frappe.db.set_value("OAuth Bearer Token", {"refresh_token": token}, 'status', 'Revoked')
  216. else:
  217. otoken = frappe.db.set_value("OAuth Bearer Token", token, 'status', 'Revoked')
  218. frappe.db.commit()
  219. def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):
  220. # """Ensure the Bearer token is valid and authorized access to scopes.
  221. # OBS! The request.user attribute should be set to the resource owner
  222. # associated with this refresh token.
  223. # :param refresh_token: Unicode refresh token
  224. # :param client: Client object set by you, see authenticate_client.
  225. # :param request: The HTTP Request (oauthlib.common.Request)
  226. # :rtype: True or False
  227. # Method is used by:
  228. # - Authorization Code Grant (indirectly by issuing refresh tokens)
  229. # - Resource Owner Password Credentials Grant (also indirectly)
  230. # - Refresh Token Grant
  231. # """
  232. otoken = frappe.get_doc("OAuth Bearer Token", {"refresh_token": refresh_token, "status": "Active"})
  233. if not otoken:
  234. return False
  235. else:
  236. return True
  237. # OpenID Connect
  238. def get_id_token(self, token, token_handler, request):
  239. """
  240. In the OpenID Connect workflows when an ID Token is requested this method is called.
  241. Subclasses should implement the construction, signing and optional encryption of the
  242. ID Token as described in the OpenID Connect spec.
  243. In addition to the standard OAuth2 request properties, the request may also contain
  244. these OIDC specific properties which are useful to this method:
  245. - nonce, if workflow is implicit or hybrid and it was provided
  246. - claims, if provided to the original Authorization Code request
  247. The token parameter is a dict which may contain an ``access_token`` entry, in which
  248. case the resulting ID Token *should* include a calculated ``at_hash`` claim.
  249. Similarly, when the request parameter has a ``code`` property defined, the ID Token
  250. *should* include a calculated ``c_hash`` claim.
  251. http://openid.net/specs/openid-connect-core-1_0.html (sections `3.1.3.6`_, `3.2.2.10`_, `3.3.2.11`_)
  252. .. _`3.1.3.6`: http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  253. .. _`3.2.2.10`: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDToken
  254. .. _`3.3.2.11`: http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken
  255. :param token: A Bearer token dict
  256. :param token_handler: the token handler (BearerToken class)
  257. :param request: the HTTP Request (oauthlib.common.Request)
  258. :return: The ID Token (a JWS signed JWT)
  259. """
  260. # the request.scope should be used by the get_id_token() method to determine which claims to include in the resulting id_token
  261. def validate_silent_authorization(self, request):
  262. """Ensure the logged in user has authorized silent OpenID authorization.
  263. Silent OpenID authorization allows access tokens and id tokens to be
  264. granted to clients without any user prompt or interaction.
  265. :param request: The HTTP Request (oauthlib.common.Request)
  266. :rtype: True or False
  267. Method is used by:
  268. - OpenIDConnectAuthCode
  269. - OpenIDConnectImplicit
  270. - OpenIDConnectHybrid
  271. """
  272. if request.prompt == "login":
  273. False
  274. else:
  275. True
  276. def validate_silent_login(self, request):
  277. """Ensure session user has authorized silent OpenID login.
  278. If no user is logged in or has not authorized silent login, this
  279. method should return False.
  280. If the user is logged in but associated with multiple accounts and
  281. not selected which one to link to the token then this method should
  282. raise an oauthlib.oauth2.AccountSelectionRequired error.
  283. :param request: The HTTP Request (oauthlib.common.Request)
  284. :rtype: True or False
  285. Method is used by:
  286. - OpenIDConnectAuthCode
  287. - OpenIDConnectImplicit
  288. - OpenIDConnectHybrid
  289. """
  290. if frappe.session.user == "Guest" or request.prompt.lower() == "login":
  291. return False
  292. else:
  293. return True
  294. def validate_user_match(self, id_token_hint, scopes, claims, request):
  295. """Ensure client supplied user id hint matches session user.
  296. If the sub claim or id_token_hint is supplied then the session
  297. user must match the given ID.
  298. :param id_token_hint: User identifier string.
  299. :param scopes: List of OAuth 2 scopes and OpenID claims (strings).
  300. :param claims: OpenID Connect claims dict.
  301. :param request: The HTTP Request (oauthlib.common.Request)
  302. :rtype: True or False
  303. Method is used by:
  304. - OpenIDConnectAuthCode
  305. - OpenIDConnectImplicit
  306. - OpenIDConnectHybrid
  307. """
  308. if id_token_hint and id_token_hint == frappe.db.get_value("User Social Login", {"parent":frappe.session.user, "provider": "frappe"}, "userid"):
  309. return True
  310. else:
  311. return False
  312. def validate_user(self, username, password, client, request, *args, **kwargs):
  313. """Ensure the username and password is valid.
  314. Method is used by:
  315. - Resource Owner Password Credentials Grant
  316. """
  317. login_manager = LoginManager()
  318. login_manager.authenticate(username, password)
  319. request.user = login_manager.user
  320. return True
  321. def get_cookie_dict_from_headers(r):
  322. cookie = cookies.BaseCookie()
  323. if r.headers.get('Cookie'):
  324. cookie.load(r.headers.get('Cookie'))
  325. return cookie
  326. def calculate_at_hash(access_token, hash_alg):
  327. """Helper method for calculating an access token
  328. hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  329. Its value is the base64url encoding of the left-most half of the hash of the octets
  330. of the ASCII representation of the access_token value, where the hash algorithm
  331. used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE
  332. Header. For instance, if the alg is RS256, hash the access_token value with SHA-256,
  333. then take the left-most 128 bits and base64url encode them. The at_hash value is a
  334. case sensitive string.
  335. Args:
  336. access_token (str): An access token string.
  337. hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256
  338. """
  339. hash_digest = hash_alg(access_token.encode('utf-8')).digest()
  340. cut_at = int(len(hash_digest) / 2)
  341. truncated = hash_digest[:cut_at]
  342. from jwt.utils import base64url_encode
  343. at_hash = base64url_encode(truncated)
  344. return at_hash.decode('utf-8')
  345. def delete_oauth2_data():
  346. # Delete Invalid Authorization Code and Revoked Token
  347. commit_code, commit_token = False, False
  348. code_list = frappe.get_all("OAuth Authorization Code", filters={"validity":"Invalid"})
  349. token_list = frappe.get_all("OAuth Bearer Token", filters={"status":"Revoked"})
  350. if len(code_list) > 0:
  351. commit_code = True
  352. if len(token_list) > 0:
  353. commit_token = True
  354. for code in code_list:
  355. frappe.delete_doc("OAuth Authorization Code", code["name"])
  356. for token in token_list:
  357. frappe.delete_doc("OAuth Bearer Token", token["name"])
  358. if commit_code or commit_token:
  359. frappe.db.commit()
  360. def get_client_scopes(client_id):
  361. scopes_string = frappe.db.get_value("OAuth Client", client_id, "scopes")
  362. return scopes_string.split()