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.
 
 
 
 
 
 

433 line
17 KiB

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