Token verification

    Checks for the Authorization header and verifies using the verify_user function
332990
def token(request, response, verify_user, context=None, **kwargs):
    
    token = request.get_header('Authorization')
    if token:
        try:
            verified_token = verify_user(token)
        except TypeError:
            verified_token = verify_user(token, context)
        if verified_token:
            return verified_token
        else:
            return False
    return None
976269
def get_auth_header(self, user_payload):
        
        auth_token = self.get_auth_token(user_payload)
        return '{auth_header_prefix} {auth_token}'.format(
            auth_header_prefix=self.auth_header_prefix, auth_token=auth_token
        )
1122584
async def check_hook(self, request: HttpRequest):
        

        verify_token = request.query.get('hub.verify_token')

        if not verify_token:
            return json_response({
                'error': 'No verification token was provided',
            }, status=400)

        if verify_token == self.verify_token:
            return Response(text=request.query.get('hub.challenge', ''))

        return json_response({
            'error': 'could not find the page token in the configuration',
        })
77543
def check_auth(func):
    
    def wrapper(handler, *args, **kwargs):
        if handler.check_auth_header():
            return func(handler, *args, **kwargs)
    return wrapper
762283
def required(self, func):
        
        @wraps(func)
        def decorated(*args, **kwargs):
            """
            Actual wrapper to run the auth checks.
            """
            is_valid, user = self.authenticate()
            if not is_valid:
                return self.auth_failed()
            kwargs['user'] = user
            return func(*args, **kwargs)
        return decorated
1338954
public function verify( $user, $token ) {

		// Check Token
		if( $user->isVerifyTokenValid( $token ) ) {

			$modelClass	= static::$modelClass;

			// Find existing user
			$userToUpdate = $modelClass::findById( $user->id );

			// User need admin approval
			if( Yii::$app->core->isUserApproval() ) {

				$userToUpdate->verify();
			}
			// Direct approval and activation
			else {

				$userToUpdate->status = User::STATUS_ACTIVE;
			}

			$userToUpdate->unsetVerifyToken();

			$userToUpdate->update();

			return true;
		}

		return false;
	}
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
1343284
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
    
    key = encode_if_text(public_key)
    date_header = request.headers.get("Date")
    if not date_header:
        raise ValueError("Rquest Date header is missing")

    ts = parse_http_date(date_header)
    dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
    delta = datetime.timedelta(seconds=30)
    now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
    if dt < now - delta or dt > now + delta:
        raise ValueError("Request Date is too far in future or past")

    HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key)
97004
def check_token(self, user, token):
        
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS:
            return False

        return True
559028
function verifyHeader (currentHash, currentHeader, hashPrevBlock, prevHeader, target, isTestnet) {
  try {
    // check hashPrevBlock
    assert.equal(hashPrevBlock, currentHeader.hashPrevBlock)

    try {
      // check difficulty
      assert.equal(currentHeader.bits, target.bits)
      // check hash and target
      assert.equal(isGoodHash(currentHash, target.target), true)

    } catch (err) {
      // special case for testnet:
      // If no block has been found in 20 minutes, the difficulty automatically
      //  resets back to the minimum for a single block, after which it returns
      //  to its previous value.
      if (!(err instanceof assert.AssertionError &&
            isTestnet &&
            currentHeader.time - prevHeader.time > 1200)) {
        throw err
      }

      assert.equal(currentHeader.bits, MAX_BITS)
      assert.equal(isGoodHash(currentHash, MAX_TARGET), true)
    }
  } catch (err) {
    if (err instanceof assert.AssertionError) {
      throw new errors.Blockchain.VerifyHeaderError(currentHash, 'verification failed')
    }

    throw err
  }
}
1330719
function verify(rawMsg, rawSig, rawPub) {
  const msg = nacl.util.decodeUTF8(rawMsg);
  const sig = nacl.util.decodeBase64(rawSig);
  const pub = base58.decode(rawPub);
  const m = new Uint8Array(crypto_sign_BYTES + msg.length);
  const sm = new Uint8Array(crypto_sign_BYTES + msg.length);
  let i;
  for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
  for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];

  // Call to verification lib...
  return naclBinding.verify(m, sm, pub);
}
1362011
def identify(self, req, resp, resource, uri_kwargs):
        """"""
        header = req.get_header('Authorization', False)
        auth = header.split(' ') if header else None

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

        if len(auth) != 2:
            raise HTTPBadRequest(
                "Invalid Authorization header",
                "The Authorization header for Token auth should be in form:\n"
                "Authorization: Token <token_value>"
            )

        return auth[1]
597518
def verify_request_common(consumers, url, method, headers, params):
    
    log.debug("consumers %s", consumers)
    log.debug("url %s", url)
    log.debug("method %s", method)
    log.debug("headers %s", headers)
    log.debug("params %s", params)

    oauth_server = LTIOAuthServer(consumers)
    oauth_server.add_signature_method(
        SignatureMethod_PLAINTEXT_Unicode())
    oauth_server.add_signature_method(
        SignatureMethod_HMAC_SHA1_Unicode())

    # Check header for SSL before selecting the url
    if headers.get('X-Forwarded-Proto', 'http') == 'https':
        url = url.replace('http:', 'https:', 1)

    oauth_request = Request_Fix_Duplicate.from_request(
        method,
        url,
        headers=dict(headers),
        parameters=params
    )
    if not oauth_request:
        log.info('Received non oauth request on oauth protected page')
        raise LTIException('This page requires a valid oauth session '
                           'or request')
    try:
        # pylint: disable=protected-access
        oauth_consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_server.lookup_consumer(oauth_consumer_key)
        if not consumer:
            raise oauth2.Error('Invalid consumer.')
        oauth_server.verify_request(oauth_request, consumer, None)
    except oauth2.Error:
        # Rethrow our own for nice error handling (don't print
        # error message as it will contain the key
        raise LTIException("OAuth error: Please check your key and secret")

    return True
532182
async function _verifyToken (jwksClient, token) {
  const decoded = jwt.decode(token, { complete: true })
  const signingKey = await jwksClient.getSigningKeyAsync(decoded.header.kid)
  return jwt.verifyAsync(token, signingKey.publicKey || signingKey.rsaPublicKey)
}
1256230
def _authenticate_user(self, user, password):
        
        headers = self._get_headers()
        params = {
                'username': user,
                'password': password,
                'grant_type': 'password',
                }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate %s" % (user))
            response.raise_for_status()
1206136
def check_token(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        response = func(*args, **kwargs)
        if response.status_code == 401:
            raise InvalidToken('Access token invalid or no longer valid')
        else:
            return response
    return wrapper
961214
def verify_http_auth_token(self) -> bool:
        
        authorization_token = self.get_http_token()
        if authorization_token is not None:
            if self.verify_token(authorization_token):
                if self.data is not None:
                    self.data = self.data['data']
                    return True
                return False
            else:
                return False
        return False