Passes Exchange credentials to Nylas, to set up native authentication.
775769
def pass_creds_to_nylas(name, email, password, server_host=None):
    
    # Start the connection process by looking up all the information that
    # Nylas needs in order to connect, and sending it to the authorize API.
    nylas_authorize_data = {
        "client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
        "name": name,
        "email_address": email,
        "provider": "exchange",
        "settings": {"username": email, "password": password},
    }
    if server_host:
        nylas_authorize_data["settings"]["eas_server_host"] = server_host

    nylas_authorize_resp = requests.post(
        "https://api.nylas.com/connect/authorize", json=nylas_authorize_data
    )
    if not nylas_authorize_resp.ok:
        message = nylas_authorize_resp.json()["message"]
        raise APIError(message)

    nylas_code = nylas_authorize_resp.json()["code"]

    # Now that we've got the `code` from the authorize response,
    # pass it to the token response to complete the connection.
    nylas_token_data = {
        "client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
        "client_secret": app.config["NYLAS_OAUTH_CLIENT_SECRET"],
        "code": nylas_code,
    }
    nylas_token_resp = requests.post(
        "https://api.nylas.com/connect/token", json=nylas_token_data
    )
    if not nylas_token_resp.ok:
        message = nylas_token_resp.json()["message"]
        raise APIError(message)

    nylas_access_token = nylas_token_resp.json()["access_token"]

    # Great, we've connected the Exchange account to Nylas!
    # In the process, Nylas gave us an OAuth access token, which we'll need
    # in order to make API requests to Nylas in the future.
    # We'll save that access token in the Flask session, so we can pick it up
    # later and use it when we need it.
    session["nylas_access_token"] = nylas_access_token

    # We're all done here. Redirect the user back to the success page,
    # which will pick up the access token we just saved.
    return redirect(url_for("success"))
154929
function exchangePassword(client, username, password, scope, body, authInfo, done) {
    if (!client || !client.id) {
        return done(new common.errors.UnauthorizedError({
            message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided')
        }), false);
    }

    // Validate the user
    return models.User.check({email: username, password: password})
        .then(function then(user) {
            return authUtils.createTokens({
                clientId: client.id,
                userId: user.id
            });
        })
        .then(function then(response) {
            web.shared.middlewares.api.spamPrevention.userLogin()
                .reset(authInfo.ip, username + 'login');

            return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in});
        })
        .catch(function (err) {
            done(err, false);
        });
}
976720
async def authenticate(self, username: str, password: str) -> None:
        """"""
        self._credentials = {
            'username': username,
            'password': password,
        }

        await self._get_security_token()
655899
private void addBasicCredentials(BasicAuthInfo authInfo,
                                     Map<AuthScope, Credentials> credentialsMap) {
        logger.info("BASIC authentication for: {}", authInfo.getLoginTarget());
        Credentials credentials = new UsernamePasswordCredentials(authInfo.getUsername(),
                authInfo.getPassword());
        credentialsMap.put(new AuthScope(authInfo.getHost(), authInfo.getPort()), credentials);
    }
1004024
def _authenticate(self, client):
        """"""
        yield client.authenticate(
            self._username, self._password, mechanism=self._auth_mechanism)
        returnValue(client)
494227
def SetCredentials(self, password=None, username=None):
    
    if password:
      self._password = password
    if username:
      self._user = username
291334
def setCredentials(self, creds):
        """"""

        if isinstance(creds, UserKeyCredential):
            self.setUserKeyCredentials(creds.username, creds.public_key, creds.private_key)
        elif isinstance(creds, UserPassCredential):
            self.setUserPasswdCredentials(creds.username, creds.password)
1062667
def pull_env_credential(env, param, value):
    
    rex = "USE_KEYRING\[([\x27\x22])(.*)\\1\]"

    # This is the old-style, per-environment keyring credential
    if value == "USE_KEYRING":
        username = utils.assemble_username(env, param)

    # This is the new-style, global keyring credential that can be applied
    # to multiple environments
    else:
        global_identifier = re.match(rex, value).group(2)
        username = utils.assemble_username('global', global_identifier)

    return (username, password_get(username))
1172195
def _authenticate_plain(credentials, sock_info):
    
    source = credentials.source
    username = credentials.username
    password = credentials.password
    payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8')
    cmd = SON([('saslStart', 1),
               ('mechanism', 'PLAIN'),
               ('payload', Binary(payload)),
               ('autoAuthorize', 1)])
    sock_info.command(source, cmd)
1192599
def authenticate(self):
        '''
        
        '''
        log.debug('Authenticate to %s:%d, using the certificate %s',
                  self.address, self.port, self.certificate)
        if ':' in self.address:
            skt_ver = socket.AF_INET6
        else:
            skt_ver = socket.AF_INET
        skt = socket.socket(skt_ver, socket.SOCK_STREAM)
        self.ssl_skt = ssl.wrap_socket(skt,
                                       ca_certs=self.certificate,
                                       cert_reqs=ssl.CERT_REQUIRED)
        try:
            self.ssl_skt.connect((self.address, self.port))
            self.auth_try_id = 0
        except socket.error as err:
            log.error('Unable to open the SSL socket.')
            self.auth_try_id += 1
            if not self.max_try or self.auth_try_id < self.max_try:
                log.error('Trying to authenticate again in %d seconds', self.timeout)
                time.sleep(self.timeout)
                self.authenticate()
            log.critical('Giving up, unable to authenticate to %s:%d using the certificate %s',
                         self.address, self.port, self.certificate)
            raise ClientConnectException(err)

        # Explicit INIT
        self.ssl_skt.write(defaults.MAGIC_REQ)
        # Receive the private key
        private_key = self.ssl_skt.recv(defaults.BUFFER_SIZE)
        # Send back explicit ACK
        self.ssl_skt.write(defaults.MAGIC_ACK)
        # Read the hex of the verification key
        verify_key_hex = self.ssl_skt.recv(defaults.BUFFER_SIZE)
        # Send back explicit ACK
        self.ssl_skt.write(defaults.MAGIC_ACK)
        self.priv_key = nacl.secret.SecretBox(private_key)
        self.verify_key = nacl.signing.VerifyKey(verify_key_hex, encoder=nacl.encoding.HexEncoder)
540844
void authenticate() throws SFException, SnowflakeSQLException
  {
    ServerSocket ssocket = this.getServerSocket();
    try
    {
      // main procedure
      int port = this.getLocalPort(ssocket);
      logger.debug("Listening localhost:{}", port);
      String ssoUrl = getSSOUrl(port);
      this.handlers.output(
          "Initiating login request with your identity provider. A " +
          "browser window should have opened for you to complete the " +
          "login. If you can't see it, check existing browser windows, " +
          "or your OS settings. Press CTRL+C to abort and try again...");
      this.handlers.openBrowser(ssoUrl);

      while (true)
      {
        Socket socket = ssocket.accept(); // start accepting the request
        try
        {
          BufferedReader in = new BufferedReader(
              new InputStreamReader(socket.getInputStream(), UTF8_CHARSET));
          char[] buf = new char[16384];
          int strLen = in.read(buf);
          String[] rets = new String(buf, 0, strLen).split("\r\n");
          if (!processOptions(rets, socket))
          {
            processSamlToken(rets, socket);
            break;
          }
        }
        finally
        {
          socket.close();
        }
      }
    }
    catch (IOException ex)
    {
      throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
    }
    finally
    {
      try
      {
        ssocket.close();
      }
      catch (IOException ex)
      {
        throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
      }
    }
  }
959329
def update_credentials(self, aws_access_key_id, aws_secret_access_key):
        '''  '''
        self.aws_access_key_id = aws_access_key_id
        self.aws_secret_access_key = aws_secret_access_key
623426
protected Authentication authenticateEcpRequest(final Credential credential,
                                                    final Pair<AuthnRequest, MessageContext> authnRequest) {
        val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest.getKey());
        LOGGER.debug("Located issuer [{}] from request prior to authenticating [{}]", issuer, credential.getId());

        val service = getSamlProfileHandlerConfigurationContext().getWebApplicationServiceFactory().createService(issuer);
        LOGGER.debug("Executing authentication request for service [{}] on behalf of credential id [{}]", service, credential.getId());
        val authenticationResult = getSamlProfileHandlerConfigurationContext()
            .getAuthenticationSystemSupport().handleAndFinalizeSingleAuthenticationTransaction(service, credential);
        return authenticationResult.getAuthentication();
    }
1133898
def _init_credentials(self, oauth_token, oauth_token_secret):
        ""
        if oauth_token and oauth_token_secret:
            if self.verified:
                # If provided, this is a fully verified set of
                # credentials. Store the oauth_token and secret
                # and initialize OAuth around those
                self._init_oauth(oauth_token, oauth_token_secret)

            else:
                # If provided, we are reconstructing an initalized
                # (but non-verified) set of public credentials.
                self.oauth_token = oauth_token
                self.oauth_token_secret = oauth_token_secret

        else:
            # This is a brand new set of credentials - we need to generate
            # an oauth token so it's available for the url property.
            oauth = OAuth1(
                self.consumer_key,
                client_secret=self.consumer_secret,
                callback_uri=self.callback_uri,
                rsa_key=self.rsa_key,
                signature_method=self._signature_method
            )

            url = self.base_url + REQUEST_TOKEN_URL
            headers = {'User-Agent': self.user_agent}
            response = requests.post(url=url, headers=headers, auth=oauth)
            self._process_oauth_response(response)
711477
def _authenticate(self):
        """"""
        self.cleanup_headers()
        url = LOGIN_ENDPOINT
        data = self.query(
            url,
            method='POST',
            extra_params={
                'email': self.__username,
                'password': self.__password
            })

        if isinstance(data, dict) and data.get('success'):
            data = data.get('data')
            self.authenticated = data.get('authenticated')
            self.country_code = data.get('countryCode')
            self.date_created = data.get('dateCreated')
            self.__token = data.get('token')
            self.userid = data.get('userId')

            # update header with the generated token
            self.__headers['Authorization'] = self.__token
1122804
function connectToNylas(data) {
  return nylasCode(data)
    .then(code => {
      const params = {
        client_id: config.nylasClientId,
        client_secret: config.nylasClientSecret,
        code: code,
      };
      return nylasToken(params)
        .then(token => {
          return Promise.resolve(token);
        })
        .catch(err => {
          return Promise.reject(
            new Error(`Could not connect to Nylas. Error: ${err.message}`)
          );
        });
    })
    .catch(err => {
      return Promise.reject(
        new Error(`Could not connect to Nylas. Error: ${err.message}`)
      );
    });
}
1217146
def setup_authentication_methods(authn_config, template_env):
    """"""
    routing = {}
    ac = AuthnBroker()
    for authn_method in authn_config:
        cls = make_cls_from_name(authn_method["class"])
        instance = cls(template_env=template_env, **authn_method["kwargs"])
        ac.add(authn_method["acr"], instance)
        routing[instance.url_endpoint] = VerifierMiddleware(instance)

    return ac, routing