Validates a token

@param  {String}   token the token to be validated
@param  {Function} cb    called when error has occured or token is validated
967129
function(token, cb){
      try{
        // decode the token
        var _token = waterlock.jwt.decode(token, waterlock.config.jsonWebTokens.secret);

        // set the time of the request
        var _reqTime = Date.now();

        // If token is expired
        if(_token.exp <= _reqTime){
          waterlock.logger.debug('access token rejected, reason: EXPIRED');
          return cb('Your token is expired.');
        }

        // If token is early
        if(_reqTime <= _token.nbf){
          waterlock.logger.debug('access token rejected, reason: TOKEN EARLY');
          return cb('This token is early.');
        }

        // If audience doesn't match
        if(waterlock.config.jsonWebTokens.audience !== _token.aud){
          waterlock.logger.debug('access token rejected, reason: AUDIENCE');
          return cb('This token cannot be accepted for this domain.');
        }

        this.findUserFromToken(_token, cb);

      } catch(err){
        cb(err);
      }
    }
694142
private function _validate($token)
    {

        $request = $this->_httpClient->createRequest('POST', $this->_tokenServiceUrl . 'validate');
        $postBody = $request->getBody();


        // $postBody is an instance of GuzzleHttp\Post\PostBodyInterface
        $postBody->setField('service', $this->_appID);
        $postBody->setField('token', $token);

        // Send the POST request
        try {
            $response = $this->_httpClient->send($request);
        } catch (ClientException $e) {
            return "BAD_TOKEN";
        } catch (ServerException $e) {
            return "SERVER_ERROR";
        }

        return $response->json();

    }
481427
function isValidRegExp(context: ParserContext): boolean {
  const previousNonWsToken = context.token(context.count() - 1);

  let previousToken;
  if (context.defaultData.text !== "") {
    previousToken = context.createToken("default", context.defaultData.text);
  } else {
    previousToken = previousNonWsToken;
    // Okay if there is no previous token.
    if (!previousToken) return true;
  }

  // Since JavaScript doesn't require statement terminators, if the previous
  // token was whitespace and contained a newline, then we're good.
  if (
    previousToken.name === "default" &&
    previousToken.value.indexOf("\n") >= 0
  )
    return true;

  // In these case the / stands for division.
  if (util.contains(["keyword", "ident", "number"], previousNonWsToken.name))
    return false;

  if (
    previousNonWsToken.name === "punctuation" &&
    !util.contains(["(", "{", "[", ",", ";"], previousNonWsToken.value)
  )
    return false;

  return true;
}
810539
public function validate($token) {
		if( !isset($_SESSION[self::SESSION_KEY][$this->name]) ) {
			return false;
		}
		$TOKEN_SESSION = &$_SESSION[self::SESSION_KEY][$this->name];
		if( empty($token) || empty($TOKEN_SESSION) || !isset($TOKEN_SESSION[$token]) ) {
			return false;
		}
		$TOKEN_SESSION[$token]++;
		if( $TOKEN_SESSION[$token] >= $this->maxUsage ) {
			unset($TOKEN_SESSION[$token]);
		}
		return true;
	}
415359
function (params, cb) {
                  // validate input requirements vs what came back in params
                  var errorMessage = null;

                  _.forEach(Card.inputs, function (input, key) {
                    if (input.required && !params[key]) {
                      if (!errorMessage) {
                        errorMessage = '';
                      }
                      else {
                        errorMessage += ' | ';
                      }

                      errorMessage += 'No value provided for required input: ' + key;
                    }
                  });

                  cb(errorMessage, params);
                }
1012520
function validateCertChain(cert, cb)
{
  // walk up the certificate chain and collect all the certificates in an array
  var certs = [];
  while (cert && cert.issuerCertificate &&
  (cert.fingerprint !== cert.issuerCertificate.fingerprint))
  {
    certs.push(cert);
    cert = cert.issuerCertificate;
  }

  // create an array to store any errors encountered
  // while validating the certificate chain
  var errors = new Array(certs.length);

  /**
   * Called for every certificate as we traverse the certificate chain and
   * validate each one.
   *
   * @param certs
   * @param index
   */
  var eachCallback = function(certs, index)
  {
    var cert = certs[index];
    validateCert(cert, function(err, data)
    {
      completed++;
      errors[index] = err;

      // if we have an ocsp response, cache it
      if (data)
      {
        getOcspResponseCache().set(cert, data);
      }

      // if this is the last request to complete
      if (completed === certs.length)
      {
        // if we saw one or more errors, invoke the callback with the first
        // error we saw; otherwise invoke the callback without any error
        for (var errorIndex = 0, length = errors.length;
             errorIndex < length; errorIndex++)
        {
          var error = errors[errorIndex];
          if (error)
          {
            break;
          }
        }
        cb(error);
      }
    });
  };

  // fire off requests to validate all the certificates in the chain
  var completed = 0;
  for (var index = 0, length = certs.length; index < length; index++)
  {
    eachCallback(certs, index);
  }
}
800670
def _validate_token(self, token, scopes_required=None):
        """"""
        if scopes_required is None:
            scopes_required = []
        scopes_required = set(scopes_required)

        token_info = None
        valid_token = False
        has_required_scopes = False
        if token:
            try:
                token_info = self._get_token_info(token)
            except Exception as ex:
                token_info = {'active': False}
                logger.error('ERROR: Unable to get token info')
                logger.error(str(ex))

            valid_token = token_info.get('active', False)

            if 'aud' in token_info and \
                    current_app.config['OIDC_RESOURCE_CHECK_AUD']:
                valid_audience = False
                aud = token_info['aud']
                clid = self.client_secrets['client_id']
                if isinstance(aud, list):
                    valid_audience = clid in aud
                else:
                    valid_audience = clid == aud

                if not valid_audience:
                    logger.error('Refused token because of invalid '
                                 'audience')
                    valid_token = False

            if valid_token:
                token_scopes = token_info.get('scope', '').split(' ')
            else:
                token_scopes = []
            has_required_scopes = scopes_required.issubset(
                set(token_scopes))

            if not has_required_scopes:
                logger.debug('Token missed required scopes')

        if (valid_token and has_required_scopes):
            g.oidc_token_info = token_info
            return True

        if not valid_token:
            return 'Token required but invalid'
        elif not has_required_scopes:
            return 'Token does not have required scopes'
        else:
            return 'Something went wrong checking your token'
168901
function isSameToken(token1, token2) {
  if (isValidToken(token1) && isValidToken(token2)) {
    return String(token1) === String(token2);
  }

  return false;
}
694825
function validateSignature(fileName, signature, cb) {
   if (isUndefined(signature) || isUndefined(signature.codesign)) {
      cb();
      return;
   }

   if (isUndefined(codeSignCertFileName)) {
      cb(new Error('No code sign certificate file specified'));
      return;
   }

   var codeSignCert;

   try {
      codeSignCert = fs.readFileSync(codeSignCertFileName, 'utf8');
   } catch (err) {
      // unable to read codeSignCertFileName file
      cb(new Error('Error encountered trying to read ' + codeSignCertFileName));
      return;
   }

   var verify;
   try {
      verify = crypto.createVerify(signature.codesign.signatureAlgorithm);
   } catch (err) {
      console.warn('Unable to use signature algorithm: ' + signature.codesign.signatureAlgorithm + ' attempting to use default algorithm SHA256');
      try {
         verify = crypto.createVerify('SHA256');
      } catch (err) {
         cb(err);
         return;
      }
   }

   var stream = fs.createReadStream(fileName);

   stream.on('data', function (data) {
      verify.write(data);
   }).on('end', function () {
      verify.end();

      try {
         if (!verify.verify(codeSignCert, signature.codesign.signature, 'base64')) {
            var err = new Error('Signature validation failed');
            err.fileName = fileName;
            cb(err);
         } else {
            cb();
         }
      } catch (err) {
         cb(err);
         return;
      }
   }).on('error', function (err) {
      err.fileName = fileName;
      cb(err);
   });
}
783427
private void checkToken(String s) {
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			if (!TOKEN.get(ch)) {
				throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + s + "\"");
			}
		}
	}
1109629
private boolean _validate(Token token, Term term) {

		if (token == null) {
			return true;
		}

		Set<String> terms = token.getTerms();
		if ((!terms.contains(Token.ALL)) && !terms.contains(term.getName()) && !(terms.contains(":" + term.getNatureStr()))) {
			return true;
		}

		boolean flag = token.getRegexs().size() != 0;

		for (String regex : token.getRegexs()) {
			if (term.getName().matches(regex)) {
				flag = false;
				break;
			}
		}

		return flag;
	}
1214547
function validate(rules, args, cb) {
  try {
    _known(rules, args);
    _required(rules, args);

    Object.keys(args).forEach(function (arg) {

      var value = args[arg],
        ruleSet = rules[arg];

      try {
        ruleSet.forEach(function (rule) {
          if (rule !== 'required') {
            exports.checks[rule](value || '');
          }
        });
      } catch (e) {
        throw new Error(util.format(
          'Validation error - arg: %s, value: %s, desc: %s',
          arg, value, e.message));
      }
    });
    cb();
  } catch (e) {
    cb(e);
  }
}
1137484
function(token) {
        this.oauthClient.setCredentials(token);
        this.brain.set(this.TOKEN_KEY, token.access_token);
        if (token.refresh_token) {
            this.brain.set(this.REFRESH_KEY, token.refresh_token);
        }
        this.brain.set(this.EXPIRY_KEY, +token.expiry_date);
        this.brain.save();
        this.brain.resetSaveInterval(60);
    }
33985
public GitkitUser validateToken(String token) throws GitkitClientException {
    JsonObject jsonToken = validateTokenToJson(token);
    if (jsonToken == null) {
      return null;
    }
    return new GitkitUser()
        .setLocalId(jsonToken.get(JsonTokenHelper.ID_TOKEN_USER_ID).getAsString())
        .setEmail(jsonToken.get(JsonTokenHelper.ID_TOKEN_EMAIL).getAsString())
        .setCurrentProvider(jsonToken.has(JsonTokenHelper.ID_TOKEN_PROVIDER)
            ? jsonToken.get(JsonTokenHelper.ID_TOKEN_PROVIDER).getAsString()
            : null)
        .setName(jsonToken.has(JsonTokenHelper.ID_TOKEN_DISPLAY_NAME)
            ? jsonToken.get(JsonTokenHelper.ID_TOKEN_DISPLAY_NAME).getAsString()
            : null)
        .setPhotoUrl(jsonToken.has(JsonTokenHelper.ID_TOKEN_PHOTO_URL)
            ? jsonToken.get(JsonTokenHelper.ID_TOKEN_PHOTO_URL).getAsString()
            : null);
  }
1266903
function validIdOrProp(token) {
                    if (!token) {
                        return false;
                    }
                    if (token.string === ".") {
                        return true;
                    }
                    var type = token.type;
                    if (type === "variable-2" || type === "variable" || type === "property") {
                        return true;
                    }

                    return false;
                }
677087
private Action validate(Token token, Term term) {

		if (token == null) {
			return Action.OVER;
		}

		int[] range = token.getRange();

		if (_validate(token, term)) {
			if (range != null && range[0] == 0) {
				return Action.NEXT_TOKEN;
			} else if (range != null && step >= range[0] && step <= range[1]) {
				step = 0;
				return Action.NEXT_TOKEN;
			} else {
				return Action.STOP;
			}
		}


		if (range == null) {
			insertInto(term, token.getIndex());
			if (token.getNext() == null) {
				return Action.OVER;
			} else {
				return Action.NEXT_TERM_TOKEN;
			}
		} else {
			if (step < range[0]) {
				step++;
				insertInto(term, token.getIndex());
				return Action.NEXT_TERM;
			}

			if (step > range[1]) {
				return Action.STOP;
			}

			step++;
			if (step > range[0]) {
				if (_validate(token.getNext(), term)) {
					insertInto(term, token.getIndex());
					if (token.getNext() == null) {
						if (step >= range[1]) {
							return Action.OVER;
						} else {
							return Action.NEXT_TERM;
						}
					} else {
						return Action.NEXT_TERM;
					}
				} else {
					step = 0;
					return Action.NEXT_TOKEN;
				}
			} else {
				insertInto(term, token.getNext().getIndex());
				return Action.NEXT_TERM;
			}

		}


	}
724757
public final boolean isValidEmailConfirmationToken(String token) {
		Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier);
		return isValidToken(s, Config._EMAIL_TOKEN, token);
	}