Authenticate hook handler
439406
function authenticate($args)
    {
        if (!empty($_SERVER['REMOTE_USER']) && !empty($_SERVER['KRB5CCNAME'])) {
            // Load plugin's config file
            $this->load_config();

            $rcmail = rcmail::get_instance();
            $host   = $rcmail->config->get('krb_authentication_host');

            if (is_string($host) && trim($host) !== '' && empty($args['host'])) {
                $args['host'] = rcube_utils::idn_to_ascii(rcube_utils::parse_host($host));
            }

            if (!empty($_SERVER['REMOTE_USER'])) {
                $args['user'] = $_SERVER['REMOTE_USER'];
                $args['pass'] = null;
            }

            $args['cookiecheck'] = false;
            $args['valid']       = true;
        }

        return $args;
    }
1356614
function Authenticate() {
		$response = $this->MakeAPICall("POST", "session");
		
		if ($response['success']) {
			$this->last_token = $response['results'][0]['AuthToken'];
			$this->last_token_expire = $response['results'][0]['Expires'];
			
			if ($this->cache) {
				$this->cache->set($this->cache_prefix . 'authtoken', $this->last_token, 86400);
			}
			
			if ( is_callable($this->access_change_callback) ) {
				call_user_func($this->access_change_callback, 'api', array('auth_token' => $this->last_token) );
			}
			
			return true;
		}
		
		return false;
	}
129340
public function authenticate()
    {
        $object = 'login';
        $url = sprintf('/api/%s/version/%s', $object, $this->version);
        $parameters = array(
            'email'    => $this->email,
            'password' => $this->password,
            'user_key' => $this->userKey,
            'format'   => $this->format
        );

        $this->apiKey = $this->doPost($object, $url, $parameters);

        return $this->apiKey;
    }
874455
def validate_authentication(self, username, password, handler):
        
        user = authenticate(
            **{self.username_field: username, 'password': password}
        )
        account = self.get_account(username)
        if not (user and account):
            raise AuthenticationFailed("Authentication failed.")
77543
def check_auth(func):
    
    def wrapper(handler, *args, **kwargs):
        if handler.check_auth_header():
            return func(handler, *args, **kwargs)
    return wrapper
686086
def handle(cls, value, context, **kwargs):
        
        try:
            hook_name, key = value.split("::")
        except ValueError:
            raise ValueError("Invalid value for hook_data: %s. Must be in "
                             "<hook_name>::<key> format." % value)

        return context.hook_data[hook_name][key]
352243
function trustableAuthHandler(//{{{
    authHandler,
    pathSpec,
    ext,
    method,
    ac,
    req,
    actualRes,
    actualNext
) {

    // Provide fake http environment:
    var httpDone = false;
    var res = Object.create(actualRes);
    res.send = function newSend(){
        actualRes.send.apply(actualRes, arguments);
        httpDone = true;
    };
    function next(){
        actualNext.apply(this, arguments);
        httpDone = true;
    };

    // Call actual authentication handler:
    var auth = authHandler(
        pathSpec,
        ext,
        method,
        ac,
        req,
        res,
        next
    );

    // Ensure http handshake is fully handled:
    if (! httpDone && typeof auth != "object") {
        var msg = (typeof auth == "string")
            ? auth
            : "Access denied."
        ;
        Util.sendStatusMessage(actualRes, "forbidden", msg);
        httpDone = true;
    };
    if (httpDone) auth = false; // Any response handling in authHandler is also an access reject.


    // Ensure consistent auth interface.
    if (auth) {
        auth.filter || (auth.filter = defaultResponse.filter);
        auth.userData || (auth.userData = defaultResponse.userData);
        auth.privileges || (auth.privileges = defaultResponse.privileges);
        if (
            (typeof auth.filter != "function")
            || (typeof auth.userData != "object")
            || (typeof auth.privileges != "function")
        ) {
            console.error("Wrong auth object", auth);
            Util.sendStatusMessage(actualRes, "error", "Internal Server Error");
                // With httpDone = true we were never got here ;-)
        };
    };

    // Return trusted auth data.
    return auth;

}
1266381
public function renderHook()
    {
        $form_hook = $this->mapAuthenticationTypeFilePath('hook.php');
        if (method_exists($this->controller, 'hook') || $form_hook->exists()) {
            ob_start();
            if (method_exists($this->controller, 'hook')) {
                $this->controller->hook();
            }
            if ($form_hook->exists()) {
                $controller = $this->controller;
                extract($this->controller->getSets());
                require_once $form_hook->file;
            }
            $out = ob_get_contents();
            ob_end_clean();
            echo $out;
        }
    }
37200
protected function authenticate()
    {
        if (!$this->isAuthenticated) {
            list($url, $this->cdnUrl, $this->authToken) = $this->auth->authenticate();
            if ($this->useServicenet) {
                $url = str_replace('https://', 'https://snet-%s', $url);
            }

            $this->connectionUrlInfo = Utils::parseUrl($url);
            $this->httpConnect();

            if ($this->cdnUrl) {
                $this->cdnConnect();
            }

            $this->isAuthenticated = true;
        }
    }
1123680
def _require_authenticate(func):
    ''''''

    def wrapped(self):
        if not hasattr(self, 'authenticated'):
            self.authenticated = None
        if self.authenticated:
            return func(self)

        auth = self.headers.get(u'Authorization')
        if auth is None:
            msg = u"You are not allowed to access this page. Please login first!"
            return _error_401(self, msg)

        token, fields = auth.split(' ', 1)
        if token != 'Digest':
            return _error_401(self, 'Unsupported authentication type')

        # Check the header fields of the request.
        cred = parse_http_list(fields)
        cred = parse_keqv_list(cred)
        keys = u'realm', u'username', u'nonce', u'uri', u'response'
        if not all(cred.get(key) for key in keys):
            return _error_401(self, 'Incomplete authentication header')
        if cred['realm'] != self.server.realm:
            return _error_401(self, 'Incorrect realm')
        if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred):
            return _error_401(self, 'qop with missing nc or cnonce')

        # Check the username.
        username = cred['username']
        password = self.server.get_password(username)
        if not username or password is None:
            return _error_401(self, 'Invalid username or password')

        # Check the digest string.
        location = u'%s:%s' % (self.command, self.path)
        location = md5hex(location.encode('utf8'))
        pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password))

        if 'qop' in cred:
            info = (cred['nonce'],
                    cred['nc'],
                    cred['cnonce'],
                    cred['qop'],
                    location)
        else:
            info = cred['nonce'], location

        expect = u'%s:%s' % (pwhash, ':'.join(info))
        expect = md5hex(expect.encode('utf8'))
        if expect != cred['response']:
            return _error_401(self, 'Invalid username or password')

        # Success!
        self.authenticated = True
        return func(self)

    return wrapped
1235556
def callHook(self, hookname, *args, **kwargs):
        ''
        r = []
        for f in self.hooks[hookname]:
            try:
                r.append(f(*args, **kwargs))
            except Exception as e:
                exceptionCaught(e)
        return r
764173
function(handler) {
        if (typeof accessToken == 'undefined') {
            var body = {
                client_id: clientId,
                client_secret: clientSecret,
                username: username,
                password: password,
                grant_type: 'password'
            };

            if (thisObject.debug) {
                console.log("Making oAuth call...");
            }

            var options =  {
                url: 'https://app1pub.smappee.net/dev/v1/oauth2/token',
                headers: {
                    'Host': 'app1pub.smappee.net'
                },
                form: body
            };

            request.post(options, function (err, httpResponse, body) {
                if (err) {
                    return console.error('Request failed:', err);
                }
                if (thisObject.debug) {
                    console.log('Server responded with:', body);
                }

                accessToken = JSON.parse(body);
                handler(accessToken);
            });
        } else {
            handler(accessToken)
        }
    }
904190
def init_orm_hooks!
      sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
        record.send(sorcery_config.password_attribute_name).present?
      }

      sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
        record.send(sorcery_config.password_attribute_name).present?
      }

      attr_accessor sorcery_config.password_attribute_name
    end
738639
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except MoparError:
            _LOGGER.info("attempted to access page before login")
            _login(args[0])
            return function(*args)
    return wrapped
1050017
function authenticate(req, cb) {
    request.post(
      'https://github.com/login/oauth/access_token',
      { form:
        { client_id: process.env.GHID,      // don't store credentials in opts
          client_secret: process.env.GHCS,  // get them straight from process.env
          code: req.query.code } },
      function(err, resp, body) {
        if (err) return cb(err);
        var result = qs.parse(body);
        getUser(req, result, function() {
          cb(null, result);
        });
      }
    );
  }
157406
async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    // grab the url that will be used for authorization
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}
1071651
function call($func,$args=NULL,$hooks='') {
		if (!is_array($args))
			$args=array($args);
		// Grab the real handler behind the string representation
		if (is_string($func))
			$func=$this->grab($func,$args);
		// Execute function; abort if callback/hook returns FALSE
		if (!is_callable($func))
			// No route handler
			if ($hooks=='beforeroute,afterroute') {
				$allowed=array();
				if (is_array($func))
					$allowed=array_intersect(
						array_map('strtoupper',get_class_methods($func[0])),
						explode('|',self::VERBS)
					);
				header('Allow: '.implode(',',$allowed));
				$this->error(405);
			}
			else
				user_error(sprintf(self::E_Method,
					is_string($func)?$func:$this->stringify($func)),
					E_USER_ERROR);
		$obj=FALSE;
		if (is_array($func)) {
			$hooks=$this->split($hooks);
			$obj=TRUE;
		}
		// Execute pre-route hook if any
		if ($obj && $hooks && in_array($hook='beforeroute',$hooks) &&
			method_exists($func[0],$hook) &&
			call_user_func_array(array($func[0],$hook),$args)===FALSE)
			return FALSE;
		// Execute callback
		$out=call_user_func_array($func,$args?:array());
		if ($out===FALSE)
			return FALSE;
		// Execute post-route hook if any
		if ($obj && $hooks && in_array($hook='afterroute',$hooks) &&
			method_exists($func[0],$hook) &&
			call_user_func_array(array($func[0],$hook),$args)===FALSE)
			return FALSE;
		return $out;
	}