You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

439 lines
18 KiB

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