Check the grant given by user to login in authserver is a good one.

Arguments:
- req
- res
6321
function(req, res) {
    var params = URL.parse(req.url, true).query
      , code = params.code
      , state = params.state
    ;

    if(!code) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "code" parameter is missing.');
    }
    if(!state) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "state" parameter is missing.');
    }
    try {
      state = this.serializer.parse(state);
    } catch(err) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "state" parameter is invalid.');
    }
    var data = {
      oauth2_server_id: state[0]
      , next_url: state[1]
      , state: state[2]
    }
    var methods = this.methods[data.oauth2_server_id];
    methods.valid_grant(data, code, function(err, token) {
      if (err) return server_error(res, err);
      if(!token) {
        res.writeHead(400, {'Content-Type': 'text/plain'});
        res.end('Invalid grant.');
        return;
      }
      data.token = token;
      methods.treat_access_token(data, req, res, function() {
        redirect(res, data.next_url);
      }, function(err){server_error(res, err)});
    });
  }
1365600
function (req, res) {
    User.find().exec(function (err, users) {
      if(err) return res.json({ err: err }, 500);
      else res.json(users);
    });
  }
730105
function authenticateUser (req, res, next) {
  // Check for verified access token
  if (req.claims && req.claims.sub) {
    User.get(req.claims.sub, function (err, user) {
      if (err) {
        return next(err)
      }

      if (!user) {
        return next(new UnauthorizedError({
          realm: 'user',
          error: 'unknown_user',
          error_description: 'Unknown user',
          statusCode: 401
        }))
      }

      req.user = user
      next()
    })

  // User is not authenticated.
  } else if (!req.user) {
    next(new UnauthorizedError({
      statusCode: 401
    }))

  // User is authenticated.
  } else {
    next()
  }
}
116018
function authorize(req, res, next) {
  const role = findRoleFromRequest(
    req,
    options.roleSearchPath,
    options.defaultRole,
    options.decodedObjectName
  );

  if (req.originalUrl === '/') {
    return next();
  }

  const policy = options.policies.get(role);

  if (!policy) {
    return res.status(403).json({
      status: 'Access denied',
      success: false,
      message: `REQUIRED: Policy for role ${role} is not defined`
    });
  }

  const permission = findPermissionForRoute(
    req.originalUrl,
    req.method,
    options.baseUrl,
    policy
  );

  if (!permission) {
    if (typeof options.denyCallback === 'function') {
      return options.denyCallback(res);
    }
    return res.status(403).json(deny(options.customMessage, options.response));
  }

  return checkIfHasAccess(
    req.method,
    res,
    next,
    permission,
    options.customMessage,
    options.response,
    options.denyCallback
  );
}
464016
def _validate_auth(self, path, obj, _):
        
        errs = []

        if obj.type == 'apiKey':
            if not obj.passAs:
                errs.append('need "passAs" for apiKey')
            if not obj.keyname:
                errs.append('need "keyname" for apiKey')

        elif obj.type == 'oauth2':
            if not obj.grantTypes:
                errs.append('need "grantTypes" for oauth2')

        return path, obj.__class__.__name__, errs
269684
function (req, res, next) {
      if (req.query.return) {
        req.session.oauth2return = req.query.return;
      }
      next();
    }
1104694
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):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator
405360
def get_handler(self, grant_type):
        
        if grant_type == 'authorization_code':
            return self.authorization_code
        elif grant_type == 'refresh_token':
            return self.refresh_token
        elif grant_type == 'password':
            return self.password
        return None
1165115
function (req, res) {
    User.findOne({ id: req.params.id }).exec(function (err, user) {
      if(err) return res.json({ err: err }, 500);
      else res.json(user);
    });
  }
652668
function authorize(route, req, res, next) {
  var allowed = true;

  if (type.is(route.allows, Array)) {
    allowed = route.allows.indexOf(req.session.authorized) > -1;
  } else if (type.is(route.allows, String)) {
    allowed = route.allows === req.session.authorized;
  }

  debug(req.method + " " + req.path + " [" + route.allows + "][" + req.session.authorized + "] : " + (allowed ? "OK" : "DENY"));

  if (allowed) {
    return next();
  }

  res.status(403).end();
}
171163
def check_auth(username, password):
    
    return (username == settings.PRIVATE_INDEX_USERNAME and
            settings.PRIVATE_INDEX_PASSWORD and
            password == settings.PRIVATE_INDEX_PASSWORD)
385924
function (req, res) {
    var oauthQueryStateToken = req.query.state;
    var oauthCookieStateToken = req.cookies.oauthStateToken;

    if (!oauthQueryStateToken || (!oauthCookieStateToken)) {
      return false;
    } else if (oauthQueryStateToken !== oauthCookieStateToken) {
      return false;
    }

    res.clearCookie('oauthStateToken');

    return true;
  }
156814
def check_credentials(self):
        '''  '''
        req = requests.get(self.api_server + '/api/ad',
                           auth=(self.access_key, self.secret_key))
        # Not sure 500 server error should be included here
        if req.status_code in [401, 403, 500]:
            return False
        else:
            return True
857326
def get_authuser_by_name(cls, request):
        
        username = authenticated_userid(request)
        if username:
            return cls.get_item(username=username)
1110091
def check_auth(username, password):
    

    with open(os.path.expanduser("~/config/.note.conf")) as fd:
        config = json.loads(fd.read())

    try:
        u = config['server']['login']['username']
        p = config['server']['login']['password']
    except KeyError:
        print "cannot start server"
        sys.exit(1)

    return username == u and password == p
205764
function password(req, res, test) {
  var options = {
    grant_type: "password",
    client_id:  process.env.SALESFORCE_CLIENT_ID,
    client_secret: process.env.SALESFORCE_CLIENT_SECRET,
    username: req.query.username || req.body.username || process.env.SALESFORCE_USERNAME,
    password: req.query.password || req.body.password || process.env.SALESFORCE_PASSWORD,
  }

  var protocol = "https://";
  if(test === true || req.test) protocol = "http://"; //for testing

  var loginServer = req.body.login_server || req.query.login_server || "login.salesforce.com";
  var url = protocol + loginServer + "/services/oauth2/token";

  var r = request.post(url)
  .type("application/x-www-form-urlencoded")
  .send(options)
  .on("error", function(err){ return onError(res, err); })
  .end(function(sfRes){
    if(sfRes.error) return onError(res, sfRes.error + " " + JSON.stringify(sfRes.body) );
    req.session.salesforce = JSON.stringify( sfRes.body );
    if (process.env.NODE_ENV === 'development') router.session = req.session.salesforce;
    res.redirect( req.query.app_url || process.env.SALESFORCE_FINAL_URL || "/login/whoami" )
  })
}
1272160
def _validate_granttype(self, path, obj, _):
        
        errs = []

        if not obj.implicit and not obj.authorization_code:
            errs.append('Either implicit or authorization_code should be defined.')

        return path, obj.__class__.__name__, errs