methods declared in OAuthSupport interface
765526
@Override
    public synchronized void setOAuthConsumer(String consumerKey, String consumerSecret) {
        if (null == consumerKey) {
            throw new NullPointerException("consumer key is null");
        }
        if (null == consumerSecret) {
            throw new NullPointerException("consumer secret is null");
        }
        if (auth instanceof NullAuthorization) {
            if (conf.isApplicationOnlyAuthEnabled()) {
                OAuth2Authorization oauth2 = new OAuth2Authorization(conf);
                oauth2.setOAuthConsumer(consumerKey, consumerSecret);
                auth = oauth2;
            } else {
                OAuthAuthorization oauth = new OAuthAuthorization(conf);
                oauth.setOAuthConsumer(consumerKey, consumerSecret);
                auth = oauth;
            }
        } else if (auth instanceof BasicAuthorization) {
            XAuthAuthorization xauth = new XAuthAuthorization((BasicAuthorization) auth);
            xauth.setOAuthConsumer(consumerKey, consumerSecret);
            auth = xauth;
        } else if (auth instanceof OAuthAuthorization || auth instanceof OAuth2Authorization) {
            throw new IllegalStateException("consumer key/secret pair already set.");
        }
    }
563926
private function onAuthenticateHandler($authMethod, $authMethodInfo, Realm $realm, Session $session, AuthenticateMessage $msg)
    {

        $onAuthenticateSuccess = function ($res) use ($realm, $session) {

            if (count($res) < 1) {
                $session->abort(new \stdClass(), 'thruway.error.authentication_failure');

                return;
            }

            // we should figure out a way to have the router send the welcome
            // message so that the roles and extras that go along with it can be
            // filled in
            if ($res[0] === 'SUCCESS') {
                $this->sendWelcomeMessage($session, $res[1]);
            } elseif (isset($res[0]) && $res[0] === 'FAILURE') {
                $this->abortSessionUsingResponse($session, $res);
            } else {
                $session->abort(new \stdClass(), 'thruway.error.authentication_failure');
            }
        };

        $onAuthenticateError = function () use ($session) {
            Logger::error($this, 'onauthenticate rejected the promise');
            $session->abort(new \stdClass(), 'thruway.error.unknown');
        };

        $extra                    = new \stdClass();
        $extra->challenge_details = $session->getAuthenticationDetails()->getChallengeDetails();

        $arguments                = new \stdClass();
        $arguments->extra         = $extra;
        $arguments->authid        = $session->getAuthenticationDetails()->getAuthId();
        $arguments->challenge     = $session->getAuthenticationDetails()->getChallenge();
        $arguments->signature     = $msg->getSignature();
        $arguments->authmethod    = $authMethod;
        $arguments->hello_message = $session->getHelloMessage();

        // now we send our authenticate information to the RPC
        $onAuthenticateHandler = $authMethodInfo['handlers']->onauthenticate;

        $this->session->call($onAuthenticateHandler, [$arguments])
            ->then($onAuthenticateSuccess, $onAuthenticateError);

    }
1283905
function OauthAuthMethods(models) {
      this.models = models;
      this.exchangeRefreshTokenForAccessToken = __bind(this.exchangeRefreshTokenForAccessToken, this);
      this.exchangeAuthorizationCodeForAccessToken = __bind(this.exchangeAuthorizationCodeForAccessToken, this);
      this.createTokenForUserId = __bind(this.createTokenForUserId, this);
      this.createOrReuseTokenForUserId = __bind(this.createOrReuseTokenForUserId, this);
      this.createAccessGrant = __bind(this.createAccessGrant, this);
      this.validate = __bind(this.validate, this);
      this.appForClientId = __bind(this.appForClientId, this);
      this.currentDateAndSeconds = __bind(this.currentDateAndSeconds, this);
      if (!this.models) {
        throw new Error("models parameter is required");
      }
    }
1146237
function initMethod(method, id) {

    function getNamespace(type) {
      return type.split('.').reduce(function(ns, name) {
        if (!ns[name]) {
          // Create missing namespaces.
          ns[name] = {};
        }
        return ns[name];
      }, global);
    }

    function canNotify(self, args) {
      var wasNotified = method.message in encountered, check;
      check = (!method.suppressed) &&
              (!optionUnique() || !wasNotified) &&
              (!method.check || method.check.apply(self, args));
      if (check) {
        encountered[method.message] = true;
      }
      return check;
    }

    function wrapMethod(target, name) {
      var fn = target[name];
      function withSugarNotification() {
        var message = method.message, result;

        function exec(self, args) {
          if (!fn) {
            var targetName = method.type + (self === target ? '' : '.prototype');
            throw new Error(['Method', name, 'does not exist on', targetName].join(' '));
          }
          return fn.apply(self, args);
        }

        if (method.call) {
          message = message.replace(/%.+%/g, method.call.apply(this, arguments));
        }

        if (!isNotifying && canNotify(this, arguments, id)) {
          // Preventing nested notifications means that we don't have to
          // worry about detecting Sugar in the call stack as any call other
          // than the main entry point must be Sugar calling itself.
          if (fn && fn.name !== 'withSugarNotification') {
            // Prevent internal Sugar calls from triggering notifications,
            // but only if methods are not multi-wrapped.
            isNotifying = true;
          }
          notify(message, method);
          result = exec(this, arguments);
          isNotifying = false;
          return result;
        }
        return exec(this, arguments);
      }
      if (method.check === 'missing') {
        if (fn) {
          method.check = function() {
            return false;
          };
        } else {
          delete method.check;
        }
      }
      target[name] = withSugarNotification;
    }

    function wrapProp(target) {
      var val = target[method.prop];
      Object.defineProperty(target, method.prop, {
        get: function() {
          notify(method.message, method);
          return val;
        },
        set: function(newVal) {
          notify(method.message, method);
          val = newVal;
        }
      });
    }

    var ns = getNamespace(method.type);

    if (method.sName) {
      method.sName.split(',').forEach(function(name) {
        wrapMethod(ns, name);
      });
    }
    if (method.iName) {
      method.iName.split(',').forEach(function(name) {
        wrapMethod(ns.prototype, name);
      });
    }
    if (method.prop && DEFINE_PROPERTY_SUPPORT) {
      wrapProp(ns);
    }

    method.clean = method.message.replace(/%/g, '');
    method.id = id;
    method.pid = pad(id, 2, true);
  }
1035752
public static ApiDynamicActionImplementor getSetCredentialsForUserApiAction(
			final AuthenticationMethodType methodType) {
		return new ApiDynamicActionImplementor(ACTION_SET_CREDENTIALS, new String[] { PARAM_USERNAME,
				PARAM_PASSWORD }, null) {

			@Override
			public void handleAction(JSONObject params) throws ApiException {
				Context context = ApiUtils.getContextByParamId(params, UsersAPI.PARAM_CONTEXT_ID);
				int userId = ApiUtils.getIntParam(params, UsersAPI.PARAM_USER_ID);
				// Make sure the type of authentication method is compatible
				if (!methodType.isTypeForMethod(context.getAuthenticationMethod()))
					throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER,
							"User's credentials should match authentication method type of the context: "
									+ context.getAuthenticationMethod().getType().getName());

				// NOTE: no need to check if extension is loaded as this method is called only if
				// the Users
				// extension is loaded
				ExtensionUserManagement extensionUserManagement = Control
						.getSingleton().getExtensionLoader().getExtension(ExtensionUserManagement.class);
				User user = extensionUserManagement.getContextUserAuthManager(context.getIndex())
						.getUserById(userId);
				if (user == null)
					throw new ApiException(ApiException.Type.USER_NOT_FOUND, UsersAPI.PARAM_USER_ID);
				// Build and set the credentials
				UsernamePasswordAuthenticationCredentials credentials = new UsernamePasswordAuthenticationCredentials();
				credentials.username = ApiUtils.getNonEmptyStringParam(params, PARAM_USERNAME);
				credentials.password = ApiUtils.getNonEmptyStringParam(params, PARAM_PASSWORD);
				user.setAuthenticationCredentials(credentials);
			}
		};
	}
1317366
private OAuthRequest constructXAuthPost(String email, String password) {
        OAuthRequest request = new OAuthRequest(Verb.POST, xauthEndpoint);
        request.addBodyParameter("x_auth_username", email);
        request.addBodyParameter("x_auth_password", password);
        request.addBodyParameter("x_auth_mode", "client_auth");
        return request;
    }
1118582
function AdminMethods(models, users, oauthApps, oauthAuth) {
      this.models = models;
      this.users = users;
      this.oauthApps = oauthApps;
      this.oauthAuth = oauthAuth;
      this.setup = __bind(this.setup, this);
      if (!this.models) {
        throw new Error("models parameter is required");
      }
      if (!this.users) {
        throw new Error("users parameter is required");
      }
      if (!this.oauthApps) {
        throw new Error("oauthApps parameter is required");
      }
      if (!this.oauthAuth) {
        throw new Error("oauthAuth parameter is required");
      }
    }
19765
def sign_request(method, uri, form_args)
      # Convert non-string keys to strings so the sort works
      args = {}
      if form_args
        form_args.each do |key, value|
          next unless value and value != ""

          key = key.to_s unless key.is_a?(String)
          args[key] = value
        end
      end

      # Add the necessary OAuth args
      args["oauth_version"] = "1.0"
      args["oauth_consumer_key"] = @config[:api_key]
      args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}")
      args["oauth_signature_method"] = "HMAC-SHA1"
      args["oauth_timestamp"] = Time.now.utc.to_i
      args["oauth_token"] = @config[:user][:token]

      # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says:
      #
      #     Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
      #     reserved characters used for their reserved purposes may be used
      #     unencoded within a URL.
      #
      # However, if we don't escape apostrophes and parentheses the SmugMug API fails
      # with an invalid signature error:
      #
      #     Error #35, invalid signature (SmugMug::OAuthError)
      #
      # To overcome this, define a new unreserved character list and use this in URI::escape
      unreserved = "\\-_.!~*a-zA-Z\\d"
      unsafe = Regexp.new("[^#{unreserved}]", false, 'N')

      # Sort the params
      sorted_args = []
      args.sort.each do |key, value|
        sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}")
      end

      postdata = sorted_args.join("&")

      # Final string to hash
      sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}"

      signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base)
      signature = URI::escape(Base64.encode64(signature).chomp, unsafe)

      if uri == API_URI
        "#{postdata}&oauth_signature=#{signature}"
      else
        args["oauth_signature"] = signature
        args
      end
    end
1171598
private void auditEventSafAuthDetails(Object[] methodParams) {

		// Getting object array which have audit fields
		Object[] varargs = (Object[]) methodParams[1];

		// Get audit fields and convert them to respective type
		int safReturnCode = (Integer) varargs[0];
		int racfReturnCode = (Integer) varargs[1];
		int racfReasonCode = (Integer) varargs[2];
		String userSecurityName = (String) varargs[3];
		String safProfile = (String) varargs[4];
		String safClass = (String) varargs[5];
		Boolean authDecision = (Boolean) varargs[6];
		String principalName = (String) varargs[7];
		String applid = (String) varargs[8];

		if (auditServiceRef.getService() != null
				&& auditServiceRef.getService().isAuditRequired(AuditConstants.SECURITY_SAF_AUTHZ_DETAILS,
						AuditConstants.SUCCESS)) {
			// Create audit event
			SAFAuthorizationDetailsEvent safAuthDetails = new SAFAuthorizationDetailsEvent(safReturnCode,
					racfReturnCode, racfReasonCode, userSecurityName, applid, safProfile, safClass, authDecision,
					principalName);
			auditServiceRef.getService().sendEvent(safAuthDetails);
		}
	}
273014
function OAuthError(errorResponse, message) {
	this.name = "OAuthError";
	this.message = message || errorResponse.errorMessage;
	this.code = errorResponse.code;
	this.response = errorResponse;

	if (Error.captureStackTrace
		&& typeof Error.captureStackTrace === 'function') {
		Error.captureStackTrace(this, OAuthError);
	}
}
385855
function solidityToABI(methodInterface) {
  // count open and clsoed
  const methodABIObject = {};

  // not a string
  if (typeof methodInterface !== 'string') {
    throw new Error(`Method interface must be a string, currently ${typeof methodInterface}`);
  }

  // empty string
  if (methodInterface.length === 0) {
    throw new Error(`Solidity method interface must have a length greater than zero, currently ${methodInterface.length}`);
  }

  // count open brackets, closed brackets, colon count, outpouts and invalid characters
  const openBrackets = (methodInterface.match(/\(/g) || []).length;
  const closedBrackets = (methodInterface.match(/\)/g) || []).length;
  const colonCount = (methodInterface.match(/:/g) || []).length;
  const hasOutputs = openBrackets === 2 && closedBrackets === 2 && colonCount === 1;
  const hasInvalidCharacters = methodInterface.replace(/([A-Za-z0-9\_\s\,\:(\)]+)/g, '').trim().length > 0; // eslint-disable-line

  // invalid characters
  if (hasInvalidCharacters) {
    throw new Error('Invalid Solidity method interface, your method interface contains invalid chars. Only letters, numbers, spaces, commas, underscores, brackets and colons.');
  }

  // method ABI object assembly
  methodABIObject.name = methodInterface.slice(0, methodInterface.indexOf('('));
  methodABIObject.type = 'function';
  methodABIObject.constant = false;
  const methodInputsString = methodInterface.slice(methodInterface.indexOf('(') + 1, methodInterface.indexOf(')')).trim();
  const methodOutputString = (hasOutputs && methodInterface.slice(methodInterface.lastIndexOf('(') + 1, methodInterface.lastIndexOf(')')) || '').trim();
  methodABIObject.inputs = buildInputsArray(methodInputsString);
  methodABIObject.outputs = buildInputsArray(methodOutputString);

  // check open brackets
  if (methodABIObject.name === '' || typeof methodABIObject.name === 'undefined') {
    throw new Error('Invalid Solidity method interface, no method name');
  }

  // check open brackets
  if (openBrackets !== 1 && openBrackets !== 2) {
    throw new Error(`Invalid Solidity method interface, too many or too little open brackets in solidity interface, currenlty only ${openBrackets} open brackets!`);
  }

  // check open brackets
  if (openBrackets !== 1 && openBrackets !== 2) {
    throw new Error('Invalid Solidity method interface, too many or too little open brackets in solidity interface!');
  }

  // check closed brackets
  if (closedBrackets !== 1 && closedBrackets !== 2) {
    throw new Error('Invalid Solidity method interface, too many or too little closed brackets in solidity interface!');
  }

  // check colon count
  if (colonCount !== 0 && colonCount !== 1) {
    throw new Error('Invalid Solidity method interface, to many or too little colons.');
  }

  // return method abi object
  return methodABIObject;
}
1142133
def oauth_request_method(http_method, path, params = {})
      fail "OAuth access token required!" unless @oauth_token

      headers = { "Accept" => "application/xml" }

      resp = if http_method == :get || http_method == :delete
        if params
          url_params = params.map { |k, v| "#{k}=#{v}" }.join("&")
          path = "#{path}?#{url_params}"
        end
        @oauth_token.request(http_method, path, headers)
      else
        @oauth_token.request(http_method, path, params || {}, headers)
      end

      case resp
      when Net::HTTPUnauthorized
        fail Goodreads::Unauthorized
      when Net::HTTPNotFound
        fail Goodreads::NotFound
      end

      parse(resp)
    end
1012224
def supported_auth_methods(self) -> List[str]:
        
        return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]
567562
function parseMethodsFromRust (source) {
  // Matching the custom `rpc` attribute with it's doc comment
  const attributePattern = /((?:\s*\/\/\/.*$)*)\s*#\[rpc\(([^)]+)\)]/gm;
  const commentPattern = /\s*\/\/\/\s*/g;
  const separatorPattern = /\s*,\s*/g;
  const assignPattern = /([\S]+)\s*=\s*"([^"]*)"/;
  const ignorePattern = /@(ignore|deprecated|unimplemented|alias)\b/i;

  const methods = [];

  source.toString().replace(attributePattern, (match, comment, props) => {
    comment = comment.replace(commentPattern, '\n').trim();

    // Skip deprecated methods
    if (ignorePattern.test(comment)) {
      return match;
    }

    props.split(separatorPattern).forEach((prop) => {
      const [, key, value] = prop.split(assignPattern) || [];

      if (key === 'name' && value != null) {
        methods.push(value);
      }
    });

    return match;
  });

  return methods;
}
1172835
public static ApiDynamicActionImplementor getSetCredentialsForUserApiAction(
			final AuthenticationMethodType methodType) {
		return new ApiDynamicActionImplementor(ACTION_SET_CREDENTIALS, null,
				new String[] { PARAM_CONFIG_PARAMS }) {

			@Override
			public void handleAction(JSONObject params) throws ApiException {
				Context context = ApiUtils.getContextByParamId(params, UsersAPI.PARAM_CONTEXT_ID);
				int userId = ApiUtils.getIntParam(params, UsersAPI.PARAM_USER_ID);
				// Make sure the type of authentication method is compatible
				if (!methodType.isTypeForMethod(context.getAuthenticationMethod()))
					throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER,
							"User's credentials should match authentication method type of the context: "
									+ context.getAuthenticationMethod().getType().getName());

				// NOTE: no need to check if extension is loaded as this method is called only if
				// the Users extension is loaded
				ExtensionUserManagement extensionUserManagement = Control.getSingleton()
						.getExtensionLoader().getExtension(ExtensionUserManagement.class);
				User user = extensionUserManagement.getContextUserAuthManager(context.getIndex())
						.getUserById(userId);
				if (user == null)
					throw new ApiException(ApiException.Type.USER_NOT_FOUND, UsersAPI.PARAM_USER_ID);
				// Build and set the credentials
				GenericAuthenticationCredentials credentials = (GenericAuthenticationCredentials) context
						.getAuthenticationMethod().createAuthenticationCredentials();
				for (String paramName : credentials.paramNames)
					credentials.setParam(paramName, ApiUtils.getNonEmptyStringParam(params, paramName));
				user.setAuthenticationCredentials(credentials);
			}
		};
	}
150600
function onStartAuthClick(e) {
    var elmBody = document.body;

    platform.isAuthenticated().catch(function (err) {
        // methods are registered globally for the popup to call on this main window
      window.onAuthCompleted = function() {
        // the platform SDK instance from the popup has
        // received a new auth token and saved it to the store.
        // Let's retrieve it for this instance.
        platform.refreshAuthFromStore();

        elmBody.innerHTML = compiledSuccess();
      };
      window.onAuthError = function() {
        elmBody.innerHTML = compiledError();
      };

      openPopup();
    });
  }
656413
function oAuthRequest($url, $args = array(), $method = NULL) {/*{{{*/
    if (empty($method)) $method = empty($args) ? "GET" : "POST";
    $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $args);
    $req->sign_request($this->sha1_method, $this->consumer, $this->token);
	
    switch ($method) {
    case 'GET': $result = $this->http($req->to_url());
    case 'POST': $result = $this->http($req->get_normalized_http_url(), $req->to_postdata());
    }
	
	$this->validateRequest($result);

	return $result;
  }