25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

436 lines
18 KiB

  1. from __future__ import print_function
  2. import frappe, urllib
  3. import pytz
  4. from frappe import _
  5. from urlparse import parse_qs, urlparse
  6. from oauthlib.oauth2.rfc6749.tokens import BearerToken
  7. from oauthlib.oauth2.rfc6749.grant_types import AuthorizationCodeGrant, ImplicitGrant, ResourceOwnerPasswordCredentialsGrant, ClientCredentialsGrant, RefreshTokenGrant, OpenIDConnectAuthCode
  8. from oauthlib.oauth2 import RequestValidator
  9. from oauthlib.oauth2.rfc6749.endpoints.authorization import AuthorizationEndpoint
  10. from oauthlib.oauth2.rfc6749.endpoints.token import TokenEndpoint
  11. from oauthlib.oauth2.rfc6749.endpoints.resource import ResourceEndpoint
  12. from oauthlib.oauth2.rfc6749.endpoints.revocation import RevocationEndpoint
  13. from oauthlib.common import Request
  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 = urllib.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 frappe.form_dict.has_key("refresh_token"):
  124. oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", {"refresh_token": frappe.form_dict["refresh_token"]}, 'client'))
  125. elif frappe.form_dict.has_key("token"):
  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 == urllib.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. otoken.user = request.user if request.user else frappe.db.get_value("OAuth Bearer Token", {"refresh_token":request.body.get("refresh_token")}, "user")
  171. otoken.scopes = get_url_delimiter().join(request.scopes)
  172. otoken.access_token = token['access_token']
  173. otoken.refresh_token = token.get('refresh_token')
  174. otoken.expires_in = token['expires_in']
  175. otoken.save(ignore_permissions=True)
  176. frappe.db.commit()
  177. default_redirect_uri = frappe.db.get_value("OAuth Client", request.client['name'], "default_redirect_uri")
  178. return default_redirect_uri
  179. def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):
  180. # Authorization codes are use once, invalidate it when a Bearer token
  181. # has been acquired.
  182. frappe.db.set_value("OAuth Authorization Code", code, "validity", "Invalid")
  183. frappe.db.commit()
  184. # Protected resource request
  185. def validate_bearer_token(self, token, scopes, request):
  186. # Remember to check expiration and scope membership
  187. otoken = frappe.get_doc("OAuth Bearer Token", token)
  188. token_expiration_local = otoken.expiration_time.replace(tzinfo=pytz.timezone(frappe.utils.get_time_zone()))
  189. token_expiration_utc = token_expiration_local.astimezone(pytz.utc)
  190. is_token_valid = (frappe.utils.datetime.datetime.utcnow().replace(tzinfo=pytz.utc) < token_expiration_utc) \
  191. and otoken.status != "Revoked"
  192. client_scopes = frappe.db.get_value("OAuth Client", otoken.client, 'scopes').split(get_url_delimiter())
  193. are_scopes_valid = True
  194. for scp in scopes:
  195. are_scopes_valid = are_scopes_valid and True if scp in client_scopes else False
  196. return is_token_valid and are_scopes_valid
  197. # Token refresh request
  198. def get_original_scopes(self, refresh_token, request, *args, **kwargs):
  199. # Obtain the token associated with the given refresh_token and
  200. # return its scopes, these will be passed on to the refreshed
  201. # access token if the client did not specify a scope during the
  202. # request.
  203. obearer_token = frappe.get_doc("OAuth Bearer Token", {"refresh_token": refresh_token})
  204. return obearer_token.scopes
  205. def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
  206. """Revoke an access or refresh token.
  207. :param token: The token string.
  208. :param token_type_hint: access_token or refresh_token.
  209. :param request: The HTTP Request (oauthlib.common.Request)
  210. Method is used by:
  211. - Revocation Endpoint
  212. """
  213. otoken = None
  214. if token_type_hint == "access_token":
  215. otoken = frappe.db.set_value("OAuth Bearer Token", token, 'status', 'Revoked')
  216. elif token_type_hint == "refresh_token":
  217. otoken = frappe.db.set_value("OAuth Bearer Token", {"refresh_token": token}, 'status', 'Revoked')
  218. else:
  219. otoken = frappe.db.set_value("OAuth Bearer Token", token, 'status', 'Revoked')
  220. frappe.db.commit()
  221. def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):
  222. # """Ensure the Bearer token is valid and authorized access to scopes.
  223. # OBS! The request.user attribute should be set to the resource owner
  224. # associated with this refresh token.
  225. # :param refresh_token: Unicode refresh token
  226. # :param client: Client object set by you, see authenticate_client.
  227. # :param request: The HTTP Request (oauthlib.common.Request)
  228. # :rtype: True or False
  229. # Method is used by:
  230. # - Authorization Code Grant (indirectly by issuing refresh tokens)
  231. # - Resource Owner Password Credentials Grant (also indirectly)
  232. # - Refresh Token Grant
  233. # """
  234. otoken = frappe.get_doc("OAuth Bearer Token", {"refresh_token": refresh_token, "status": "Active"})
  235. if not otoken:
  236. return False
  237. else:
  238. return True
  239. # OpenID Connect
  240. def get_id_token(self, token, token_handler, request):
  241. """
  242. In the OpenID Connect workflows when an ID Token is requested this method is called.
  243. Subclasses should implement the construction, signing and optional encryption of the
  244. ID Token as described in the OpenID Connect spec.
  245. In addition to the standard OAuth2 request properties, the request may also contain
  246. these OIDC specific properties which are useful to this method:
  247. - nonce, if workflow is implicit or hybrid and it was provided
  248. - claims, if provided to the original Authorization Code request
  249. The token parameter is a dict which may contain an ``access_token`` entry, in which
  250. case the resulting ID Token *should* include a calculated ``at_hash`` claim.
  251. Similarly, when the request parameter has a ``code`` property defined, the ID Token
  252. *should* include a calculated ``c_hash`` claim.
  253. http://openid.net/specs/openid-connect-core-1_0.html (sections `3.1.3.6`_, `3.2.2.10`_, `3.3.2.11`_)
  254. .. _`3.1.3.6`: http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  255. .. _`3.2.2.10`: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDToken
  256. .. _`3.3.2.11`: http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken
  257. :param token: A Bearer token dict
  258. :param token_handler: the token handler (BearerToken class)
  259. :param request: the HTTP Request (oauthlib.common.Request)
  260. :return: The ID Token (a JWS signed JWT)
  261. """
  262. # the request.scope should be used by the get_id_token() method to determine which claims to include in the resulting id_token
  263. def validate_silent_authorization(self, request):
  264. """Ensure the logged in user has authorized silent OpenID authorization.
  265. Silent OpenID authorization allows access tokens and id tokens to be
  266. granted to clients without any user prompt or interaction.
  267. :param request: The HTTP Request (oauthlib.common.Request)
  268. :rtype: True or False
  269. Method is used by:
  270. - OpenIDConnectAuthCode
  271. - OpenIDConnectImplicit
  272. - OpenIDConnectHybrid
  273. """
  274. if request.prompt == "login":
  275. False
  276. else:
  277. True
  278. def validate_silent_login(self, request):
  279. """Ensure session user has authorized silent OpenID login.
  280. If no user is logged in or has not authorized silent login, this
  281. method should return False.
  282. If the user is logged in but associated with multiple accounts and
  283. not selected which one to link to the token then this method should
  284. raise an oauthlib.oauth2.AccountSelectionRequired error.
  285. :param request: The HTTP Request (oauthlib.common.Request)
  286. :rtype: True or False
  287. Method is used by:
  288. - OpenIDConnectAuthCode
  289. - OpenIDConnectImplicit
  290. - OpenIDConnectHybrid
  291. """
  292. if frappe.session.user == "Guest" or request.prompt.lower() == "login":
  293. return False
  294. else:
  295. return True
  296. def validate_user_match(self, id_token_hint, scopes, claims, request):
  297. """Ensure client supplied user id hint matches session user.
  298. If the sub claim or id_token_hint is supplied then the session
  299. user must match the given ID.
  300. :param id_token_hint: User identifier string.
  301. :param scopes: List of OAuth 2 scopes and OpenID claims (strings).
  302. :param claims: OpenID Connect claims dict.
  303. :param request: The HTTP Request (oauthlib.common.Request)
  304. :rtype: True or False
  305. Method is used by:
  306. - OpenIDConnectAuthCode
  307. - OpenIDConnectImplicit
  308. - OpenIDConnectHybrid
  309. """
  310. if id_token_hint and id_token_hint == frappe.get_value("User", frappe.session.user, "frappe_userid"):
  311. return True
  312. else:
  313. return False
  314. def get_cookie_dict_from_headers(r):
  315. if r.headers.get('Cookie'):
  316. cookie = r.headers.get('Cookie')
  317. cookie = cookie.split("; ")
  318. cookie_dict = {k:v for k,v in (x.split('=') for x in cookie)}
  319. return cookie_dict
  320. else:
  321. return {}
  322. def calculate_at_hash(access_token, hash_alg):
  323. """Helper method for calculating an access token
  324. hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  325. Its value is the base64url encoding of the left-most half of the hash of the octets
  326. of the ASCII representation of the access_token value, where the hash algorithm
  327. used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE
  328. Header. For instance, if the alg is RS256, hash the access_token value with SHA-256,
  329. then take the left-most 128 bits and base64url encode them. The at_hash value is a
  330. case sensitive string.
  331. Args:
  332. access_token (str): An access token string.
  333. hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256
  334. """
  335. hash_digest = hash_alg(access_token.encode('utf-8')).digest()
  336. cut_at = int(len(hash_digest) / 2)
  337. truncated = hash_digest[:cut_at]
  338. from jwt.utils import base64url_encode
  339. at_hash = base64url_encode(truncated)
  340. return at_hash.decode('utf-8')
  341. def delete_oauth2_data():
  342. # Delete Invalid Authorization Code and Revoked Token
  343. commit_code, commit_token = False, False
  344. code_list = frappe.get_all("OAuth Authorization Code", filters={"validity":"Invalid"})
  345. token_list = frappe.get_all("OAuth Bearer Token", filters={"status":"Revoked"})
  346. if len(code_list) > 0:
  347. commit_code = True
  348. if len(token_list) > 0:
  349. commit_token = True
  350. for code in code_list:
  351. frappe.delete_doc("OAuth Authorization Code", code["name"])
  352. for token in token_list:
  353. frappe.delete_doc("OAuth Bearer Token", token["name"])
  354. if commit_code or commit_token:
  355. frappe.db.commit()