Simple route middleware to ensure user is authenticated, use on any protected resource. Also restores the user's Google oauth token from the session, available as req.authClient
193567
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    req.authClient = new googleapis.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET);
    req.authClient.credentials = req.session.googleCredentials;
    return next();
  }
  res.redirect('/');
}
117124
function isAuthenticated() {
  return compose()
    // Validate jwt
    .use(function (req, res, next) {
      // allow access_token to be passed through query parameter as well
      if (req.query && req.query.hasOwnProperty('access_token')) {
        req.headers.authorization = 'Bearer ' + req.query.access_token;
      }

      validateJwt(req, res, next);
    })

    .use(function (req, res, next) { // Attach userInfo to request
      // return if this request has already been authorized
      if (req.hasOwnProperty('userInfo')) {
        return next();
      }

      // load user model on demand
      var User = require('../../api/user/user.model').model;

      // read the user id from the token information provided in req.user
      User.findOne({_id: req.user._id, active: true}, function (err, user) {
        if (err) {
          return next(err);
        }

        if (!user) {
          res.unauthorized();
          return next();
        }

        // set the requests userInfo object as the authenticated user
        req.userInfo = user;
        next();
      });
    });
}
1114522
async def login(self, client_name, request, redirect_uri=None, **params):
        
        client = self.client(client_name, logger=self.app.logger)

        redirect_uri = redirect_uri or self.cfg.redirect_uri or '%s://%s%s' % (
            request.scheme, request.host, request.path)
        session = await self.app.ps.session(request)

        if isinstance(client, OAuth1Client):
            oauth_verifier = request.query.get('oauth_verifier')
            if not oauth_verifier:

                # Get request credentials
                token, secret = await client.get_request_token(
                    oauth_callback=redirect_uri)

                # Save the credentials in current user session
                session['oauth_token'] = token
                session['oauth_token_secret'] = secret

                url = client.get_authorize_url()
                raise muffin.HTTPFound(url)

            # Check request_token
            oauth_token = request.query.get('oauth_token')
            if session['oauth_token'] != oauth_token:
                raise muffin.HTTPForbidden(reason='Invalid token.')

            client.oauth_token = oauth_token
            client.oauth_token_secret = session.get('oauth_token_secret')

            # Get access tokens
            return client, await client.get_access_token(oauth_verifier)

        if isinstance(client, OAuth2Client):
            code = request.query.get('code')
            if not code:

                # Authorize an user
                state = sha1(str(random()).encode('ascii')).hexdigest()
                session['oauth_secret'] = state
                url = client.get_authorize_url(
                    redirect_uri=redirect_uri, state=state, **params)
                raise muffin.HTTPFound(url)

            # Check state
            state = request.query.get('state')
            oauth_secret = session.pop('oauth_secret', '')
            if oauth_secret != state:
                raise muffin.HTTPForbidden(reason='Invalid token "%s".' % oauth_secret)

            # Get access token
            return client, await client.get_access_token(code, redirect_uri=redirect_uri)

        return client
1130411
def authenticate(self, request):
        
        authenticators = self._meta.authenticators

        if request.method == 'OPTIONS' and ADREST_ALLOW_OPTIONS:
            self.auth = AnonimousAuthenticator(self)
            return True

        error_message = "Authorization required."
        for authenticator in authenticators:
            auth = authenticator(self)
            try:
                if not auth.authenticate(request):
                    raise AssertionError(error_message)

                self.auth = auth
                auth.configure(request)
                return True
            except AssertionError, e:
                error_message = str(e)

        raise HttpError(error_message, status=status.HTTP_401_UNAUTHORIZED)
84314
def authenticate_user(self, request, user):
        
        return user.check_password(request.data.get('password')) or \
               self.check_user_token(request, user)
313445
def auth(self, request):
        
        request_token = super(ServiceTumblr, self).auth(request)
        callback_url = self.callback_url(request)

        # URL to redirect user to, to authorize your app
        auth_url_str = '{auth_url}?oauth_token={token}'
        auth_url_str += '&oauth_callback={callback_url}'
        auth_url = auth_url_str.format(auth_url=self.AUTH_URL,
                                       token=request_token['oauth_token'],
                                       callback_url=callback_url)

        return auth_url
558185
def auth(self, request):
        
        request_token = super(ServiceTrello, self).auth(request)
        callback_url = self.callback_url(request)

        # URL to redirect user to, to authorize your app
        auth_url_str = '{auth_url}?oauth_token={token}'
        auth_url_str += '&scope={scope}&name={name}'
        auth_url_str += '&expiration={expiry}&oauth_callback={callback_url}'
        auth_url = auth_url_str.format(auth_url=self.AUTH_URL,
                                       token=request_token['oauth_token'],
                                       scope=self.scope,
                                       name=self.app_name,
                                       expiry=self.expiry,
                                       callback_url=callback_url)

        return auth_url
269684
function (req, res, next) {
      if (req.query.return) {
        req.session.oauth2return = req.query.return;
      }
      next();
    }
1160080
def authenticate(self):
        
        settings_dict = self.settings_dict
        url = ''.join([settings_dict['HOST'], '/services/oauth2/token'])

        log.info("attempting authentication to %s", settings_dict['HOST'])
        self._session.mount(settings_dict['HOST'], HTTPAdapter(max_retries=get_max_retries()))
        auth_params = {
            'grant_type':    'password',
            'client_id':     settings_dict['CONSUMER_KEY'],
            'client_secret': settings_dict['CONSUMER_SECRET'],
            'username':      settings_dict['USER'],
            'password':      settings_dict['PASSWORD'],
        }
        response = self._session.post(url, data=auth_params)
        if response.status_code == 200:
            # prefer str in Python 2 due to other API
            response_data = {str(k): str(v) for k, v in response.json().items()}
            # Verify signature (not important for this auth mechanism)
            calc_signature = (
                base64.b64encode(
                    hmac.new(
                        key=settings_dict['CONSUMER_SECRET'].encode('ascii'),
                        msg=(response_data['id'] + response_data['issued_at']).encode('ascii'),
                        digestmod=hashlib.sha256
                    ).digest()
                )
            ).decode('ascii')
            if calc_signature == response_data['signature']:
                log.info("successfully authenticated %s", settings_dict['USER'])
            else:
                raise IntegrityError('Invalid auth signature received')
        else:
            raise LookupError("oauth failed: %s: %s" % (settings_dict['USER'], response.text))
        return response_data
818834
def authenticate(self, request, **credentials):
        """"""
        from allauth.account.auth_backends import AuthenticationBackend

        self.pre_authenticate(request, **credentials)
        AuthenticationBackend.unstash_authenticated_user()
        user = authenticate(request, **credentials)
        alt_user = AuthenticationBackend.unstash_authenticated_user()
        user = user or alt_user
        if user and app_settings.LOGIN_ATTEMPTS_LIMIT:
            cache_key = self._get_login_attempts_cache_key(
                request, **credentials)
            cache.delete(cache_key)
        else:
            self.authentication_failed(request, **credentials)
        return user
471789
def authenticate(self, req, resp, resource):
        
        payload = self._decode_jwt_token(req)
        user = self.user_loader(payload)
        if not user:
            raise falcon.HTTPUnauthorized(
                description='Invalid JWT Credentials')

        return user
32620
function auth(app, config) {
  /* Ensure authorizer */
  if (!type.is(config.authorizer, Function)) {
    throw new Error("Authorizer must be a [Function]!");
  }

  /* Check debug type */
  if (type.is(config.debug, Function)) {
    debug = config.debug;
  } else if (config.debug) {
    debug = console.log;
  }

  app.use(function (req, res, next) {
    /* Set the session authorized property */
    req.session.authorized = config.authorizer(req);

    next();
  });

  /* Set authorization rules for each path */
  config.routes.forEach(function (route) {
    if (!type.is(route.path, Array) && !type.is(route.path, String)) {
      throw new Error("The route's path must be a [String] or an [Array] of [String]s!");
    }

    debug(route.method + " " + route.path + " --> " + route.allows);

    /* Callback for each method */
    function callback(req, res, next) {
      authorize(route, req, res, next);
    }

    /* The base router */
    var router = app.route(route.path);

    /* If method is an array */
    if (type.is(route.method, Array)) {
      return route.method.forEach(function (method) {
        router[method.toLowerCase()](callback);
      });
    }

    /* If method is a string */
    if (type.is(route.method, String)) {
      return router[route.method.toLowerCase()](callback);
    }

    /* If no method is specified default to ALL */
    router(callback);
  });
}
1081404
def authenticate(self, request):
        
        auth_header = get_authorization_header(request).decode(HTTP_HEADER_ENCODING)
        auth = auth_header.split()

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

        if len(auth) == 1:
            msg = 'Invalid token header. No backend provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) == 2:
            msg = 'Invalid token header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 3:
            msg = 'Invalid token header. Token string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        token = auth[2]
        backend = auth[1]

        strategy = load_strategy(request=request)

        try:
            backend = load_backend(strategy, backend, reverse(NAMESPACE + ":complete", args=(backend,)))
        except MissingBackend:
            msg = 'Invalid token header. Invalid backend.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = backend.do_auth(access_token=token)
        except requests.HTTPError as e:
            msg = e.response.text
            raise exceptions.AuthenticationFailed(msg)

        if not user:
            msg = 'Bad credentials.'
            raise exceptions.AuthenticationFailed(msg)
        return user, token
829060
def authenticate(self, username=None, password=None):
        
        data = api_client.authenticate(username, password)
        if not data:
            return

        return User(
            data.get('pk'), data.get('token'), data.get('user_data')
        )
1028621
def authorized(route):
    
    @wraps(route)
    def authorized_route(*args, **kwargs):
        if 'mwoauth_access_token' in flask.session:
            return route(*args, **kwargs)
        else:
            return flask.redirect(
                flask.url_for('mwoauth.mwoauth_initiate') +
                "?next=" + flask.request.endpoint)

    return authorized_route
990960
def authenticate_user(self, response, **kwargs):
        """"""

        host = urlparse(response.url).hostname

        try:
            auth_header = self.generate_request_header(response, host)
        except KerberosExchangeError:
            # GSS Failure, return existing response
            return response

        log.debug("authenticate_user(): Authorization header: {0}".format(
            auth_header))
        response.request.headers['Authorization'] = auth_header

        # Consume the content so we can reuse the connection for the next
        # request.
        response.content
        response.raw.release_conn()

        _r = response.connection.send(response.request, **kwargs)
        _r.history.append(response)

        log.debug("authenticate_user(): returning {0}".format(_r))
        return _r
95271
def auth_required(self, view):
        

        @functools.wraps(view)
        def decorated(*args, **kwargs):
            log.info("Trying to get access to protected resource: '%s'", view.__name__)
            if request.method == 'POST':
                token = request.form['token']
                if self.development or self.authenticated(token):
                    return view(*args, **kwargs)
                else:
                    log.warning("User has not been authorized to get access to resource: %s", view.__name__)
            else:
                log.warning("Bad request type! Expected 'POST', actual '%s'", request.method)

            return abort(403)

        return decorated