When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's
    "deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding
    users as unauthorized.
506593
def deauthorize_application(request):
    
    if request.facebook:
        user = User.objects.get(
            facebook_id = request.facebook.signed_request.user.id
        )

        user.authorized = False
        user.save()

        return HttpResponse()
    else:
        return HttpResponse(status=400)
1127570
private ModelAndView getImplicitGrantResponse(AuthorizationRequest authorizationRequest) {
		try {
			TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, "implicit");
			OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
			OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request);
			if (accessToken == null) {
				throw new UnsupportedResponseTypeException("Unsupported response type: token");
			}
			return new ModelAndView(new RedirectView(appendAccessToken(authorizationRequest, accessToken), false, true,
					false));
		}
		catch (OAuth2Exception e) {
			return new ModelAndView(new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false,
					true, false));
		}
	}
455337
public String blockingIssueAuthorizationCode(HttpRequest req) throws OAuthException {
        AuthRequest authRequest = new AuthRequest(req);
        LOG.info("received client_id:" + authRequest.getClientId());
        if (!isActiveClientId(authRequest.getClientId()).blockingGet()) {
            throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
        }
        authRequest.validate();

        String scope = scopeService.getValidScope(authRequest.getScope(), authRequest.getClientId()).blockingGet();
        if (scope == null) {
            throw new OAuthException(ResponseBuilder.SCOPE_NOK_MESSAGE, HttpResponseStatus.BAD_REQUEST);
        }

        AuthCode authCode = new AuthCode(generateCode(), authRequest.getClientId(), authRequest.getRedirectUri(),
                authRequest.getState(), scope, authRequest.getResponseType(), authRequest.getUserId());
        LOG.info("authCode: {" + authCode.getCode() + "}");
        db.storeAuthCode(authCode).blockingAwait();

        // return redirect URI, append param code=[Authcode]
        QueryStringEncoder enc = new QueryStringEncoder(authRequest.getRedirectUri());
        enc.addParam("code", authCode.getCode());
        return enc.toString();
    }
151457
function performRemove() {
        UserService.remove(vm.user)
          .then(deleteUserSuccess)
          .catch(deleteUserCatch);

        function deleteUserSuccess() {
          Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'});
          vm.showList();
        }

        function deleteUserCatch(err) {
          Toast.show({
            type: 'warn',
            text: 'Error while deleting user ' + vm.displayName,
            link: {state: $state.$current, params: $stateParams}
          });

          if (form && err) {
            form.setResponseErrors(err, vm.errors);
          }
        }
      }
508945
def inactive_response(self, request):
        
        inactive_url = getattr(settings, 'LOGIN_INACTIVE_REDIRECT_URL', '')
        if inactive_url:
            return HttpResponseRedirect(inactive_url)
        else:
            return self.error_to_response(request, {'error': _("This user account is marked as inactive.")})
623750
private function deAuthorize(User $user): void
    {
        $client = new Client;

        $client->delete("https://graph.facebook.com/{$user->id}/permissions",
            [
                'headers' => ['Accept' => 'application/json'],
                'form_params' => [
                    'access_token' => $user->token,
                ],
            ]
        );
    }
42681
public static void removeCurrentAuthentication() {
        RequestContext context = RequestContext.getCurrent();
        if (context != null) {
            removeAuthentication(context.getRequest());
        }
    }
255147
def parse_signed_request
      Rails.logger.info "  Facebook application \"#{fb_app.namespace}\" configuration in use for this request."
      if request_parameter = request.params["signed_request"]
        encoded_signature, encoded_data = request_parameter.split(".")
        decoded_signature = base64_url_decode(encoded_signature)
        decoded_data = base64_url_decode(encoded_data)
        @fbparams = HashWithIndifferentAccess.new(JSON.parse(decoded_data))
        Rails.logger.info "  Facebook Parameters: #{fbparams.inspect}"
      end
    end
420935
function(req, token, refreshToken, profile, done) {
        // asynchronous
        process.nextTick(function() {
            var User = app.userModel;
            // find the user in the database based on their facebook id
            User.findOne({ 'facebook.id' : profile.id }, function(err, user) {

                // if there is an error, stop everything and return that
                // ie an error connecting to the database
                if (err)
                    return done(err);

                // if the user is found, then log them in
                if (user) {
                    if (req.session.reauthenticate) {
                      delete req.session.reauthenticate;
                      req.session.loginTime = new Date();
                    }
                    return done(null, user); // user found, return that user
                } else {
                    // if there is no user found with that facebook id, create them
                    var newUser            = new User();

                    // set all of the facebook information in our user model
                    newUser.facebook.id    = profile.id; // set the users facebook id
                    newUser.facebook.token = token; // we will save the token that facebook provides to the user
                    newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                    newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first

                    //XXX if the user with that email already exists -- associate with facebook (prompt for password?)
                    //XXX need a way for a currently logged in user to login to facebook and associate accounts

                    // save our user to the database
                    newUser.save(function(err) {
                        if (err)
                            return done(err);
                        if (req.session.reauthenticate) {
                          delete req.session.reauthenticate;
                          req.session.loginTime = new Date();
                        }
                        // if successful, return the new user
                        return done(null, newUser);
                    });
                }

            });
        });

    }
1251610
function(id, callback) {
        var self = this;

        var requestOptions = {
            uri: '/images/' + id
        };

        self.authorizedRequest(requestOptions, function(err, res, body) {
            if (err || !body.image) {
                callback(err);
                return;
            }

            callback(err, new rackspace.Image(self, body.image));
        });
    }
764604
def HandleRequest(self, request):
    """"""
    impersonated_username = config.CONFIG["AdminUI.debug_impersonate_user"]
    if impersonated_username:
      logging.info("Overriding user as %s", impersonated_username)
      request.user = config.CONFIG["AdminUI.debug_impersonate_user"]

    if not aff4_users.GRRUser.IsValidUsername(request.user):
      return self._BuildResponse(
          403, dict(message="Invalid username: %s" % request.user))

    try:
      router, method_metadata, args = self._router_matcher.MatchRouter(request)
    except access_control.UnauthorizedAccess as e:
      error_message = str(e)
      logging.exception("Access denied to %s (%s): %s", request.path,
                        request.method, e)

      additional_headers = {
          "X-GRR-Unauthorized-Access-Reason": error_message.replace("\n", ""),
          "X-GRR-Unauthorized-Access-Subject": utils.SmartStr(e.subject)
      }
      return self._BuildResponse(
          403,
          dict(
              message="Access denied by ACL: %s" % error_message,
              subject=utils.SmartStr(e.subject)),
          headers=additional_headers)

    except ApiCallRouterNotFoundError as e:
      error_message = str(e)
      return self._BuildResponse(404, dict(message=error_message))
    except werkzeug_exceptions.MethodNotAllowed as e:
      error_message = str(e)
      return self._BuildResponse(405, dict(message=error_message))
    except Error as e:
      logging.exception("Can't match URL to router/method: %s", e)

      return self._BuildResponse(
          500, dict(message=str(e), traceBack=traceback.format_exc()))

    request.method_metadata = method_metadata
    request.parsed_args = args

    # SetUID() is called here so that ACL checks done by the router do not
    # clash with datastore ACL checks.
    # TODO(user): increase token expiry time.
    token = self.BuildToken(request, 60).SetUID()

    if data_store.AFF4Enabled():
      # TODO:
      # AFF4 edge case: if a user is issuing a request, before they are created
      # using CreateGRRUser (e.g. in E2E tests or with single sign-on),
      # AFF4's ReadGRRUsers will NEVER contain the user, because the creation
      # done in the following lines does not add the user to the /users/
      # collection. Furthermore, subsequent CreateGrrUserHandler calls fail,
      # because the user technically already exists.

      # We send a blind-write request to ensure that the user object is created
      # for a user specified by the username.
      user_urn = rdfvalue.RDFURN("aff4:/users/").Add(request.user)
      # We can't use conventional AFF4 interface, since aff4.FACTORY.Create will
      # create a new version of the object for every call.
      with data_store.DB.GetMutationPool() as pool:
        pool.MultiSet(
            user_urn, {
                aff4_users.GRRUser.SchemaCls.TYPE:
                    [aff4_users.GRRUser.__name__],
                aff4_users.GRRUser.SchemaCls.LAST:
                    [rdfvalue.RDFDatetime.Now().SerializeToDataStore()]
            },
            replace=True)

    if data_store.RelationalDBEnabled():
      data_store.REL_DB.WriteGRRUser(request.user)

    handler = None
    try:
      # ACL checks are done here by the router. If this method succeeds (i.e.
      # does not raise), then handlers run without further ACL checks (they're
      # free to do some in their own implementations, though).
      handler = getattr(router, method_metadata.name)(args, token=token)

      if handler.args_type != method_metadata.args_type:
        raise RuntimeError("Handler args type doesn't match "
                           "method args type: %s vs %s" %
                           (handler.args_type, method_metadata.args_type))

      binary_result_type = (
          api_call_router.RouterMethodMetadata.BINARY_STREAM_RESULT_TYPE)

      if (handler.result_type != method_metadata.result_type and
          not (handler.result_type is None and
               method_metadata.result_type == binary_result_type)):
        raise RuntimeError("Handler result type doesn't match "
                           "method result type: %s vs %s" %
                           (handler.result_type, method_metadata.result_type))

      # HEAD method is only used for checking the ACLs for particular API
      # methods.
      if request.method == "HEAD":
        # If the request would return a stream, we add the Content-Length
        # header to the response.
        if (method_metadata.result_type ==
            method_metadata.BINARY_STREAM_RESULT_TYPE):
          binary_stream = handler.Handle(args, token=token)
          return self._BuildResponse(
              200, {"status": "OK"},
              method_name=method_metadata.name,
              no_audit_log=method_metadata.no_audit_log_required,
              content_length=binary_stream.content_length,
              token=token)
        else:
          return self._BuildResponse(
              200, {"status": "OK"},
              method_name=method_metadata.name,
              no_audit_log=method_metadata.no_audit_log_required,
              token=token)

      if (method_metadata.result_type ==
          method_metadata.BINARY_STREAM_RESULT_TYPE):
        binary_stream = handler.Handle(args, token=token)
        return self._BuildStreamingResponse(
            binary_stream, method_name=method_metadata.name)
      else:
        format_mode = GetRequestFormatMode(request, method_metadata)
        result = self.CallApiHandler(handler, args, token=token)
        rendered_data = self._FormatResultAsJson(
            result, format_mode=format_mode)

        return self._BuildResponse(
            200,
            rendered_data,
            method_name=method_metadata.name,
            no_audit_log=method_metadata.no_audit_log_required,
            token=token)
    except access_control.UnauthorizedAccess as e:
      error_message = str(e)
      logging.warning("Access denied for %s (HTTP %s %s): %s",
                      method_metadata.name, request.method, request.path,
                      error_message)

      additional_headers = {
          "X-GRR-Unauthorized-Access-Reason": error_message.replace("\n", ""),
          "X-GRR-Unauthorized-Access-Subject": utils.SmartStr(e.subject)
      }
      return self._BuildResponse(
          403,
          dict(
              message="Access denied by ACL: %s" % error_message,
              subject=utils.SmartStr(e.subject)),
          headers=additional_headers,
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except api_call_handler_base.ResourceNotFoundError as e:
      error_message = str(e)
      return self._BuildResponse(
          404,
          dict(message=error_message),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except NotImplementedError as e:
      error_message = str(e)
      return self._BuildResponse(
          501,
          dict(message=error_message),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except Exception as e:  # pylint: disable=broad-except
      error_message = str(e)
      logging.exception("Error while processing %s (%s) with %s: %s",
                        request.path, request.method,
                        handler.__class__.__name__, e)
      return self._BuildResponse(
          500,
          dict(message=error_message, traceBack=traceback.format_exc()),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
1037601
function(image, callback) {
        var self = this,
            imageId = image instanceof rackspace.Image ? image.id : image;

        var destroyOptions = {
            method: 'DELETE',
            uri: '/images/' + imageId
        };

        self.authorizedRequest(destroyOptions, function(err, res, body) {
            if (err || res.statusCode !== 204) {
                callback(err);
                return;
            }

            callback(err, true);
        });
    }
429425
function handleUnauthorizedAPIResponse(error) {
    const response = error && error.response;
    const errorStatus = response && response.status;
    const requestUrl = response && response.config && response.config.url;
    const requestIsTokenRefresh = requestUrl === authenticatedAPIClient.refreshAccessTokenEndpoint;

    switch (errorStatus) { // eslint-disable-line default-case
      case 401:
        if (requestIsTokenRefresh) {
          logInfo(`Unauthorized token refresh response from ${requestUrl}. This is expected if the user is not yet logged in.`);
        } else {
          logInfo(`Unauthorized API response from ${requestUrl}`);
        }
        break;
      case 403:
        logInfo(`Forbidden API response from ${requestUrl}`);
        break;
    }

    return Promise.reject(error);
  }
406132
@DELETE
  @Path("{user}")
  public Response deleteUser(@PathParam("user") String username, @HeaderParam("Authorization") @DefaultValue("no token") String auth) throws Exception {
    if(!this.isAuth(auth)) {
      throw new Exception("Unauthorized!");
    }
    if( realm != null ){
      AuthenticationManagerRequest req = new AuthenticationManagerRequest();
      req.setAccountName(username);
      req.setRequestType(RequestType.REMOVE);
      
      sendMessage(req);
      return Response.status(Status.GONE).build();
    }
    return Response.status(Status.NOT_FOUND).build();
  }
1206690
def cleanup_request(request):
        
        for method_type in ('GET', 'PUT', 'POST', 'DELETE'):
            block = getattr(request, method_type, { })

            if True in [ k.startswith("oauth_") for k in block.keys() ]:
                sanitized = block.copy()

                for k in sanitized.keys():
                    if k.startswith("oauth_"):
                        sanitized.pop(k)

                setattr(request, method_type, sanitized)

        return request
95271
def auth_required(self, view):
        

        @functools.wraps(view)
        def decorated(*args, **kwargs):
            log.info("Trying to get access to protected resource: '%s'", view.__name__)
            if request.method == 'POST':
                token = request.form['token']
                if self.development or self.authenticated(token):
                    return view(*args, **kwargs)
                else:
                    log.warning("User has not been authorized to get access to resource: %s", view.__name__)
            else:
                log.warning("Bad request type! Expected 'POST', actual '%s'", request.method)

            return abort(403)

        return decorated
202970
protected String getUserAuthorizationRedirectURL(ProtectedResourceDetails details, OAuthConsumerToken requestToken, String callbackURL) {
		try {
			String baseURL = details.getUserAuthorizationURL();
			StringBuilder builder = new StringBuilder(baseURL);
			char appendChar = baseURL.indexOf('?') < 0 ? '?' : '&';
			builder.append(appendChar).append("oauth_token=");
			builder.append(URLEncoder.encode(requestToken.getValue(), "UTF-8"));
			if (!details.isUse10a()) {
				builder.append('&').append("oauth_callback=");
				builder.append(URLEncoder.encode(callbackURL, "UTF-8"));
			}
			return builder.toString();
		}
		catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e);
		}
	}