Expects an exception with an authorization_paramaters field in its raw_json
908
def session_hook(exception):
    
    safeprint(
        "The resource you are trying to access requires you to "
        "re-authenticate with specific identities."
    )

    params = exception.raw_json["authorization_parameters"]
    message = params.get("session_message")
    if message:
        safeprint("message: {}".format(message))

    identities = params.get("session_required_identities")
    if identities:
        id_str = " ".join(identities)
        safeprint(
            "Please run\n\n"
            "    globus session update {}\n\n"
            "to re-authenticate with the required identities".format(id_str)
        )
    else:
        safeprint(
            'Please use "globus session update" to re-authenticate '
            "with specific identities".format(id_str)
        )

    exit_with_mapped_status(exception.http_status)
763676
public static function convert(Throwable $throwable): ?JsonApiException
    {
        $converted = null;

        if ($throwable instanceof AuthorizationException) {
            $httpCode  = 403;
            $action    = $throwable->getAction();
            $errors    = (new ErrorCollection())
                ->addDataError(
                    'Unauthorized',
                    "You are not unauthorized for action `$action`.",
                    null,
                    null,
                    null,
                    $httpCode
                );
            $converted = new JsonApiException($errors, $httpCode, $throwable);
        } elseif ($throwable instanceof AuthenticationException) {
            $httpCode  = 401;
            $errors    = (new ErrorCollection())
                ->addDataError(
                    'Authentication failed',
                    'Authentication failed',
                    null,
                    null,
                    null,
                    $httpCode
                );
            $converted = new JsonApiException($errors, $httpCode, $throwable);
        }

        return $converted;
    }
136585
private String getMemberAsString(JsonObject obj, String memberName, String defaultValue) {
        try {
     	   JsonPrimitive value = obj.getAsJsonPrimitive(memberName);

	        if (value != null) {
	            return value.getAsString();
	        }
	        return defaultValue;
	        
        } catch (ClassCastException | IllegalStateException e) {
            throw new JsonParseException("Not a JSON string", e);
        }
    }
1367656
public JSONObject insert(Map<String, String> params) throws Exception {
		OperationAccess operationAccess = tableSchema.getInsertAccess();
		if( false == operationAccess.isAllowed() ) {
			throw new Exception("Attempting to insert a record while the privilege is not allowed: "+tableSchema.getLogicalName()+" ("+tableSchema.getPhysicalName()+")");
		}
		
		// Create a list of parameters to retrieve the row after it is
		// inserted
		List<RecordSelector> whereClauses = new Vector<RecordSelector>();

		// Create a list of all writable columns where a value is specified in
		// the parameters
		List<ColumnData> columnsWithParam = new Vector<ColumnData>();
		for(String columnName : params.keySet()) {
			ColumnData columnData = tableSchema.getColumnFromName(columnName);
			
			if( null != columnData && false == columnData.isWriteable() ) {
				columnData = null;
			}
			if( null != columnData && columnData.isAutoIncrementInteger() ) {
				columnData = null;
			}
			
			if( null == columnData ) {
				throw new Exception("No write access to column "+columnName+" in table "+tableSchema.getLogicalName()+" ("+tableSchema.getPhysicalName()+")");
			} else {
				columnsWithParam.add(columnData);
			}
		}
		
		// Get all columns that are auto fill
		List<ColumnData> autoIncrementIntegerColumns = new Vector<ColumnData>();
		for( ColumnData columnData : tableSchema.getColumns() ) {
			if( columnData.isAutoIncrementInteger() ) {
				autoIncrementIntegerColumns.add(columnData);
			}
		}
		
		// Get all columns that are assigned a value on insert
		List<ColumnData> valueAssignedColumns = new Vector<ColumnData>();
		for( ColumnData columnData : tableSchema.getColumns() ) {
			if( null != columnData.getAssignValueOnInsert() ) {
				valueAssignedColumns.add(columnData);
			} else if( null != columnData.getAssignVariableOnInsert() ) {
				valueAssignedColumns.add(columnData);
			}
		}
		
		// Sort according to column name. This offers greater reusability
		// of the prepared statement.
		Collections.sort(autoIncrementIntegerColumns,new ColumnDataComparator());
		Collections.sort(columnsWithParam,new ColumnDataComparator());
		Collections.sort(valueAssignedColumns,new ColumnDataComparator());
		
		// Obtain all auto increment integers
		List<Integer> autoIncrementIntegerValues = new Vector<Integer>();
		for( ColumnData autoIncrementIntegerColumn : autoIncrementIntegerColumns ) {
			int nextValue = ColumnDataUtils.obtainNextIncrementInteger(connection, autoIncrementIntegerColumn);
			Integer value = new Integer(nextValue);
			autoIncrementIntegerValues.add( value );
			whereClauses.add(
				new RecordSelectorComparison(
					autoIncrementIntegerColumn.getColumnName()
					,RecordSelectorComparison.Comparison.EQUAL
					,new ExpressionConstantImpl(value.toString()) ) );
		}
		
		// Create SQL command
		String sqlQuery = null;
		PreparedStatement pstmt = null;
		{
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			pw.print("INSERT INTO ");
			pw.print(tableSchema.getPhysicalName());
			pw.print(" (");
			boolean first = true;
			for(ColumnData columnData : autoIncrementIntegerColumns) {
				if( first ) {
					first = false;
				} else {
					pw.print(",");
				}
				pw.print(columnData.getColumnName());
			}
			for(ColumnData columnData : columnsWithParam) {
				if( first ) {
					first = false;
				} else {
					pw.print(",");
				}
				pw.print(columnData.getColumnName());
			}
			for(ColumnData columnData : valueAssignedColumns) {
				if( first ) {
					first = false;
				} else {
					pw.print(",");
				}
				pw.print(columnData.getColumnName());
			}
			pw.print(") VALUES (");
			first = true;
			for(ColumnData columnData : autoIncrementIntegerColumns) {
				if( first ) {
					first = false;
				} else {
					pw.print(",");
				}
				pw.print(columnData.getInsertWildcard());
			}
			for(ColumnData columnData : columnsWithParam) {
				if( first ) {
					first = false;
				} else {
					pw.print(",");
				}
				pw.print(columnData.getInsertWildcard());
			}
			for(ColumnData columnData : valueAssignedColumns) {
				if( first ) {
					first = false;
				} else {
					pw.print(",");
				}
				pw.print(columnData.getInsertWildcard());
			}
			pw.print(");");
			pw.flush();
			
			sqlQuery = sw.toString();
			pstmt = connection.prepareStatement(sqlQuery);
			
			// Populate prepared statement
			int index = 1;
			for(Integer integerValue : autoIncrementIntegerValues) {
				pstmt.setInt(index, integerValue.intValue());
				
				++index;
			}
			for(ColumnData columnData : columnsWithParam) {
				// Compute value
				String value = params.get(columnData.getColumnName());
				
				ColumnDataUtils.writeToPreparedStatement(pstmt, index, value, columnData.getColumnType());
				
				++index;
			}
			for(ColumnData columnData : valueAssignedColumns) {
				String value = columnData.getAssignValueOnInsert();
				if( null == value && null != columnData.getAssignVariableOnInsert() ) {
					value = variables.getVariableValue( columnData.getAssignVariableOnInsert() );
				}
				ColumnDataUtils.writeToPreparedStatement(pstmt, index, value, columnData.getColumnType());
				
				++index;
			}
		}
		
		// If there are no selector, there is no point in inserting the data since
		// we will not be able to retrieve it
		if( whereClauses.size() < 1 ) {
			throw new Exception("Refusing to insert data since it can not be selected: "+sqlQuery);
		}
		
		// Execute insert
		pstmt.execute();

		// Now, we need to retrieve the object
		JSONArray array = query(whereClauses, null, null,null,null,null);
		
		// In INSERT, we expect only one element in array
		if( 1 != array.length() ) {
			throw new Exception("Expected only one element returned in an INSERT. Returned size:"+array.length()+" sql: "+sqlQuery);
		}
		
		return array.getJSONObject(0);
	}
738931
def read(self, entity=None, attrs=None, ignore=None, params=None):
        
        if attrs is None:
            attrs = self.update_json([])
        if ignore is None:
            ignore = set()
        ignore.add('account_password')
        return super(AuthSourceLDAP, self).read(entity, attrs, ignore, params)
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);
  }
531705
function validateParams (params) {
  if (!params) {
    throw new Error('Transloadit: The `params` option is required.')
  }

  if (typeof params === 'string') {
    try {
      params = JSON.parse(params)
    } catch (err) {
      // Tell the user that this is not an Uppy bug!
      err.message = 'Transloadit: The `params` option is a malformed JSON string: ' +
        err.message
      throw err
    }
  }

  if (!params.auth || !params.auth.key) {
    throw new Error('Transloadit: The `params.auth.key` option is required. ' +
      'You can find your Transloadit API key at https://transloadit.com/account/api-settings.')
  }
}
896760
async function parseDocument(rawData) {
  try {
    const api = utils.unthrowableParseJson(rawData) || SwaggerParser.YAML.parse(rawData);
    if (!api) {
      return null;
    }

    // Await here so we catch any exceptions
    return await SwaggerParser.validate(api);
  } catch (err) {
    return null;
  }
}
511379
def request(verb, path, raw: false, params: {}, **options)
      # Make sure @access is populated by a valid access
      ensure_access_is_valid
      # Setup base API params and make request
      api_params = { api_type: 'json', raw_json: 1 }.merge(params)

      # This loop is retried @max_retries number of times until it succeeds
      handle_retryable_errors do
        response = @rate_limiter.after_limit { super(verb, path, params: api_params, **options) }
        # Raise errors if encountered at the API level.
        response_error = @error_handler.check_error(response, raw: raw)
        raise response_error unless response_error.nil?
        # All done, return the response
        response
      end
    end
23027
private Object decrypt(JsonObject object, String providerName) throws Exception {
        Object decrypted;

        String key = object.getString("kid");
        String alg = object.getString("alg");

        CryptoProvider provider = this.cryptoManager.getProvider(providerName);

        if (!provider.checkAlgorithmNameMatch(alg)) {
            cryptoManager.throwMissingPublicKeyEx(providerName);
        }

        if (!key.contentEquals(provider.getKeyStoreProvider().publicKeyName())) {
            cryptoManager.throwMissingPublicKeyEx(providerName);
        }

        byte[] encryptedBytes;
        String encryptedValueWithConfig;

        if (object.containsKey("iv")) {
            encryptedValueWithConfig = object.getString("kid") + object.getString("alg")
                    + object.getString("iv") + object.getString("ciphertext");

            byte[] encrypted = Base64.decode(object.getString("ciphertext"));
            byte[] iv = Base64.decode(object.getString("iv"));
            encryptedBytes = new byte[iv.length + encrypted.length];
            System.arraycopy(iv, 0, encryptedBytes, 0, iv.length);
            System.arraycopy(encrypted, 0, encryptedBytes, iv.length, encrypted.length);
        } else {
            encryptedValueWithConfig = object.getString("kid") + object.getString("alg")
                    + object.getString("ciphertext");
            encryptedBytes = Base64.decode(object.getString("ciphertext"));
        }

        if (object.containsKey("sig")) {
            byte[] signature = Base64.decode(object.getString("sig"));

            if (!provider.verifySignature(encryptedValueWithConfig.getBytes(), signature)) {
                cryptoManager.throwSigningFailedEx(providerName);
            }
        }

        byte[] decryptedBytes = provider.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes, Charset.forName("UTF-8"));
        decrypted = JacksonTransformers.MAPPER.readValue(decryptedString, Object.class);
        if (decrypted instanceof Map) {
            decrypted = JsonObject.from((Map<String, ?>) decrypted);
        } else if (decrypted instanceof List) {
            decrypted = JsonArray.from((List<?>) decrypted);
        }
        return decrypted;
    }
735533
public static RegistrationRequest fromJson(Map<String, Object> raw) throws JsonException {
    // If we could, we'd just get Json to coerce this for us, but that would lead to endless
    // recursion as the first thing it would do would be to call this very method. *sigh*
    Json json = new Json();
    RegistrationRequest request = new RegistrationRequest();

    if (raw.get("name") instanceof String) {
      request.name = (String) raw.get("name");
    }

    if (raw.get("description") instanceof String) {
      request.description = (String) raw.get("description");
    }

    if (raw.get("configuration") instanceof Map) {
      // This is nasty. Look away now!
      String converted = json.toJson(raw.get("configuration"));
      request.configuration = GridConfiguredJson.toType(converted, GridNodeConfiguration.class);
    }
    
    if (raw.get("configuration") instanceof GridNodeConfiguration) {
      request.configuration = (GridNodeConfiguration)raw.get("configuration");
    }

    return request;
  }
1228192
function defaultJsonResponse(req, res) {
  res.json({
    account: helpers.strippedAccount(req.user)
  });
}
1040974
function serializationError(msg, obj, fields) {
  var details = [];
  var i, l, field;
  for (i = 0, l = fields.length; i < l; i++) {
    field = fields[i];
    field.type.isValid(obj[field.name], {errorHook: errorHook});
  }
  var detailsStr = details
    .map(function (obj) {
      return f('%s = %j but expected %s', obj.path, obj.value, obj.type);
    })
    .join(', ');
  var err = new Error(f('%s (%s)', msg, detailsStr));
  err.details = details;
  return err;

  function errorHook(parts, any, type) {
    var strs = [];
    var i, l, part;
    for (i = 0, l = parts.length; i < l; i++) {
      part = parts[i];
      if (isNaN(part)) {
        strs.push('.' + part);
      } else {
        strs.push('[' + part + ']');
      }
    }
    details.push({
      path: field.name + strs.join(''),
      value: any,
      type: type
    });
  }
}
71530
public function validateWebhookNotification($json_data) {
        // validate vars
        if (!strlen($json_data['apiToken'])) { throw new AuthorizationException("API token not found"); }
        if ($json_data['apiToken'] != $this->api_token) { throw new AuthorizationException("Invalid API token"); }
        if (!strlen($json_data['signature'])) { throw new AuthorizationException("signature not found"); }
        $notification_json_string = $json_data['payload'];
        if (!strlen($notification_json_string)) { throw new AuthorizationException("payload not found"); }

        // check signature
        $expected_signature = hash_hmac('sha256', $notification_json_string, $this->api_scret_key, false);
        $is_valid = ($expected_signature === $json_data['signature']);
        if (!$is_valid) { throw new AuthorizationException("Invalid signature"); }

        // this will always be true
        //   otherwise an exception will be thrown by now
        return $is_valid;
    }
434744
def json(self, **kwargs):
        
        try:
            return super(ScraperResponse, self).json(**kwargs)
        except ValueError as ve:
            raise ParseException(ve)
995650
function() {
    var a, auth, auths, code, contentTypeModel, isMethodSubmissionSupported, k, key, l, len, len1, len2, len3, len4, m, modelAuths, n, o, p, param, q, ref, ref1, ref2, ref3, ref4, ref5, responseContentTypeView, responseSignatureView, schema, schemaObj, scopeIndex, signatureModel, statusCode, successResponse, type, v, value, produces, isXML, isJSON;
    isMethodSubmissionSupported = jQuery.inArray(this.model.method, this.model.supportedSubmitMethods()) >= 0;
    if (!isMethodSubmissionSupported) {
      this.model.isReadOnly = true;
    }
    this.model.description = this.model.description || this.model.notes;
    this.model.oauth = null;
    modelAuths = this.model.authorizations || this.model.security;
    if (modelAuths) {
      if (Array.isArray(modelAuths)) {
        for (l = 0, len = modelAuths.length; l < len; l++) {
          auths = modelAuths[l];
          for (key in auths) {
            for (a in this.auths) {
              auth = this.auths[a];
              if (key === auth.name) {
                if (auth.type === 'oauth2') {
                  this.model.oauth = {};
                  this.model.oauth.scopes = [];
                  ref1 = auth.value.scopes;
                  for (k in ref1) {
                    v = ref1[k];
                    scopeIndex = auths[key].indexOf(k);
                    if (scopeIndex >= 0) {
                      o = {
                        scope: k,
                        description: v
                      };
                      this.model.oauth.scopes.push(o);
                    }
                  }
                }
              }
            }
          }
        }
      } else {
        for (k in modelAuths) {
          v = modelAuths[k];
          if (k === 'oauth2') {
            if (this.model.oauth === null) {
              this.model.oauth = {};
            }
            if (this.model.oauth.scopes === void 0) {
              this.model.oauth.scopes = [];
            }
            for (m = 0, len1 = v.length; m < len1; m++) {
              o = v[m];
              this.model.oauth.scopes.push(o);
            }
          }
        }
      }
    }
    if (typeof this.model.responses !== 'undefined') {
      this.model.responseMessages = [];
      ref2 = this.model.responses;
      for (code in ref2) {
        value = ref2[code];
        schema = null;
        schemaObj = this.model.responses[code].schema;
        if (schemaObj && schemaObj.$ref) {
          schema = schemaObj.$ref;
          if (schema.indexOf('#/definitions/') !== -1) {
            schema = schema.replace(/^.*#\/definitions\//, '');
          }
        }
        this.model.responseMessages.push({
          code: code,
          message: value.description,
          responseModel: schema,
          headers: value.headers,
          schema: schemaObj
        });
      }
    }
    if (typeof this.model.responseMessages === 'undefined') {
      this.model.responseMessages = [];
    }
    signatureModel = null;
    produces = this.model.produces;
    isXML = this.contains(produces, 'xml');
    isJSON = isXML ? this.contains(produces, 'json') : true;

    if (this.model.successResponse) {
      successResponse = this.model.successResponse;
      for (key in successResponse) {
        value = successResponse[key];
        this.model.successCode = key;
        if (typeof value === 'object' && typeof value.createJSONSample === 'function') {
          this.model.successDescription = value.description;
          this.model.headers = this.parseResponseHeaders(value.headers);
          signatureModel = {
            sampleJSON: isJSON ? JSON.stringify(SwaggerUi.partials.signature.createJSONSample(value), void 0, 2) : false,
            isParam: false,
            sampleXML: isXML ? SwaggerUi.partials.signature.createXMLSample(value.name, value.definition, value.models) : false,
            signature: SwaggerUi.partials.signature.getModelSignature(value.name, value.definition, value.models, value.modelPropertyMacro)
          };
        } else {
          signatureModel = {
            signature: SwaggerUi.partials.signature.getPrimitiveSignature(value)
          };
        }
      }
    } else if (this.model.responseClassSignature && this.model.responseClassSignature !== 'string') {
      signatureModel = {
        sampleJSON: this.model.responseSampleJSON,
        isParam: false,
        signature: this.model.responseClassSignature
      };
    }
    $(this.el).html(Handlebars.templates.operation(this.model));
    if (signatureModel) {
      signatureModel.defaultRendering = this.model.defaultRendering;
      responseSignatureView = new SwaggerUi.Views.SignatureView({
        model: signatureModel,
        router: this.router,
        tagName: 'div'
      });
      $('.model-signature', $(this.el)).append(responseSignatureView.render().el);
    } else {
      this.model.responseClassSignature = 'string';
      $('.model-signature', $(this.el)).html(this.model.type);
    }
    contentTypeModel = {
      isParam: false
    };
    contentTypeModel.consumes = this.model.consumes;
    contentTypeModel.produces = this.model.produces;
    ref3 = this.model.parameters;
    for (n = 0, len2 = ref3.length; n < len2; n++) {
      param = ref3[n];
      type = param.type || param.dataType || '';
      if (typeof type === 'undefined') {
        schema = param.schema;
        if (schema && schema.$ref) {
          ref = schema.$ref;
          if (ref.indexOf('#/definitions/') === 0) {
            type = ref.substring('#/definitions/'.length);
          } else {
            type = ref;
          }
        }
      }
      if (type && type.toLowerCase() === 'file') {
        if (!contentTypeModel.consumes) {
          contentTypeModel.consumes = 'multipart/form-data';
        }
      }
      param.type = type;
    }
    responseContentTypeView = new SwaggerUi.Views.ResponseContentTypeView({
      model: contentTypeModel,
      router: this.router
    });
    $('.response-content-type', $(this.el)).append(responseContentTypeView.render().el);
    ref4 = this.model.parameters;
    for (p = 0, len3 = ref4.length; p < len3; p++) {
      param = ref4[p];
      this.addParameter(param, contentTypeModel.consumes);
    }
    ref5 = this.model.responseMessages;
    for (q = 0, len4 = ref5.length; q < len4; q++) {
      statusCode = ref5[q];
      statusCode.isXML = isXML;
      statusCode.isJSON = isJSON;
      if (!_.isUndefined(statusCode.headers)) {
        statusCode.headers = this.parseHeadersType(statusCode.headers);
      }
      this.addStatusCode(statusCode);
    }

    if (Array.isArray(this.model.security)) {
      var authsModel = SwaggerUi.utils.parseSecurityDefinitions(this.model.security);

      authsModel.isLogout = !_.isEmpty(window.swaggerUi.api.clientAuthorizations.authz);
      this.authView = new SwaggerUi.Views.AuthButtonView({
        data: authsModel,
        router: this.router,
        isOperation: true,
        model: {
          scopes: authsModel.scopes
        }
      });
      this.$('.authorize-wrapper').append(this.authView.render().el);
    }

    this.showSnippet();
    return this;
  }
868151
@GET
  public Response getConfigurableUsers(@HeaderParam("Authorization") @DefaultValue("no token") String auth) throws Exception {
    if(!this.isAuth(auth)) {
      throw new Exception("Unauthorized!");
    }
    if( realm != null ) {
      List<String> usernames = new ArrayList<String>();
      usernames = realm.listUsers();
      return Response.ok(new Gson().toJson(usernames), MediaType.APPLICATION_JSON).build();
    }
    return Response.status(Status.NOT_FOUND).build();
  }