auth_and_mail_phase() IMPORTANT: do STARTTLS before AUTH for security
192723
function process_ehlo_data () {
            set_ehlo_props();

            if (secured) return auth_and_mail_phase();              // TLS already negotiated
            if (!cfg.enable_tls) return auth_and_mail_phase();      // TLS not enabled
            if (!smtp_properties.tls) return auth_and_mail_phase(); // TLS not advertised by remote

            if (obtls.cfg === undefined) {
                self.logerror(`Oops, TLS config not loaded yet!`);
                return auth_and_mail_phase();  // no outbound TLS config
            }

            // TLS is configured and available

            // TLS exclude lists checks for MX host or remote domain
            if (net_utils.ip_in_list(obtls.cfg.no_tls_hosts, host)) return auth_and_mail_phase();
            if (net_utils.ip_in_list(obtls.cfg.no_tls_hosts, self.todo.domain)) return auth_and_mail_phase();

            // Check Redis and skip for hosts that failed past TLS upgrade
            return obtls.check_tls_nogo(host,
                () => { // Clear to GO
                    self.logdebug(`Trying TLS for domain: ${self.todo.domain}, host: ${host}`);

                    socket.on('secure', () => {
                        // Set this flag so we don't try STARTTLS again if it
                        // is incorrectly offered at EHLO once we are secured.
                        secured = true;
                        send_command(mx.using_lmtp ? 'LHLO' : 'EHLO', mx.bind_helo);
                    });
                    return send_command('STARTTLS');
                },
                (when) => { // No GO
                    self.loginfo(`TLS disabled for ${host} because it was marked as non-TLS on ${when}`);
                    return auth_and_mail_phase();
                }
            );

        }
643462
def cmd_auth(auth_phrase=None):
    
    def decorate(func):
        """
        decorates the funcion
        """
        # get the Singleton
        ap_ = ArgParseInator(skip_init=True)
        # set the authorization name
        auth_name = id(func)
        if auth_phrase is None:
            # if we don't have a specific auth_phrase we set the
            # **authorization needed** to True
            ap_.auths[auth_name] = True
        else:
            # else if we have a specific auth_phrase we set it for the
            # command authorization
            ap_.auths[auth_name] = str(auth_phrase)
        return func
    return decorate
748536
public function auth()
    {
        if ($this->phase !== self::PHASE_GOT_INIT) {
            return;
        }
        $this->phase = self::PHASE_AUTH_SENT;
        $this->onResponse->push(function ($conn, $result) {
            if ($conn->onConnected) {
                $conn->connected = true;
                $conn->onConnected->executeAll($conn, $result);
                $conn->onConnected = null;
            }
        });
        $this->clientFlags =
            Pool::CLIENT_LONG_PASSWORD |
            Pool::CLIENT_LONG_FLAG |
            Pool::CLIENT_LOCAL_FILES |
            Pool::CLIENT_PROTOCOL_41 |
            Pool::CLIENT_INTERACTIVE |
            Pool::CLIENT_TRANSACTIONS |
            Pool::CLIENT_SECURE_CONNECTION |
            Pool::CLIENT_MULTI_STATEMENTS |
            Pool::CLIENT_MULTI_RESULTS;

        $this->sendPacket(
            $packet = pack('VVc', $this->clientFlags, $this->pool->maxAllowedPacket, $this->charsetNumber)
                . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
                . $this->user . "\x00"
                . ($this->password === '' ? "\x00" : $this->buildLenEncodedBinary(
                    $this->getAuthToken($this->scramble, $this->password)
                ))
                . ($this->path !== '' ? $this->path . "\x00" : '')
        );
    }
600254
def auth_tls(self, mount_point='cert', use_token=True):
        
        return self.login('/v1/auth/{0}/login'.format(mount_point), use_token=use_token)
48896
function setup() {
        if (
            !isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != $this->username ||
            !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_PW'] != $this->password
        ) {
            throw new Tonic\UnauthorizedException;
        }
    }
172793
def auth():
    
    # the template context
    context = {
        'name': 'auth',
    }

    render_template(template='common', context=context)
    render_template(template='auth', context=context)
351442
def _require_auth(fnc):
    """"""
    @wraps(fnc)
    @_assure_identity
    def _wrapped(*args, **kwargs):
        if not identity.authenticated:
            msg = "Authentication required before calling '%s'." % fnc.__name__
            raise exc.NotAuthenticated(msg)
        return fnc(*args, **kwargs)
    return _wrapped
425302
public function startTLS()
    {
        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
            return false;
        }
        // Begin encrypted connection
        if (!stream_socket_enable_crypto(
            $this->smtp_conn,
            true,
            STREAM_CRYPTO_METHOD_TLS_CLIENT
        )) {
            return false;
        }
        return true;
    }
1145571
def begin_auth(request):
    
    # Instantiate Twython with the first leg of our trip.
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET)

    # Request an authorization url to send the user to...
    callback_url = request.build_absolute_uri(reverse('twython_django_oauth.views.thanks'))
    auth_props = twitter.get_authentication_tokens(callback_url)

    # Then send them over there, durh.
    request.session['request_token'] = auth_props

    request.session['next_url'] = request.GET.get('next',None)
    
    return HttpResponseRedirect(auth_props['auth_url'])
1106970
function auth (username, password, callback) {
    return relax({
      method: 'POST',
      db: '_session',
      form: {
        name: username,
        password: password
      }
    }, callback)
  }
499668
def before(self):
        """"""
        user = self.request.user()

        if user and user.verified_at is None:
            self.request.redirect('/email/verify')
658020
async def starttls(
        self,
        tls_context: ssl.SSLContext,
        server_hostname: str = None,
        timeout: NumType = None,
    ) -> StartTLSResponse:
        
        if self._stream_reader is None or self._stream_writer is None:
            raise SMTPServerDisconnected("Client not connected")

        response = await self.execute_command(b"STARTTLS", timeout=timeout)

        if response.code != SMTPStatus.ready:
            raise SMTPResponseException(response.code, response.message)

        await self._drain_writer(timeout)

        waiter = asyncio.Future(loop=self._loop)  # type: asyncio.Future

        tls_protocol = self.upgrade_transport(
            tls_context, server_hostname=server_hostname, waiter=waiter
        )

        try:
            await asyncio.wait_for(waiter, timeout=timeout, loop=self._loop)
        except asyncio.TimeoutError as exc:
            raise SMTPTimeoutError(str(exc))

        return response, tls_protocol
314066
def auth_by_email(email, password, endpoint)
      endpoint = API_BASE_URL if endpoint.nil?
      res = RestClient.post endpoint + '/auth',
                            { email: email, password: password },
                            'Content-Type' => 'application/json',
                            'Accept' => 'application/json'
      result = JSON.parse(res.body)
      fail result['message'] if res.code != '200'
      Hash[JSON.parse(res.body).map { |k, v| [k.to_sym, v] }]
    end
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);

    }
1054092
public function connectAndAuthenticate() {
		// 1. connect
		if (!$this->isConnected()) {
			$this->connect();
		}
		$this->hello();
		
		// 2. open tls connection if needed
		$securityMode = $this->config->getSecurityMode();
		if ($securityMode == SmtpConfig::SECURITY_MODE_TLS) {
			$this->startTls();
			$this->hello();
		}
		
		// 3. authenticat if needed
		if ($this->config->doAuthenticate()) {
			$this->authenticate();
		}
	}
1046976
function init($host, $port, $path, $user, $pass)
    {
        $headers = array(
            sprintf("HTTP_AUTH_LOGIN: %s", $user),
            sprintf("HTTP_AUTH_PASSWD: %s", $pass),
            "Content-Type: text/xml"
        );

        $url        = sprintf("https://%s:%s/%s", $host, $port, $path);
        $this->curl = curl_init();

        curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT , 5);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST , 0);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($this->curl, CURLOPT_HTTPHEADER     , $headers);
        curl_setopt($this->curl, CURLOPT_URL            , $url);
    }
991759
public function auth()
    {
        // Ensure AUTH has not already been initiated.
        parent::auth();

        $this->_send('AUTH PLAIN');
        $this->_expect(334);
        $this->_send(base64_encode("\0" . $this->_username . "\0" . $this->_password));
        $this->_expect(235);
        $this->_auth = true;
    }