General-purpose authentication action
175174
public function authenticateAction()
    {
        if ($this->zfcUserAuthentication()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response) {
            return $result;
        }

        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (!$auth->isValid()) {
            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();
            return $this->redirect()->toUrl(
                $this->url()->fromRoute(static::ROUTE_LOGIN) .
                ($redirect ? '?redirect='. rawurlencode($redirect) : '')
            );
        }

        $redirect = $this->redirectCallback;

        return $redirect();
    }
599608
def _plain_authentication(self, login, password, authz_id=b""):
        
        if isinstance(login, six.text_type):
            login = login.encode("utf-8")
        if isinstance(password, six.text_type):
            password = password.encode("utf-8")
        params = base64.b64encode(b'\0'.join([authz_id, login, password]))
        code, data = self.__send_command("AUTHENTICATE", [b"PLAIN", params])
        if code == "OK":
            return True
        return False
1062259
def ux_actions(parser, args):
    """"""
    # cryptorito uses native logging (as aomi should tbh)
    normal_fmt = '%(message)s'
    if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2:
        logging.basicConfig(level=logging.DEBUG)
    elif hasattr(args, 'verbose') and args.verbose >= 1:
        logging.basicConfig(level=logging.INFO, format=normal_fmt)
    else:
        logging.basicConfig(level=logging.WARN, format=normal_fmt)

    if args.operation == 'help':
        help_me(parser, args)
66172
public void authenticate() {
    if (mAccount == null) {
      // Create account also performs authentication.
      createAccount();
    } else {
      mAccess = mAccount.authenticate();
      if (mRegion != null) {
        mAccess.setPreferredRegion(mRegion);
      }
    }
  }
450958
def _handleAuthenticationEvents(self, requestdata, requestaction,
                                    clientuuid, sock):
        """"""

        # TODO: Move this stuff over to ./auth.py
        if requestaction in ("login", "autologin"):
            try:
                self.log("Login request", lvl=verbose)

                if requestaction == "autologin":
                    username = password = None
                    requestedclientuuid = requestdata
                    auto = True

                    self.log("Autologin for", requestedclientuuid, lvl=debug)
                else:
                    username = requestdata['username']
                    password = requestdata['password']

                    if 'clientuuid' in requestdata:
                        requestedclientuuid = requestdata['clientuuid']
                    else:
                        requestedclientuuid = None
                    auto = False

                    self.log("Auth request by", username, lvl=verbose)

                self.fireEvent(authenticationrequest(
                    username,
                    password,
                    clientuuid,
                    requestedclientuuid,
                    sock,
                    auto,
                ), "auth")
                return
            except Exception as e:
                self.log("Login failed: ", e, type(e), lvl=warn, exc=True)
        elif requestaction == "logout":
            self.log("User logged out, refreshing client.", lvl=network)
            try:
                if clientuuid in self._clients:
                    client = self._clients[clientuuid]
                    user_id = client.useruuid
                    if client.useruuid:
                        self.log("Logout client uuid: ", clientuuid)
                        self._logoutclient(client.useruuid, clientuuid)
                    self.fireEvent(clientdisconnect(clientuuid))
                else:
                    self.log("Client is not connected!", lvl=warn)
            except Exception as e:
                self.log("Error during client logout: ", e, type(e),
                         lvl=error, exc=True)
        else:
            self.log("Unsupported auth action requested:",
                     requestaction, lvl=warn)
458719
async function authorize (action, target) {
    let result = await check(this.auth.credentials && this.auth.credentials.user, action, target)
    if (result !== true) throw Boom.unauthorized(action)
    return true
  }
604524
private boolean authenticate(byte method, InputStream in,
                                 BufferedOutputStream out) throws IOException {
        return authenticate(method, in, out, 0L);
    }
325812
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except FedexError:
            _login(*args)
            return function(*args)
    return wrapped
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
1315183
def authenticate(self):
        """"""
        if self.apiKey:
            return
        loginResponse = self._curl_bitmex(
            api="user/login",
            postdict={'email': self.login, 'password': self.password, 'token': self.otpToken})
        self.token = loginResponse['id']
        self.session.headers.update({'access-token': self.token})
465276
private static function auth()
    {
        $files = ['Auth'];
        $folder = static::$root.'Authentication'.'/';

        self::call($files, $folder);

        $files = ['AuthenticationModelNotFoundException'];
        $folder = static::$root.'Authentication/Exceptions'.'/';

        self::call($files, $folder);
    }
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']));
        }
    }
865748
def authenticateRequest(self, service_request, username, password, **kwargs):
        
        authenticator = self.getAuthenticator(service_request)

        if self.logger:
            self.logger.debug('Authenticator expands to: %r' % authenticator)

        if authenticator is None:
            return defer.succeed(True)

        args = (username, password)

        if hasattr(authenticator, '_pyamf_expose_request'):
            http_request = kwargs.get('http_request', None)
            args = (http_request,) + args

        return defer.maybeDeferred(authenticator, *args)
353530
async def on_request(
        self,
        domain,
        address,
        identity,
        mechanism,
        credentials,
    ):
        
        logger.debug(
            "Request in domain %s for %s (%r): %r (%r)",
            domain,
            address,
            identity,
            mechanism,
            credentials,
        )

        user_id = None
        metadata = {}

        if self.whitelist:
            if address not in self.whitelist:
                raise ZAPAuthenticationFailure(
                    "IP address is not in the whitelist",
                )
        elif self.blacklist:
            if address in self.blacklist:
                raise ZAPAuthenticationFailure("IP address is blacklisted")

        if mechanism == b'PLAIN':
            username = credentials[0].decode('utf-8')
            password = credentials[1].decode('utf-8')
            ref_password = self.passwords.get(username)

            if not ref_password:
                raise ZAPAuthenticationFailure("No such user %r" % username)

            if password != ref_password:
                raise ZAPAuthenticationFailure(
                    "Invalid password for user %r" % username,
                )

            user_id = username

        elif mechanism == b'CURVE':
            public_key = credentials[0]

            if public_key not in self.authorized_keys:
                raise ZAPAuthenticationFailure(
                    "Unauthorized key %r" % public_key,
                )

        return user_id, metadata
618787
public void postProgrammaticAuthenticate(final HttpServletRequest req, final HttpServletResponse resp, final AuthenticationResult authResult,
                                             final boolean alwaysSetCallerSubject, final boolean addSSOCookie) {
        if (System.getSecurityManager() == null) {
            setSubjectAndCookies(req, resp, authResult, alwaysSetCallerSubject, addSSOCookie);
        } else {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {
                    setSubjectAndCookies(req, resp, authResult, alwaysSetCallerSubject, addSSOCookie);
                    return null;
                }
            });
        }
    }
523229
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
      def wrapper(*a, **ka):
        user, password = request.auth or (None, None)
        if user is None or not check(user, password):
          response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
          return HTTPError(401, text)
        return func(*a, **ka)
      return wrapper
    return decorator
470706
def authenticate(cls, request, route, server_config):
        
        if not server_config.getboolean("auth", False):
            return

        user = server_config.get("user", "").strip()
        password = server_config.get("password", "").strip()

        if len(user) == 0:
            return

        if "AUTHORIZATION" in request.headers:
            if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
                return

        log.error("Invalid auth. Username should %s", user)

        response = Response(request=request, route=route)
        response.set_status(401)
        response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
        # Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
        # this happen only for the first query send by the client.
        response.force_close()
        return response