Process validation GET requests.

        All modes of validation (OTP, OATH and PWHASH) must be explicitly
        enabled in `args' to be allowed.
162048
def do_GET(self):
        
        if self.path.startswith(args.serve_url):
            res = None
            log_res = None
            mode = None
            params = urlparse.parse_qs(self.path[len(args.serve_url):])
            if "otp" in params:
                if args.mode_short_otp:
                    # YubiKey internal db OTP in KSM mode
                    mode = 'YubiKey OTP (short)'
                    res = validate_yubikey_otp_short(self, params)
                elif args.mode_otp:
                    # YubiKey internal db OTP validation 2.0
                    mode = 'YubiKey OTP'
                    res = validate_yubikey_otp(self, params)
                    #status = [x for x in res.split('\n') if x.startswith("status=")]
                    #if len(status) == 1:
                    #    res = status[0][7:]
                    log_res = '&'.join(res.split('\n'))
                else:
                    res = "ERR 'otp/otp2' disabled"
            elif "hotp" in params:
                if args.mode_hotp:
                    mode = 'OATH-HOTP'
                    res = validate_oath_hotp(self, params)
                else:
                    res = "ERR 'hotp' disabled"
            elif "totp" in params:
                if args.mode_totp:
                    mode = 'OATH-TOTP'
                    res = validate_oath_totp(self, params)
                else:
                    res = "ERR 'totp' disabled"
            elif "pwhash" in params:
                if args.mode_pwhash:
                    mode = 'Password hash'
                    res = validate_pwhash(self, params)
                else:
                    res = "ERR 'pwhash' disabled"

            if not log_res:
                log_res = res

            self.log_message("%s validation result: %s -> %s", mode, self.path, log_res)

            if res != None:
                self.send_response(200)
                self.send_header('Content-type', 'text/plain')
                self.end_headers()
                self.wfile.write(res)
                self.wfile.write("\n")
            else:
                self.log_error ("No validation result to '%s' (responding 403)" % (self.path))
                self.send_response(403, 'Forbidden')
                self.end_headers()
        else:
            self.log_error ("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, args.serve_url))
            self.send_response(403, 'Forbidden')
            self.end_headers()
1355805
def processCheckIn(request):
    '''
    
    '''

    if request.method == 'POST':
        event_id = request.POST.get('event_id')
        reg_ids = request.POST.getlist('reg_id')

        if not event_id:
            return HttpResponse(_("Error at start."))

        # Get all possible registrations, so that we can set those that are not included to False (and set those that are included to True)
        all_eventreg = list(EventRegistration.objects.filter(event__id=event_id))

        for this_reg in all_eventreg:
            if str(this_reg.registration.id) in reg_ids and not this_reg.checkedIn:
                this_reg.checkedIn = True
                this_reg.save()
            elif str(this_reg.registration.id) not in reg_ids and this_reg.checkedIn:
                this_reg.checkedIn = False
                this_reg.save()
        return HttpResponse("OK.")
1251024
function validateHTTPInput( $http, $base, $workflowEvent, &$validation )
    {
        $returnState = eZInputValidator::STATE_ACCEPTED;
        $reason = array();

        if ( !$http->hasSessionVariable( 'BrowseParameters' ) )
        {
            // No validation when deleting to avoid blocking deletion of invalid items
            if (
                $http->hasPostVariable( 'DeleteApproveUserIDArray_' . $workflowEvent->attribute( 'id' ) ) ||
                $http->hasPostVariable( 'DeleteApproveGroupIDArray_' . $workflowEvent->attribute( 'id' ) )
            )
            {
                return eZInputValidator::STATE_ACCEPTED;
            }

            // check approve-users
            $approversIDs = array_unique( $this->attributeDecoder( $workflowEvent, 'approve_users' ) );
            if ( is_array( $approversIDs ) and
                 count( $approversIDs ) > 0 )
            {
                $returnState = eZApproveType::validateUserIDList( $approversIDs, $reason );
            }
            else
                $returnState = false;

            if ( $returnState != eZInputValidator::STATE_INVALID )
            {
                // check approve-groups
                $userGroupIDList = array_unique( $this->attributeDecoder( $workflowEvent, 'approve_groups' ) );
                if ( is_array( $userGroupIDList ) and
                     count( $userGroupIDList ) > 0 )
                {
                    $returnState = eZApproveType::validateGroupIDList( $userGroupIDList, $reason );
                }
                else if ( $returnState === false )
                {
                    // if no one user or user-group was passed as approvers
                    $returnState = eZInputValidator::STATE_INVALID;
                    $reason[ 'text' ] = "There must be passed at least one valid user or user group who approves content for the event.";
                }

                // check excluded-users
                /*
                if ( $returnState != eZInputValidator::STATE_INVALID )
                {
                    // TODO:
                    // ....
                }
                */

                // check excluded-groups
                if ( $returnState != eZInputValidator::STATE_INVALID )
                {
                    $userGroupIDList = array_unique( $this->attributeDecoder( $workflowEvent, 'selected_usergroups' ) );
                    if ( is_array( $userGroupIDList ) and
                         count( $userGroupIDList ) > 0 )
                    {
                        $returnState = eZApproveType::validateGroupIDList( $userGroupIDList, $reason );
                    }
                }
            }
        }
        else
        {
            $browseParameters = $http->sessionVariable( 'BrowseParameters' );
            if ( isset( $browseParameters['custom_action_data'] ) )
            {
                $customData = $browseParameters['custom_action_data'];
                if ( isset( $customData['event_id'] ) and
                     $customData['event_id'] == $workflowEvent->attribute( 'id' ) )
                {
                    if ( !$http->hasPostVariable( 'BrowseCancelButton' ) and
                         $http->hasPostVariable( 'SelectedObjectIDArray' ) )
                    {
                        $objectIDArray = $http->postVariable( 'SelectedObjectIDArray' );
                        if ( is_array( $objectIDArray ) and
                             count( $objectIDArray ) > 0 )
                        {
                            switch( $customData['browse_action'] )
                            {
                            case "AddApproveUsers":
                                {
                                    $returnState = eZApproveType::validateUserIDList( $objectIDArray, $reason );
                                } break;
                            case 'AddApproveGroups':
                            case 'AddExcludeUser':
                                {
                                    $returnState = eZApproveType::validateGroupIDList( $objectIDArray, $reason );
                                } break;
                            case 'AddExcludedGroups':
                                {
                                    // TODO:
                                    // .....
                                } break;
                            }
                        }
                    }
                }
            }
        }

        if ( $returnState == eZInputValidator::STATE_INVALID )
        {
            $validation[ 'processed' ] = true;
            $validation[ 'events' ][] = array( 'id' => $workflowEvent->attribute( 'id' ),
                                               'placement' => $workflowEvent->attribute( 'placement' ),
                                               'workflow_type' => &$this,
                                               'reason' => $reason );
        }
        return $returnState;
    }
146357
async def validation_middleware(request: web.Request, handler) -> web.Response:
    
    orig_handler = request.match_info.handler
    if not hasattr(orig_handler, "__schemas__"):
        if not issubclass_py37fix(orig_handler, web.View):
            return await handler(request)
        sub_handler = getattr(orig_handler, request.method.lower(), None)
        if sub_handler is None:
            return await handler(request)
        if not hasattr(sub_handler, "__schemas__"):
            return await handler(request)
        schemas = sub_handler.__schemas__
    else:
        schemas = orig_handler.__schemas__
    kwargs = {}
    for schema in schemas:
        data = await parser.parse(
            schema["schema"], request, locations=schema["locations"]
        )
        if data:
            kwargs.update(data)
    kwargs.update(request.match_info)
    request[request.app["_apispec_request_data_name"]] = kwargs
    return await handler(request)
1145332
def _validate_client(self, request, data):
        
        client = self.get_client(data.get('client_id'))

        if client is None:
            raise OAuthError({
                'error': 'unauthorized_client',
                'error_description': _("An unauthorized client tried to access"
                    " your resources.")
            })

        form = self.get_request_form(client, data)

        if not form.is_valid():
            raise OAuthError(form.errors)

        return client, form.cleaned_data
1314642
def _pv_required(opts, key, is_required=true)
        if is_required
          if (opts.has_key?(key.to_s) && !opts[key.to_s].nil?) ||
              (opts.has_key?(key.to_sym) && !opts[key.to_sym].nil?)
            true
          else
            raise ValidationFailed, "Required argument #{key} is missing!"
          end
        end
      end
830642
def validate_get_arguments(kwargs):
    # type: (Dict[Text, Any]) -> None
    
    for arg in ("AttributesToGet", "ProjectionExpression"):
        if arg in kwargs:
            raise InvalidArgumentError('"{}" is not supported for this operation'.format(arg))

    if kwargs.get("Select", None) in ("SPECIFIC_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES"):
        raise InvalidArgumentError('Scan "Select" value of "{}" is not supported'.format(kwargs["Select"]))
1262767
def read_validate_params(self, request):
        
        self.client = self.client_authenticator.by_identifier(request)

        response_type = request.get_param("response_type")

        if self.client.response_type_supported(response_type) is False:
            raise OAuthInvalidError(error="unauthorized_client")

        self.state = request.get_param("state")

        self.scope_handler.parse(request, "query")

        return True
448139
def request(*args)
      response = make_request(*args)
      # binding.pry unless response.kind_of?(Net::HTTPSuccess)
      raise HTTPError, response unless response.is_a?(Net::HTTPSuccess)
      response
    end
500200
def verify_request_method env
        allowed = ALLOWED_METHODS
        allowed |= ALLOWED_METHODS_PRIVATE if whitelisted?(env)
        if !allowed.include?(env[METHOD])
          raise "Request method #{env[METHOD]} not allowed"
        end
      end
623023
def validate_request(request):
    
    if getattr(settings, 'BASICAUTH_DISABLE', False):
        # Not to use this env
        return True

    if 'HTTP_AUTHORIZATION' not in request.META:
        return False

    authorization_header = request.META['HTTP_AUTHORIZATION']
    ret = extract_basicauth(authorization_header)
    if not ret:
        return False

    username, password = ret

    raw_pass = settings.BASICAUTH_USERS.get(username)
    if raw_pass is None:
        return False

    # To avoid timing atacks
    # https://security.stackexchange.com/questions/83660/simple-string-comparisons-not-secure-against-timing-attacks
    if not constant_time_compare(raw_pass, password):
        return False

    request.META['REMOTE_USER'] = username
    return True
734466
function validArguments() {
    var conditions = {
      'port and host': function () {
        return port && host;
      },
      'options.target or options.router': function () {
        return options && (options.router ||
          (options.target && options.target.host && options.target.port));
      },
      'or proxy handlers': function () {
        return handlers && handlers.length;
      }
    }

    var missing = Object.keys(conditions).filter(function (name) {
      return !conditions[name]();
    });

    if (missing.length === 3) {
      message = 'Cannot proxy without ' + missing.join(', ');
      return false;
    }

    return true;
  }
1308187
def validate(self):
        
        endpoint = '/validate'

        payload = dict(accessToken=self.access_token)
        rep = self._ygg_req(endpoint, payload)
        return not bool(rep)
1045636
def _validate_param(self, path, obj, _):
        
        errs = []

        if obj.allowMultiple:
            if not obj.paramType in ('path', 'query', 'header'):
                errs.append('allowMultiple should be applied on path, header, or query parameters')
            if obj.type == 'array':
                errs.append('array Type with allowMultiple is not supported.')

        if obj.paramType == 'body' and obj.name not in ('', 'body'):
            errs.append('body parameter with invalid name: {0}'.format(obj.name))

        if obj.type == 'File':
            if obj.paramType != 'form':
                errs.append('File parameter should be form type: {0}'.format(obj.name))
            if 'multipart/form-data' not in obj._parent_.consumes:
                errs.append('File parameter should consume multipart/form-data: {0}'.format(obj.name))

        if obj.type == 'void':
            errs.append('void is only allowed in Operation object.')

        return path, obj.__class__.__name__, errs
1331355
def parse_args():
    
    global default_device

    parser = argparse.ArgumentParser(description = "Validate YubiKey OTP's using YubiHSM",
                                     add_help=True
                                     )
    parser.add_argument('-D', '--device',
                        dest='device',
                        default=default_device,
                        required=False,
                        help='YubiHSM device (default : %s).' % default_device
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation.'
                        )
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=False,
                        help='Enable debug operation.'
                        )
    group = parser.add_argument_group('Modes', 'What you want to validate')
    mode_group = group.add_mutually_exclusive_group(required = True)
    mode_group.add_argument('--otp',
                            dest='otp',
                            help='The output from your YubiKey.'
                            )
    mode_group.add_argument('--oath',
                            dest='oath',
                            help='The output from your OATH-HOTP token.'
                            )

    args = parser.parse_args()
    return args
1347214
def validate(self):
        

        try:
            resp = self.request().get(self.validate_url, verify=self.verifySSL).json()
        except TokenExpiredError:
            return False
        except AttributeError:
            return False

        if 'error' in resp:
            return False
        return True
380663
def validation_requests(self):
        
        if self._validation_requests is None:
            self._validation_requests = ValidationRequestList(self._version, account_sid=self._solution['sid'], )
        return self._validation_requests