handle plain authentification
173440
def process_auth_plain(session, encoded_auth_response)
      begin
        # extract auth id (and password)
        @auth_values = Base64.decode64(encoded_auth_response).split("\x00")
        # check for valid credentials parameters
        raise Smtpd500Exception unless @auth_values.length == 3
        # call event function to test credentials
        return_value = on_auth_event(session[:ctx], @auth_values[0], @auth_values[1], @auth_values[2])
        if return_value
          # overwrite data with returned value as authorization id
          @auth_values[0] = return_value
        end
        # save authentication information to ctx
        session[:ctx][:server][:authorization_id] = @auth_values[0].to_s.empty? ? @auth_values[1] : @auth_values[0]
        session[:ctx][:server][:authentication_id] = @auth_values[1]
        session[:ctx][:server][:authenticated] = Time.now.utc
        # response code
        return '235 OK'

      ensure
        # whatever happens in this check, reset next sequence
        session[:cmd_sequence] = :CMD_RSET
      end
    end
963113
def requires_basic_auth(f):
    """"""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated
4391
def authentication(self):
        """"""
        if self.session.digest:
            authentication = self.session.generate_digest()
        elif self.session.basic:
            authentication = self.session.generate_basic()
        else:
            return ''
        return "Authorization: " + authentication + '\r\n'
330111
def handle_401(self, response, exc=None):
        """"""
        if response.status_code == 401:
            s_auth = response.headers.get('www-authenticate', '')
            if 'digest' not in s_auth.lower():
                return
            request = response.request
            if not request.headers.get('authorization'):
                self.options = parse_dict_header(s_auth.replace('Digest ', ''))
                authorization = self.encode(request.method, request.url)
                params = request.inp_params.copy()
                headers = params.pop('headers', [])
                headers.append(('authorization', authorization))
                params['headers'] = headers
                response.request_again = request_again(request.method,
                                                       request.url,
                                                       params)
1310008
def handle_authenticated_user(self, response):
        
        current_user = get_user(self.request)

        ulogin, registered = ULoginUser.objects.get_or_create(
            uid=response['uid'],
            network=response['network'],
            defaults={'identity': response['identity'],
                      'user': current_user})

        if not registered:
            ulogin_user = ulogin.user
            logger.debug('uLogin user already exists')

            if current_user != ulogin_user:
                logger.debug(
                    "Mismatch: %s is not a %s. Take over it!" % (current_user,
                                                                 ulogin_user)
                )
                ulogin.user = current_user
                ulogin.save()

        return get_user(self.request), ulogin, registered
477369
function () {
                try {
                    authHandler.sign(authInterface, context.item.request, function (err) {
                        // handle all types of errors in one place, see catch block
                        if (err) { throw err; }

                        done();
                    });
                }
                catch (err) {
                    // handles synchronous and asynchronous errors in auth.sign
                    run.triggers.console(context.coords,
                        'warn',
                        'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
                        err
                    );

                    // swallow the error, we've warned the user
                    done();
                }
            }
1218542
def authenticated(viewfunc):
    """"""
    @wraps(viewfunc)
    def wrapper(*args, **kwargs):
        ctx = stack.top
        if ctx and hasattr(ctx, 'htauth'):
            auth_header = request.headers.get('Authorization', None)
            if not auth_header:
                return _unauthorized_response()

            if not auth_header.startswith('Basic '):
                raise RuntimeError('Flask-HTAuth supports only Basic auth.')

            auth_header = auth_header.replace('Basic ', '')
            auth_header = base64.b64decode(auth_header)
            username, password = auth_header.split(':', 1)

            if not username in ctx.htauth['users']:
                return _unauthorized_response()

            if not check_password(password, ctx.htauth['users'][username]):
                return _unauthorized_response()

            g.htauth_user = username

        return viewfunc(*args, **kwargs)

    return wrapper
1099270
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'basic':
            return None

        if len(auth) == 1:
            msg = _('Invalid basic header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid basic header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
        except (TypeError, UnicodeDecodeError):
            msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
            raise exceptions.AuthenticationFailed(msg)

        userid, password = auth_parts[0], auth_parts[2]
        return self.authenticate_credentials(userid, password)
420713
def authenticate(self, provider=None, identifier=None):
        ""
        provider_q = Q(provider__name=provider)
        if isinstance(provider, Provider):
            provider_q = Q(provider=provider)
        try:
            access = AccountAccess.objects.filter(
                provider_q, identifier=identifier
            ).select_related('user')[0]
        except IndexError:
            return None
        else:
            return access.user
20553
public static AuthInfo typical(String username, String password) {
    return new AuthInfo(new PlainCallbackHandler(username, password),
        new String[] {"CRAM-MD5", "PLAIN"});
  }
20204
def _do_server_auth(conn, auth_secret):
    
    write_with_length(auth_secret.encode("utf-8"), conn)
    conn.flush()
    reply = UTF8Deserializer().loads(conn)
    if reply != "ok":
        conn.close()
        raise Exception("Unexpected reply from iterator server.")
332337
protected function handleAuthentication()
    {
        if (isset($this->payload['options']['username'], $this->payload['options']['password'])) {
            $this->addCurlOption(CURLOPT_USERPWD, sprintf('%s:%s', $this->payload['options']['username'], $this->payload['options']['password']));
        }
    }
837104
def authenticate(self, user, password):
        

        request = Request(AUTH_URL)
        request.add_header('X-Simperium-API-Key', API_KEY)
        if sys.version_info < (3, 3):
            request.add_data(json.dumps({'username': user, 'password': password}))
        else:
            request.data = json.dumps({'username': user, 'password': password}).encode()
        try:
            res = urllib2.urlopen(request).read()
            token = json.loads(res.decode('utf-8'))["access_token"]
        except HTTPError:
            raise SimplenoteLoginFailed('Login to Simplenote API failed!')
        except IOError: # no connection exception
            token = None
        return token
463049
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except USPSError:
            _LOGGER.info("attempted to access page before login")
            _login(args[0])
            return function(*args)
    return wrapped
814127
def process_auth(self):
        
        r = self._reader
        w = self._writer
        pdu_size = r.get_smallint()
        if not self.authentication:
            raise tds_base.Error('Got unexpected token')
        packet = self.authentication.handle_next(readall(r, pdu_size))
        if packet:
            w.write(packet)
            w.flush()
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)
846491
def no_auth(self):
        """"""
        old_basic_auth, self.auth = self.auth, None
        old_token_auth = self.headers.pop('Authorization', None)

        yield

        self.auth = old_basic_auth
        if old_token_auth:
            self.headers['Authorization'] = old_token_auth