def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s"%self.request.url) # access token logger.debug("!!!Entering ACESS_TOKEN_URL") oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: return send_oauth_error(oauth.OAuthError('Invalid request parameters.'), self.response) else: logger.debug("!!!OAuth Params: %s"%oauth_request.parameters) try: # create an access token token = oauth_server.fetch_access_token(oauth_request) if token == None: logger.debug("!!! oauth_server.fetch_access_token returning None") send_oauth_error(oauth.OAuthError("Cannot find corresponding access token."), self.response) return # send okay response self.response.set_status(200, 'OK') # return the token self.response.out.write(token.to_string()) except oauth.OAuthError, err: send_oauth_error(err, self.response)
def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s" % self.request.url) logger.debug("!!!Entering REQUEST_TOKEN_URL") oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: send_oauth_error(oauth.OAuthError('Invalid request parameters.'), self.response) return else: logger.debug("!!!OAuth Params: %s" % oauth_request.parameters) try: # create a request token token = oauth_server.fetch_request_token(oauth_request) # return the token self.response.set_status(200, 'OK') self.response.out.write(token.to_string()) except oauth.OAuthError, err: logger.exception("Error when trying to do a request_token") send_oauth_error(err, self.response) return
def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s"%self.request.url) # user authorization #TODO: put up a screen explaining what this authorization is for before #approving the request_token, and allowing the user to decide if they #want to proceed- now it just approves right away. If the user rejects #the approval , redirect to the callback with an error parameter logger.debug("!!!Entering AUTHORIZATION_URL") # get the request token oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: return send_oauth_error(oauth.OAuthError('Invalid request parameters.'), self.response) else: logger.debug("!!!OAuth Params: %s"%oauth_request.parameters) try: # get the request token token = oauth_server.fetch_request_token(oauth_request) except oauth.OAuthError, err: logger.exception("Failed accessing request token") return send_oauth_error(err, self.response)
def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): oauth_request = get_oauth_request(request) consumer = store.get_consumer( request, oauth_request, oauth_request.get_parameter('oauth_consumer_key')) try: token = store.get_access_token( request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error( Error( _('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) try: parameters = self.validate_token(request, consumer, token) except Error, e: return send_oauth_error(e) if self.resource_name and token.resource.name != self.resource_name: return send_oauth_error( Error(_('You are not allowed to access this resource.'))) elif consumer and token: # Hack request.user = token.user return self.view_func(request, *args, **kwargs)
def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s" % self.request.url) # user authorization #TODO: put up a screen explaining what this authorization is for before #approving the request_token, and allowing the user to decide if they #want to proceed- now it just approves right away. If the user rejects #the approval , redirect to the callback with an error parameter logger.debug("!!!Entering AUTHORIZATION_URL") # get the request token oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: return send_oauth_error( oauth.OAuthError('Invalid request parameters.'), self.response) else: logger.debug("!!!OAuth Params: %s" % oauth_request.parameters) try: # get the request token token = oauth_server.fetch_request_token(oauth_request) except oauth.OAuthError, err: logger.exception("Failed accessing request token") return send_oauth_error(err, self.response)
def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): oauth_request = get_oauth_request(request) consumer = store.get_consumer( request, oauth_request, oauth_request.get_parameter('oauth_consumer_key')) consumer.key = str(consumer.key) consumer.secret = str(consumer.secret) try: token = store.get_access_token( request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) token.key = str(token.key) token.secret = str(token.secret) except InvalidTokenError: return send_oauth_error( Error( _('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) try: parameters = self.validate_token(request, consumer, token) except Error, e: return send_oauth_error(e) if consumer and token: request.user = token.user return self.view_func(request, *args, **kwargs)
def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s" % self.request.url) # access token logger.debug("!!!Entering ACESS_TOKEN_URL") oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: return send_oauth_error( oauth.OAuthError('Invalid request parameters.'), self.response) else: logger.debug("!!!OAuth Params: %s" % oauth_request.parameters) try: # create an access token token = oauth_server.fetch_access_token(oauth_request) if token == None: logger.debug( "!!! oauth_server.fetch_access_token returning None") send_oauth_error( oauth.OAuthError( "Cannot find corresponding access token."), self.response) return # send okay response self.response.set_status(200, 'OK') # return the token self.response.out.write(token.to_string()) except oauth.OAuthError, err: send_oauth_error(err, self.response)
def callback_view(request, **args): d = {} if 'error' in args: d['error'] = args['error'] try: oauth_token = Token.objects.get(key=args['oauth_token']) except AttributeError, e: send_oauth_error(e)
def wrapper(self, *args, **kwargs): if is_valid_request(self.request): try: consumer, token, parameters = validate_token(self.request) if consumer and token: return method(self, *args, **kwargs) except oauth.OAuthError, e: send_oauth_error(e, self.response) return
def wrapper(self,*args,**kwargs): if is_valid_request(self.request): try: consumer, token, parameters = validate_token(self.request) if consumer and token: return method(self,*args,**kwargs) except oauth.OAuthError, e: send_oauth_error(e,self.response) return
def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) if self.resource_name and token.resource.name != self.resource_name: return send_oauth_error(OAuthError(_('You are not allowed to access this resource.'))) elif consumer and token: return self.view_func(request, *args, **kwargs)
def __call__(self, request): if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) # lou w - changed to check token scope and self scope instead of resource if self.scopes and token.scope != self.scopes: return send_oauth_error(OAuthError(_('You are not allowed to access this resource.'))) elif consumer and token: return self.view_func(request, *args, **kwargs)
def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) if self.resource_name and token.resource.name != self.resource_name: return send_oauth_error( OAuthError( _('You are not allowed to access this resource.'))) elif consumer and token: return self.view_func(request, *args, **kwargs)
def callback_view(request, **args): d = {} if "error" in args: d["error"] = args["error"] try: oauth_token = Token.objects.get(key=args["oauth_token"]) except AttributeError as e: send_oauth_error("https" if request.is_secure() else "http", get_current_site(request).domain, e) except Token.DoesNotExist as e: send_oauth_error("https" if request.is_secure() else "http", get_current_site(request).domain, e) d["verifier"] = oauth_token.verifier return render(request, "oauth_verifier_pin.html", d)
def callback_view(request, **args): d = {} if 'error' in args: d['error'] = args['error'] try: oauth_token = Token.objects.get(key=args['oauth_token']) except AttributeError as e: send_oauth_error(e) except Token.DoesNotExist as e: send_oauth_error(e) d['verifier'] = oauth_token.verifier return render(request, 'oauth_verifier_pin.html', d)
def __call__(self, request): if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) # lou w - changed to check token scope and self scope instead of resource if self.scopes and token.scope != self.scopes: return send_oauth_error( OAuthError( _('You are not allowed to access this resource.'))) elif consumer and token: return self.view_func(request, *args, **kwargs)
def callback_view(request, **args): d = {} if 'error' in args: d['error'] = args['error'] try: oauth_token = Token.objects.get(key=args['oauth_token']) except AttributeError as e: send_oauth_error('https' if request.is_secure() else 'http', get_current_site(request).domain, e) except Token.DoesNotExist as e: send_oauth_error('https' if request.is_secure() else 'http', get_current_site(request).domain, e) d['verifier'] = oauth_token.verifier return render(request, 'oauth_verifier_pin.html', d)
def wrapped_view(request, *args, **kwargs): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE try: consumer = store.get_consumer( request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return INVALID_CONSUMER_RESPONSE try: token = store.get_access_token( request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error( oauth.Error( _('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) if not verify_oauth_request(request, oauth_request, consumer, token): return COULD_NOT_VERIFY_OAUTH_REQUEST_RESPONSE if self.scope_name and (not token.scope or token.scope.name != self.scope_name): return INVALID_SCOPE_RESPONSE if token.user: request.user = token.user return view_func(request, *args, **kwargs)
def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ('oauth_callback', )) if missing_params is not None: return missing_params if is_xauth_request(oauth_request): return HttpResponseBadRequest('xAuth not allowed for this method.') try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return INVALID_CONSUMER_RESPONSE if not verify_oauth_request(request, oauth_request, consumer): return COULD_NOT_VERIFY_OAUTH_REQUEST_RESPONSE try: request_token = store.create_request_token( request, oauth_request, consumer, oauth_request['oauth_callback']) except oauth.Error, err: return send_oauth_error(err)
def user_authorization(request, form_class=AuthorizeRequestTokenForm): if 'oauth_token' not in request.REQUEST: return HttpResponseBadRequest('No request token specified.') oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, request.REQUEST['oauth_token']) except InvalidTokenError: logging.info('Oauth error: could not authorize user %s with token %s' % (request.user, request.REQUEST['oauth_token'])) return HttpResponseBadRequest('Invalid request token.') consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) if request.method == 'POST': form = form_class(request.POST) if request.session.get('oauth', '') == request_token.key and form.is_valid(): request.session['oauth'] = '' if form.cleaned_data['authorize_access']: request_token = store.authorize_request_token( request, oauth_request, request_token) args = {'oauth_token': request_token.key} else: args = {'error': _('Access not granted by user.')} if request_token.callback is not None and request_token.callback != OUT_OF_BAND: response = HttpResponseRedirect( '%s&%s' % (request_token.get_callback_url(), urlencode(args))) else: # try to get custom callback view callback_view_str = getattr( settings, OAUTH_CALLBACK_VIEW, 'oauth_provider.views.fake_callback_view') try: callback_view = get_callable(callback_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % callback_view_str response = callback_view(request, **args) else: response = send_oauth_error(oauth.Error(_('Action not allowed.'))) else: # try to get custom authorize view authorize_view_str = getattr( settings, OAUTH_AUTHORIZE_VIEW, 'oauth_provider.views.default_authorize_view') try: authorize_view = get_callable(authorize_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % authorize_view_str params = oauth_request.get_normalized_parameters() # set the oauth flag request.session['oauth'] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ('oauth_callback', )) if missing_params is not None: return missing_params try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: logging.info('Oauth error: invalid consumer: %d' % oauth_request['oauth_consumer_key']) return HttpResponseBadRequest('Invalid Consumer.') if not verify_oauth_request(request, oauth_request, consumer): logging.info('Oauth error: could not verify request') return HttpResponseBadRequest('Could not verify OAuth request.') try: request_token = store.create_request_token( request, oauth_request, consumer, oauth_request['oauth_callback']) except oauth.Error, err: return send_oauth_error(err)
class CheckOAuth(object): """ Class that checks that the OAuth parameters passes the given test, raising an OAuth error otherwise. If the test is passed, the view function is invoked. We use a class here so that we can define __get__. This way, when a CheckOAuth object is used as a method decorator, the view function is properly bound to its instance. """ def __init__(self, request): self.request = request self.view_func = view_func # lou w - name scope instead of resource self.scopes = resource_name update_wrapper(self, request) def __get__(self, obj, cls=None): return CheckOAuth(request) def __call__(self, request): if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) # lou w - changed to check token scope and self scope instead of resource if self.scopes and token.scope != self.scopes: return send_oauth_error( OAuthError( _('You are not allowed to access this resource.'))) elif consumer and token: return self.view_func(request, *args, **kwargs) return send_oauth_error(OAuthError(_('Invalid request parameters.')))
def wrapped_view(request, *args, **kwargs): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return INVALID_CONSUMER_RESPONSE try: token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error(oauth.Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) if not verify_oauth_request(request, oauth_request, consumer, token): return COULD_NOT_VERIFY_OAUTH_REQUEST_RESPONSE if self.scope_name and (not token.scope or token.scope.name != self.scope_name): return INVALID_SCOPE_RESPONSE if token.user: request.user = token.user return view_func(request, *args, **kwargs)
def wrapped_view(request, *args, **kwargs): oauth_request = get_oauth_request(request) scheme = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain if oauth_request is None: return invalid_params_response(scheme, domain) try: consumer = store.get_consumer( request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return INVALID_CONSUMER_RESPONSE try: token = store.get_access_token( request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error('https' if request.is_secure() else 'http', get_current_site(request).domain, oauth.Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) if not verify_oauth_request(request, oauth_request, consumer, token): return could_not_verify_oauth_request_response(scheme, domain) if self.scope_name and (not token.scope or token.scope.name != self.scope_name): return invalid_scope_response(scheme, domain) if token.user: request.user = token.user return view_func(request, *args, **kwargs)
def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): oauth_request = get_oauth_request(request) consumer = store.get_consumer(request, oauth_request, oauth_request.get_parameter('oauth_consumer_key')) try: token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error(Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) try: parameters = self.validate_token(request, consumer, token) except Error, e: return send_oauth_error(e) if self.resource_name and token.resource.name != self.resource_name: return send_oauth_error(Error(_('You are not allowed to access this resource.'))) elif consumer and token: return self.view_func(request, *args, **kwargs)
def handle_request(self, request): # pdb.set_trace() if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) if consumer and token: request["user"] = token.user
class AuthorizeHandler(webapp.RequestHandler): """HTTP request handler with OAuth support.""" def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s" % self.request.url) # user authorization #TODO: put up a screen explaining what this authorization is for before #approving the request_token, and allowing the user to decide if they #want to proceed- now it just approves right away. If the user rejects #the approval , redirect to the callback with an error parameter logger.debug("!!!Entering AUTHORIZATION_URL") # get the request token oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: return send_oauth_error( oauth.OAuthError('Invalid request parameters.'), self.response) else: logger.debug("!!!OAuth Params: %s" % oauth_request.parameters) try: # get the request token token = oauth_server.fetch_request_token(oauth_request) except oauth.OAuthError, err: logger.exception("Failed accessing request token") return send_oauth_error(err, self.response) try: # get the request callback, though there might not be one if this is OAuth 1.0a callback = oauth_server.get_callback(oauth_request) # OAuth 1.0a: this parameter should not be present on this version if token.callback_confirmed: return send_oauth_error( oauth.OAuthError( "Cannot specify oauth_callback at authorization step for 1.0a protocol" ), self.response) if not check_valid_callback(callback): return send_oauth_error( oauth.OAuthError("Invalid callback URL"), self.response) except oauth.OAuthError, err: callback = None
def user_authorization(request): """ The Consumer cannot use the Request Token until it has been authorized by the User. """ oauth_server, oauth_request = initialize_server_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE try: # get the request token token = oauth_server.fetch_request_token(oauth_request) except OAuthError, err: return send_oauth_error(err)
def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): oauth_request = get_oauth_request(request) consumer = store.get_consumer(request, oauth_request, oauth_request.get_parameter('oauth_consumer_key')) consumer.key = str(consumer.key) consumer.secret = str(consumer.secret) try: token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) token.key = str(token.key) token.secret = str(token.secret) except InvalidTokenError: return send_oauth_error(Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) try: parameters = self.validate_token(request, consumer, token) except Error, e: return send_oauth_error(e) if consumer and token: request.user = token.user return self.view_func(request, *args, **kwargs)
def user_authorization(request, form_class=AuthorizeRequestTokenForm): if 'oauth_token' not in request.REQUEST: return HttpResponseBadRequest('No request token specified.') oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, request.REQUEST['oauth_token']) except InvalidTokenError: return HttpResponseBadRequest('Invalid request token.') consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) if request.method == 'POST': form = form_class(request.POST) if request.session.get('oauth', '') == request_token.key and form.is_valid(): request.session['oauth'] = '' if form.cleaned_data['authorize_access']: request_token = store.authorize_request_token(request, oauth_request, request_token) args = { 'oauth_token': request_token } else: args = { 'error': _('Access not granted by user.') } if request_token.callback is not None and request_token.callback != OUT_OF_BAND: response = HttpResponseRedirect(request_token.get_callback_url(args)) else: # try to get custom callback view callback_view_str = getattr(settings, OAUTH_CALLBACK_VIEW, 'oauth_provider.views.fake_callback_view') try: callback_view = get_callable(callback_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % callback_view_str response = callback_view(request, **args) else: response = send_oauth_error(oauth.Error(_('Action not allowed.'))) else: # try to get custom authorize view authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW, 'oauth_provider.views.fake_authorize_view') try: authorize_view = get_callable(authorize_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % authorize_view_str params = oauth_request.get_normalized_parameters() # set the oauth flag request.session['oauth'] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s"%self.request.url) logger.debug("!!!Entering REQUEST_TOKEN_URL") oauth_server, oauth_request = initialize_server_request(self.request) if oauth_server is None: send_oauth_error(oauth.OAuthError('Invalid request parameters.'), self.response) return else: logger.debug("!!!OAuth Params: %s"%oauth_request.parameters) try: # create a request token token = oauth_server.fetch_request_token(oauth_request) # return the token self.response.set_status(200, 'OK') self.response.out.write(token.to_string()) except oauth.OAuthError, err: logger.exception("Error when trying to do a request_token") send_oauth_error(err, self.response) return
def access_token(request): """ The Consumer exchanges the Request Token for an Access Token capable of accessing the Protected Resources. """ oauth_server, oauth_request = initialize_server_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE try: # get the request token token = oauth_server.fetch_access_token(oauth_request) # return the token response = HttpResponse(token.to_string(), mimetype="text/plain") except OAuthError, err: response = send_oauth_error(err)
def __call__(self, request): pdb.set_trace() if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) # Not sure how self.resource_name was being passed...the model class should handle this later # if self.resource_name and token.resource.name != self.resource_name: # return send_oauth_error(OAuthError(_('You are not allowed to access this resource.'))) # elif consumer and token: # return self.view_func(request, *args, **kwargs) if consumer and token: request["user"] = token.user
class CheckOAuth(object): """ Class that checks that the OAuth parameters passes the given test, raising an OAuth error otherwise. If the test is passed, the view function is invoked. We use a class here so that we can define __get__. This way, when a CheckOAuth object is used as a method decorator, the view function is properly bound to its instance. """ def __init__(self, view_func, resource_name): self.view_func = view_func self.resource_name = resource_name update_wrapper(self, view_func) def __get__(self, obj, cls=None): view_func = self.view_func.__get__(obj, cls) return CheckOAuth(view_func, self.resource_name) def __call__(self, request, *args, **kwargs): if self.is_valid_request(request): oauth_request = get_oauth_request(request) consumer = store.get_consumer( request, oauth_request, oauth_request.get_parameter('oauth_consumer_key')) try: token = store.get_access_token( request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error( Error( _('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) try: parameters = self.validate_token(request, consumer, token) except Error, e: return send_oauth_error(e) if self.resource_name and token.resource.name != self.resource_name: return send_oauth_error( Error(_('You are not allowed to access this resource.'))) elif consumer and token: # Hack request.user = token.user return self.view_func(request, *args, **kwargs) return send_oauth_error(Error(_('Invalid request parameters.')))
def request_token(request): """ The Consumer obtains an unauthorized Request Token by asking the Service Provider to issue a Token. The Request Token's sole purpose is to receive User approval and can only be used to obtain an Access Token. """ oauth_server, oauth_request = initialize_server_request(request) if oauth_server is None: return INVALID_PARAMS_RESPONSE try: # create a request token token = oauth_server.fetch_request_token(oauth_request) # return the token response = HttpResponse(token.to_string(), mimetype="text/plain") except OAuthError, err: response = send_oauth_error(err)
def user_authorization(request, form_class=AuthorizeRequestTokenForm): if "oauth_token" not in request.REQUEST: return HttpResponseBadRequest("No request token specified.") oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, request.REQUEST["oauth_token"]) except InvalidTokenError: return HttpResponseBadRequest("Invalid request token.") consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) if request.method == "POST": form = form_class(request.POST) if request.session.get("oauth", "") == request_token.key and form.is_valid(): request.session["oauth"] = "" if form.cleaned_data["authorize_access"]: request_token = store.authorize_request_token(request, oauth_request, request_token) args = {"oauth_token": request_token.key} else: args = {"error": _("Access not granted by user.")} if request_token.callback is not None and request_token.callback != OUT_OF_BAND: response = HttpResponseRedirect("%s&%s" % (request_token.get_callback_url(), urlencode(args))) else: # try to get custom callback view callback_view_str = getattr(settings, OAUTH_CALLBACK_VIEW, "oauth_provider.views.fake_callback_view") try: callback_view = get_callable(callback_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % callback_view_str response = callback_view(request, **args) else: response = send_oauth_error(oauth.Error(_("Action not allowed."))) else: # try to get custom authorize view authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW, "oauth_provider.views.fake_authorize_view") try: authorize_view = get_callable(authorize_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % authorize_view_str params = oauth_request.get_normalized_parameters() # set the oauth flag request.session["oauth"] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ("oauth_callback",)) if missing_params is not None: return missing_params try: consumer = store.get_consumer(request, oauth_request, oauth_request["oauth_consumer_key"]) except InvalidConsumerError: return HttpResponseBadRequest("Invalid Consumer.") if not verify_oauth_request(request, oauth_request, consumer): return HttpResponseBadRequest("Could not verify OAuth request.") try: request_token = store.create_request_token(request, oauth_request, consumer, oauth_request["oauth_callback"]) except oauth.Error, err: return send_oauth_error(err)
def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ('oauth_callback',)) if missing_params is not None: return missing_params try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: logging.info('Oauth error: invalid consumer: %d' % oauth_request['oauth_consumer_key']) return HttpResponseBadRequest('Invalid Consumer.') if not verify_oauth_request(request, oauth_request, consumer): logging.info('Oauth error: could not verify request') return HttpResponseBadRequest('Could not verify OAuth request.') try: request_token = store.create_request_token(request, oauth_request, consumer, oauth_request['oauth_callback']) except oauth.Error, err: return send_oauth_error(err)
def wrapped_view(request, *args, **kwargs): oauth_request = get_oauth_request(request) scheme = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain if oauth_request is None: return invalid_params_response(scheme, domain) try: consumer = store.get_consumer( request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return INVALID_CONSUMER_RESPONSE try: token = store.get_access_token( request, oauth_request, consumer, oauth_request.get_parameter('oauth_token')) except InvalidTokenError: return send_oauth_error( 'https' if request.is_secure() else 'http', get_current_site(request).domain, oauth.Error( _('Invalid access token: %s') % oauth_request.get_parameter('oauth_token'))) if not verify_oauth_request(request, oauth_request, consumer, token): return could_not_verify_oauth_request_response(scheme, domain) if self.scope_name and (not token.scope or token.scope.name != self.scope_name): return invalid_scope_response(scheme, domain) if token.user: request.user = token.user return view_func(request, *args, **kwargs)
def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ('oauth_callback',)) if missing_params is not None: return missing_params if is_xauth_request(oauth_request): return HttpResponseBadRequest('xAuth not allowed for this method.') try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return HttpResponseBadRequest('Invalid Consumer.') if not verify_oauth_request(request, oauth_request, consumer): return HttpResponseBadRequest('Could not verify OAuth request.') try: request_token = store.create_request_token(request, oauth_request, consumer, oauth_request['oauth_callback']) except oauth.Error, err: return send_oauth_error(err)
pdb.set_trace() if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) # Not sure how self.resource_name was being passed...the model class should handle this later # if self.resource_name and token.resource.name != self.resource_name: # return send_oauth_error(OAuthError(_('You are not allowed to access this resource.'))) # elif consumer and token: # return self.view_func(request, *args, **kwargs) if consumer and token: request["user"] = token.user else: return send_oauth_error(OAuthError(_("Invalid request parameters."))) @staticmethod def handle_request(self, request): # pdb.set_trace() if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except OAuthError, e: return send_oauth_error(e) if consumer and token: request["user"] = token.user else: return send_oauth_error(OAuthError(_("Invalid request parameters.")))
elif 'oauth_token' not in request_uri and '?' in request_uri: request_uri = '%s&%s' % (request_uri, token.to_string(only_key=True)) if not token.callback_confirmed and 'oauth_callback' not in request_uri and '?' not in request_uri: request_uri = '%s?oauth_callback=%s' % (request_uri, callback) elif not token.callback_confirmed and 'oauth_callback' not in request_uri and '?' in request_uri: request_uri = '%s&oauth_callback=%s' % (request_uri, callback) self.redirect(users.create_login_url(request_uri)) except oauth.OAuthError, err: logger.exception("Error when trying to do an authorization") send_oauth_error(err, self.response) logger.debug("!!!End request") return def post(self, *args): """Handler method for OAuth POST requests.""" return self.get() class AccessTokenHandler(webapp.RequestHandler): """HTTP request handler with OAuth support.""" def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s" % self.request.url)
def access_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return HttpResponseBadRequest("Invalid request parameters.") # Consumer try: consumer = store.get_consumer(request, oauth_request, oauth_request["oauth_consumer_key"]) except InvalidConsumerError: return HttpResponseBadRequest("Invalid consumer.") is_xauth = is_xauth_request(oauth_request) if not is_xauth: # Check Parameters missing_params = require_params(oauth_request, ("oauth_token", "oauth_verifier")) if missing_params is not None: return missing_params # Check Request Token try: request_token = store.get_request_token(request, oauth_request, oauth_request["oauth_token"]) except InvalidTokenError: return HttpResponse("Invalid request token: %s" % oauth_request["oauth_token"], status=401) if not request_token.is_approved: return HttpResponse("Request Token not approved by the user.", status=401) # Verify Signature if not verify_oauth_request(request, oauth_request, consumer, request_token): return HttpResponseBadRequest("Could not verify OAuth request.") # Check Verifier if oauth_request.get("oauth_verifier", None) != request_token.verifier: return HttpResponseBadRequest("Invalid OAuth verifier.") else: # xAuth # Check Parameters missing_params = require_params(oauth_request, ("x_auth_username", "x_auth_password", "x_auth_mode")) if missing_params is not None: return missing_params # Check if Consumer allows xAuth if not consumer.xauth_allowed: return HttpResponseBadRequest("xAuth not allowed for this method") # Check Signature if not verify_oauth_request(request, oauth_request, consumer): return HttpResponseBadRequest("Could not verify xAuth request.") user = authenticate( x_auth_username=oauth_request.get_parameter("x_auth_username"), x_auth_password=oauth_request.get_parameter("x_auth_password"), x_auth_mode=oauth_request.get_parameter("x_auth_mode"), ) if not user: return HttpResponseBadRequest("xAuth username or password is not valid") else: request.user = user # Handle Request Token try: # request_token = store.create_request_token(request, oauth_request, consumer, oauth_request.get('oauth_callback')) request_token = store.create_request_token(request, oauth_request, consumer, OUT_OF_BAND) request_token = store.authorize_request_token(request, oauth_request, request_token) except oauth.Error as err: return send_oauth_error("https" if request.is_secure() else "http", get_current_site(request).domain, err) access_token = store.create_access_token(request, oauth_request, consumer, request_token) ret = urlencode({"oauth_token": access_token.key, "oauth_token_secret": access_token.secret}) return HttpResponse(ret, content_type="application/x-www-form-urlencoded")
def user_authorization(request, form_class=AuthorizeRequestTokenForm): if request.method.lower() == "get": if "oauth_token" not in request.GET: return HttpResponseBadRequest("No request token specified.") incoming_token = request.GET["oauth_token"] elif request.method.lower() == "post": if "oauth_token" not in request.POST: return HttpResponseBadRequest("No request token specified.") incoming_token = request.POST["oauth_token"] oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, incoming_token) except InvalidTokenError: return HttpResponse("Invalid request token: %s" % incoming_token, status=401) consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER if request.user != consumer.user: return HttpResponseForbidden("Invalid user for this client.") if request.method == "POST": form = form_class(request.POST) if request.session.get("oauth", "") == request_token.key and form.is_valid(): request.session["oauth"] = "" if form.cleaned_data["authorize_access"]: request_token = store.authorize_request_token(request, oauth_request, request_token) args = {"oauth_token": request_token.key} else: args = {"error": _("Access not granted by user.")} if request_token.callback is not None and request_token.callback != OUT_OF_BAND: callback_url = request_token.get_callback_url(args) if UNSAFE_REDIRECTS: response = UnsafeRedirect(callback_url) else: response = HttpResponseRedirect(callback_url) else: # try to get custom callback view callback_view_str = getattr(settings, OAUTH_CALLBACK_VIEW, "oauth_provider.views.fake_callback_view") try: view_callable = get_callable(callback_view_str) except AttributeError: raise Exception("%s view doesn't exist." % callback_view_str) # try to treat it as Class Based View (CBV) try: callback_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV callback_view = view_callable response = callback_view(request, **args) else: response = send_oauth_error( "https" if request.is_secure() else "http", get_current_site(request).domain, oauth.Error(_("Action not allowed.")), ) else: # try to get custom authorize view authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW, "oauth_provider.views.fake_authorize_view") try: view_callable = get_callable(authorize_view_str) except AttributeError: raise Exception("%s view doesn't exist." % authorize_view_str) # try to treat it as Class Based View (CBV) try: authorize_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV authorize_view = view_callable params = oauth_request.get_normalized_parameters() # set the oauth flag request.session["oauth"] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
def user_authorization(request, form_class=AuthClientForm): if 'oauth_token' not in request.REQUEST: return HttpResponseBadRequest('No request token specified.') oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, request.REQUEST['oauth_token']) except InvalidTokenError: return HttpResponse('Invalid request token: %s' % request.REQUEST['oauth_token'], status=401) consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER if request.user != consumer.user: return HttpResponseForbidden('Invalid user for this client.') if request.method == 'POST': form = form_class(request.POST) if request.session.get('oauth', '') == request_token.key and form.is_valid(): request.session['oauth'] = '' if form.cleaned_data['authorize_access']: request_token = store.authorize_request_token(request, oauth_request, request_token) args = { 'oauth_token': request_token.key } else: args = { 'error': _('Access not granted by user.') } if request_token.callback is not None and request_token.callback != OUT_OF_BAND: callback_url = request_token.get_callback_url(args) if UNSAFE_REDIRECTS: response = UnsafeRedirect(callback_url) else: response = HttpResponseRedirect(callback_url) else: # try to get custom callback view callback_view_str = getattr(settings, OAUTH_CALLBACK_VIEW, 'oauth_provider.views.fake_callback_view') try: view_callable = get_callable(callback_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % callback_view_str # try to treat it as Class Based View (CBV) try: callback_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV callback_view = view_callable response = callback_view(request, **args) else: response = send_oauth_error(oauth.Error(_('Action not allowed.'))) else: # try to get custom authorize view authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW, 'oauth_provider.views.fake_authorize_view') try: view_callable = get_callable(authorize_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % authorize_view_str # try to treat it as Class Based View (CBV) try: authorize_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV authorize_view = view_callable params = oauth_request.get_normalized_parameters() # set the oauth flag request.session['oauth'] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from django.utils.translation import ugettext as _ from django.core.urlresolvers import get_callable from decorators import oauth_required from forms import AuthorizeRequestTokenForm from store import store, InvalidConsumerError, InvalidTokenError from utils import verify_oauth_request, get_oauth_request, require_params, send_oauth_error from consts import OUT_OF_BAND OAUTH_AUTHORIZE_VIEW = "OAUTH_AUTHORIZE_VIEW" OAUTH_CALLBACK_VIEW = "OAUTH_CALLBACK_VIEW" INVALID_PARAMS_RESPONSE = send_oauth_error(oauth.Error(_("Invalid request parameters."))) @csrf_exempt def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ("oauth_callback",)) if missing_params is not None: return missing_params try: consumer = store.get_consumer(request, oauth_request, oauth_request["oauth_consumer_key"]) except InvalidConsumerError:
if 'oauth_token' not in request_uri and '?' not in request_uri: request_uri = '%s?%s' % (request_uri,token.to_string(only_key=True)) elif 'oauth_token' not in request_uri and '?' in request_uri: request_uri = '%s&%s' % (request_uri,token.to_string(only_key=True)) if not token.callback_confirmed and 'oauth_callback' not in request_uri and '?' not in request_uri: request_uri = '%s?oauth_callback=%s' % (request_uri,callback) elif not token.callback_confirmed and 'oauth_callback' not in request_uri and '?' in request_uri: request_uri = '%s&oauth_callback=%s' % (request_uri,callback) self.redirect(users.create_login_url(request_uri)) except oauth.OAuthError, err: logger.exception("Error when trying to do an authorization") send_oauth_error(err, self.response) logger.debug("!!!End request") return def post(self, *args): """Handler method for OAuth POST requests.""" return self.get() class AccessTokenHandler(webapp.RequestHandler): """HTTP request handler with OAuth support.""" def get(self, *args): logger.debug("!!!START REQUEST!!!") """Handler method for OAuth GET requests.""" logger.debug("!!!Req URL: %s"%self.request.url)
from django.template import RequestContext from utils import initialize_server_request, send_oauth_error from decorators import oauth_required from stores import check_valid_callback from consts import OUT_OF_BAND from django.utils.decorators import decorator_from_middleware import pdb from django.shortcuts import render_to_response from lrs.forms import AuthClientForm from lrs.models import Token from lrs.util import TCAPIversionHeaderMiddleware OAUTH_AUTHORIZE_VIEW = 'OAUTH_AUTHORIZE_VIEW' OAUTH_CALLBACK_VIEW = 'OAUTH_CALLBACK_VIEW' INVALID_PARAMS_RESPONSE = send_oauth_error(OAuthError( _('Invalid request parameters.'))) def oauth_home(request): rsp = """ <html><head></head><body><h1>Oauth Authorize</h1></body></html>""" return HttpResponse(rsp) def request_token(request): """ The Consumer obtains an unauthorized Request Token by asking the Service Provider to issue a Token. The Request Token's sole purpose is to receive User approval and can only be used to obtain an Access Token. """ # If oauth is not enabled, don't initiate the handshake if settings.OAUTH_ENABLED: oauth_server, oauth_request = initialize_server_request(request)
def user_authorization(request, form_class=AuthorizeRequestTokenForm): if 'oauth_token' not in request.REQUEST: return HttpResponseBadRequest('No request token specified.') oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, request.REQUEST['oauth_token']) except InvalidTokenError: return HttpResponse('Invalid request token: %s' % request.REQUEST['oauth_token'], status=401) consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER if request.user != consumer.user: return HttpResponseForbidden('Invalid user for this client.') if request.method == 'POST': form = form_class(request.POST) if request.session.get('oauth', '') == request_token.key and form.is_valid(): request.session['oauth'] = '' if form.cleaned_data['authorize_access']: request_token = store.authorize_request_token( request, oauth_request, request_token) args = {'oauth_token': request_token.key} else: args = {'error': _('Access not granted by user.')} if request_token.callback is not None and request_token.callback != OUT_OF_BAND: callback_url = request_token.get_callback_url(args) if UNSAFE_REDIRECTS: response = UnsafeRedirect(callback_url) else: response = HttpResponseRedirect(callback_url) else: # try to get custom callback view callback_view_str = getattr( settings, OAUTH_CALLBACK_VIEW, 'oauth_provider.views.fake_callback_view') try: view_callable = get_callable(callback_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % callback_view_str # try to treat it as Class Based View (CBV) try: callback_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV callback_view = view_callable response = callback_view(request, **args) else: response = send_oauth_error(oauth.Error(_('Action not allowed.'))) else: # try to get custom authorize view authorize_view_str = getattr( settings, OAUTH_AUTHORIZE_VIEW, 'oauth_provider.views.fake_authorize_view') try: view_callable = get_callable(authorize_view_str) except AttributeError: raise Exception, "%s view doesn't exist." % authorize_view_str # try to treat it as Class Based View (CBV) try: authorize_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV authorize_view = view_callable params = oauth_request.get_normalized_parameters() # set the oauth flag request.session['oauth'] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from django.utils.translation import ugettext as _ from django.core.urlresolvers import get_callable from decorators import oauth_required from forms import AuthorizeRequestTokenForm from store import store, InvalidConsumerError, InvalidTokenError from utils import verify_oauth_request, get_oauth_request, require_params, send_oauth_error from consts import OUT_OF_BAND OAUTH_AUTHORIZE_VIEW = 'OAUTH_AUTHORIZE_VIEW' OAUTH_CALLBACK_VIEW = 'OAUTH_CALLBACK_VIEW' INVALID_PARAMS_RESPONSE = send_oauth_error(oauth.Error( _('Invalid request parameters.'))) @csrf_exempt def request_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE missing_params = require_params(oauth_request, ('oauth_callback',)) if missing_params is not None: return missing_params try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return HttpResponseBadRequest('Invalid Consumer.')
def user_authorization(request, form_class=AuthorizeRequestTokenForm): if request.method.lower() == 'get': if 'oauth_token' not in request.GET: return HttpResponseBadRequest('No request token specified.') incoming_token = request.GET['oauth_token'] elif request.method.lower() == 'post': if 'oauth_token' not in request.POST: return HttpResponseBadRequest('No request token specified.') incoming_token = request.POST['oauth_token'] oauth_request = get_oauth_request(request) try: request_token = store.get_request_token(request, oauth_request, incoming_token) except InvalidTokenError: return HttpResponse('Invalid request token: %s' % incoming_token, status=401) consumer = store.get_consumer_for_request_token(request, oauth_request, request_token) # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER # CLATOOLKIT CHANGE - MULTIPLE USERS CAN HAVE MULTIPLE CONSUMERS if not consumer.attached_to_user(request.user): return HttpResponseForbidden('Invalid user for this client.') if request.method == 'POST': form = form_class(request.POST) print 'request.session.oauth == request_token.key? %s' % ( request.session.get('oauth', '') == request_token.key) print 'session: %s and request_token: %s' % (request.session.get( 'oauth', ''), request_token.key) print 'form valid? %s' % form.is_valid() if not form.is_valid(): print 'form errors: %s' % form.errors if request.session.get('oauth', '') == request_token.key and form.is_valid(): request.session['oauth'] = '' if form.cleaned_data['authorize_access']: request_token = store.authorize_request_token( request, oauth_request, request_token) args = { 'oauth_token': request_token.key, 'user': request.GET.get('clau', None) } else: args = {'error': _('Access not granted by user.')} print 'callback url: %s' % (request_token.callback) # print 'new callback url: %s' % (request_token.callback) if request_token.callback is not None and request_token.callback != OUT_OF_BAND: callback_url = request_token.get_callback_url(args) #cla-user = request.GET.get('clau', None) #print 'got CLA user: %s' % (cla-user) if UNSAFE_REDIRECTS: response = UnsafeRedirect( callback_url) #+'?user=%s' % cla-user) else: response = HttpResponseRedirect( callback_url) #+'?user=%s' % cla-user) else: print "We're in here..." # try to get custom callback view callback_view_str = getattr( settings, OAUTH_CALLBACK_VIEW, 'oauth_provider.views.fake_callback_view') try: view_callable = get_callable(callback_view_str) except AttributeError: raise Exception("%s view doesn't exist." % callback_view_str) # try to treat it as Class Based View (CBV) try: callback_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV callback_view = view_callable response = callback_view(request, **args) else: response = send_oauth_error( 'https' if request.is_secure() else 'http', get_current_site(request).domain, oauth.Error(_('Action not allowed.'))) else: # try to get custom authorize view authorize_view_str = getattr( settings, OAUTH_AUTHORIZE_VIEW, 'oauth_provider.views.fake_authorize_view') try: view_callable = get_callable(authorize_view_str) except AttributeError: raise Exception("%s view doesn't exist." % authorize_view_str) # try to treat it as Class Based View (CBV) try: authorize_view = view_callable.as_view() except AttributeError: # if it appears not to be CBV treat it like FBV authorize_view = view_callable params = oauth_request.get_normalized_parameters() # set the oauth flag request.session['oauth'] = request_token.key response = authorize_view(request, request_token, request_token.get_callback_url(), params) return response
def access_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return HttpResponseBadRequest('Invalid request parameters.') # Consumer try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return HttpResponseBadRequest('Invalid consumer.') is_xauth = is_xauth_request(oauth_request) if not is_xauth: # Check Parameters missing_params = require_params(oauth_request, ('oauth_token', 'oauth_verifier')) if missing_params is not None: return missing_params # Check Request Token try: request_token = store.get_request_token( request, oauth_request, oauth_request['oauth_token']) except InvalidTokenError: return HttpResponse('Invalid request token: %s' % oauth_request['oauth_token'], status=401) if not request_token.is_approved: return HttpResponse('Request Token not approved by the user.', status=401) # Verify Signature if not verify_oauth_request(request, oauth_request, consumer, request_token): return HttpResponseBadRequest('Could not verify OAuth request.') # Check Verifier if oauth_request.get('oauth_verifier', None) != request_token.verifier: return HttpResponseBadRequest('Invalid OAuth verifier.') else: # xAuth # Check Parameters missing_params = require_params( oauth_request, ('x_auth_username', 'x_auth_password', 'x_auth_mode')) if missing_params is not None: return missing_params # Check if Consumer allows xAuth if not consumer.xauth_allowed: return HttpResponseBadRequest('xAuth not allowed for this method') # Check Signature if not verify_oauth_request(request, oauth_request, consumer): return HttpResponseBadRequest('Could not verify xAuth request.') user = authenticate( x_auth_username=oauth_request.get_parameter('x_auth_username'), x_auth_password=oauth_request.get_parameter('x_auth_password'), x_auth_mode=oauth_request.get_parameter('x_auth_mode')) if not user: return HttpResponseBadRequest( 'xAuth username or password is not valid') else: request.user = user # Handle Request Token try: #request_token = store.create_request_token(request, oauth_request, consumer, oauth_request.get('oauth_callback')) request_token = store.create_request_token(request, oauth_request, consumer, OUT_OF_BAND) request_token = store.authorize_request_token( request, oauth_request, request_token) except oauth.Error, err: return send_oauth_error(err)
'obj_id': token.pk }) d = {} d['form'] = form d['name'] = token.consumer.name d['description'] = token.consumer.description d['params'] = params d['oauth_token'] = token.key return render_to_response('oauth_authorize_client.html', d, context_instance=RequestContext(request)) @login_required(login_url="/accounts/login") def callback_view(request, **args): d = {} if 'error' in args: d['error'] = args['error'] try: oauth_token = Token.objects.get(key=args['oauth_token']) except AttributeError, e: send_oauth_error(e) except Token.DoesNotExist, e: send_oauth_error(e) d['verifier'] = oauth_token.verifier return render_to_response('oauth_verifier_pin.html', d, context_instance=RequestContext(request))
from oauth.oauth import OAuthError from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect from django.utils.translation import ugettext as _ from django.contrib.auth.decorators import login_required from django.core.urlresolvers import get_callable from utils import initialize_server_request, send_oauth_error from decorators import oauth_required from stores import check_valid_callback from consts import OUT_OF_BAND OAUTH_AUTHORIZE_VIEW = 'OAUTH_AUTHORIZE_VIEW' OAUTH_CALLBACK_VIEW = 'OAUTH_CALLBACK_VIEW' INVALID_PARAMS_RESPONSE = send_oauth_error( OAuthError(_('Invalid request parameters.'))) def request_token(request): """ The Consumer obtains an unauthorized Request Token by asking the Service Provider to issue a Token. The Request Token's sole purpose is to receive User approval and can only be used to obtain an Access Token. """ oauth_server, oauth_request = initialize_server_request(request) if oauth_server is None: return INVALID_PARAMS_RESPONSE try: # create a request token token = oauth_server.fetch_request_token(oauth_request) # return the token
def access_token(request): oauth_request = get_oauth_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE # Consumer try: consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key']) except InvalidConsumerError: return HttpResponseBadRequest('Invalid consumer.') is_xauth = is_xauth_request(oauth_request) if not is_xauth: # Check Parameters missing_params = require_params(oauth_request, ('oauth_token', 'oauth_verifier')) if missing_params is not None: return missing_params # Check Request Token try: request_token = store.get_request_token(request, oauth_request, oauth_request['oauth_token']) except InvalidTokenError: return HttpResponseBadRequest('Invalid request token.') if not request_token.is_approved: return HttpResponseBadRequest('Request Token not approved by the user.') # Verify Signature if not verify_oauth_request(request, oauth_request, consumer, request_token): return HttpResponseBadRequest('Could not verify OAuth request.') # Check Verifier if oauth_request.get('oauth_verifier', None) != request_token.verifier: return HttpResponseBadRequest('Invalid OAuth verifier.') else: # xAuth # Check Parameters missing_params = require_params(oauth_request, ('x_auth_username', 'x_auth_password', 'x_auth_mode')) if missing_params is not None: return missing_params # Check if Consumer allows xAuth if not consumer.xauth_allowed: return HttpResponseBadRequest('xAuth not allowed for this method') # Check Signature if not verify_oauth_request(request, oauth_request, consumer): return HttpResponseBadRequest('Could not verify xAuth request.') # Check Username/Password if is_xauth and not verify_xauth_request(request, oauth_request): return HttpResponseBadRequest('xAuth username or password is not valid') # Handle Request Token try: #request_token = store.create_request_token(request, oauth_request, consumer, oauth_request.get('oauth_callback')) request_token = store.create_request_token(request, oauth_request, consumer, OUT_OF_BAND) request_token = store.authorize_request_token(request, oauth_request, request_token) except oauth.Error, err: return send_oauth_error(err)