Return thing, but abort validation if request.user cannot edit.
169981
def run(self, value, errors, request):
        """"""
        thing = super(AccessibleDBThing, self).run(value, errors, request)
        if errors:
            return None
        if not thing.can_access(request.user):
            message = 'Insufficient permissions for {0}'.format(self.param)
            raise HTTPForbidden(message)
        return thing
1004288
public function edit(): void
    {
        $oUri   = Factory::service('Uri');
        $oInput = Factory::service('Input');

        if ($oUri->segment(5) != activeUser('id') && !userHasPermission('admin:auth:accounts:editOthers')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        /**
         * Get the user's data; loaded early because it's required for the user_meta_cols
         * (we need to know the group of the user so we can pull up the correct cols/rules)
         */

        $oSession   = Factory::service('Session', 'nails/module-auth');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $oUser      = $oUserModel->getById($oUri->segment(5));

        if (!$oUser) {
            $oSession->setFlashData('error', lang('accounts_edit_error_unknown_id'));
            $this->returnToIndex();
        }

        //  Non-superusers editing superusers is not cool
        if (!$oUserModel->isSuperuser() && userHasPermission('superuser', $oUser)) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/dashboard';
            redirect($sReturnTo);
        }

        //  Is this user editing someone other than themselves? If so, do they have permission?
        if (activeUser('id') != $oUser->id && !userHasPermission('admin:auth:accounts:editOthers')) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/dashboard';
            redirect($sReturnTo);
        }

        // --------------------------------------------------------------------------

        /**
         * Load the user_meta_cols; loaded here because it's needed for both the view
         * and the form validation
         */

        $oDb           = Factory::service('Database');
        $oConfig       = Factory::service('Config');
        $aUserMetaCols = $oConfig->item('user_meta_cols');
        $iGroupId      = (int) $oInput->post('group_id') ?: $oUser->group_id;

        if (isset($aUserMetaCols[$iGroupId])) {
            $this->data['user_meta_cols'] = $aUserMetaCols[$oUser->group_id];
        } else {
            $this->data['user_meta_cols'] = null;
        }

        //  Set fields to ignore by default
        $this->data['ignored_fields'] = [
            'id',
            'user_id',
        ];

        /**
         * If no cols were found, DESCRIBE the user_meta_app table - where possible you
         * should manually set columns, including datatypes
         */

        if (is_null($this->data['user_meta_cols'])) {

            $aResult                      = $oDb->query('DESCRIBE `' . NAILS_DB_PREFIX . 'user_meta_app`')->result();
            $this->data['user_meta_cols'] = [];

            foreach ($aResult as $col) {

                //  Always ignore some fields
                if (array_search($col->Field, $this->data['ignored_fields']) !== false) {
                    continue;
                }

                // --------------------------------------------------------------------------

                //  Attempt to detect datatype
                $sDataType = 'string';
                $type      = 'text';

                switch (strtolower($col->Type)) {

                    case 'text':
                        $type = 'textarea';
                        break;

                    case 'date':
                        $sDataType = 'date';
                        break;

                    case 'tinyint(1) unsigned':
                        $sDataType = 'bool';
                        break;
                }

                // --------------------------------------------------------------------------

                $this->data['user_meta_cols'][$col->Field] = [
                    'datatype' => $sDataType,
                    'type'     => $type,
                    'label'    => ucwords(str_replace('_', ' ', $col->Field)),
                ];
            }
        }

        // --------------------------------------------------------------------------

        //  Validate if we're saving, otherwise get the data and display the edit form
        if ($oInput->post()) {

            //  Load validation library
            $oFormValidation = Factory::service('FormValidation');

            // --------------------------------------------------------------------------

            //  Define user table rules
            $oFormValidation->set_rules('first_name', '', 'trim|required');
            $oFormValidation->set_rules('last_name', '', 'trim|required');
            $oFormValidation->set_rules('gender', '', 'required');
            $oFormValidation->set_rules('dob', '', 'valid_date');
            $oFormValidation->set_rules('timezone', '', 'required');
            $oFormValidation->set_rules('datetime_format_date', '', 'required');
            $oFormValidation->set_rules('datetime_format_time', '', 'required');

            // --------------------------------------------------------------------------

            //  Define user_meta table rules
            foreach ($this->data['user_meta_cols'] as $col => $value) {

                $sDataType = isset($value['datatype']) ? $value['datatype'] : 'string';
                $label     = isset($value['label']) ? $value['label'] : ucwords(str_replace('_', ' ', $col));

                //  Some data types require different handling
                switch ($sDataType) {

                    case 'date':
                        //  Dates must validate
                        if (isset($value['validation'])) {
                            $oFormValidation->set_rules($col, $label, $value['validation'] . '|valid_date[' . $col . ']');
                        } else {
                            $oFormValidation->set_rules($col, $label, 'valid_date[' . $col . ']');
                        }
                        break;

                    // --------------------------------------------------------------------------

                    case 'file':
                    case 'upload':
                    case 'string':
                    default:
                        if (isset($value['validation'])) {
                            $oFormValidation->set_rules($col, $label, $value['validation']);
                        }
                        break;
                }
            }

            // --------------------------------------------------------------------------

            //  Set messages
            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('min_length', lang('fv_min_length'));
            $oFormValidation->set_message('alpha_dash_period', lang('fv_alpha_dash_period'));
            $oFormValidation->set_message('is_natural_no_zero', lang('fv_required'));
            $oFormValidation->set_message('valid_date', lang('fv_valid_date'));
            $oFormValidation->set_message('valid_datetime', lang('fv_valid_datetime'));

            // --------------------------------------------------------------------------

            //  Data is valid; ALL GOOD :]
            if ($oFormValidation->run()) {

                //  Define the data var
                $aData = [];

                // --------------------------------------------------------------------------

                //  If we have a profile image, attempt to upload it
                if (isset($_FILES['profile_img']) && $_FILES['profile_img']['error'] != UPLOAD_ERR_NO_FILE) {

                    $oCdn   = Factory::service('Cdn', 'nails/module-cdn');
                    $object = $oCdn->objectReplace($oUser->profile_img, 'profile-images', 'profile_img');

                    if ($object) {

                        $aData['profile_img'] = $object->id;

                    } else {

                        $this->data['upload_error'] = $oCdn->getErrors();
                        $this->data['error']        = lang('accounts_edit_error_profile_img');
                    }
                }

                // --------------------------------------------------------------------------

                if (!isset($this->data['upload_error'])) {

                    //  Set basic data

                    $aData['temp_pw']              = stringToBoolean($oInput->post('temp_pw', true));
                    $aData['reset_mfa_question']   = stringToBoolean($oInput->post('reset_mfa_question', true));
                    $aData['reset_mfa_device']     = stringToBoolean($oInput->post('reset_mfa_device', true));
                    $aData['first_name']           = $oInput->post('first_name', true);
                    $aData['last_name']            = $oInput->post('last_name', true);
                    $aData['username']             = $oInput->post('username', true);
                    $aData['gender']               = $oInput->post('gender', true);
                    $aData['dob']                  = $oInput->post('dob', true);
                    $aData['dob']                  = !empty($aData['dob']) ? $aData['dob'] : null;
                    $aData['timezone']             = $oInput->post('timezone', true);
                    $aData['datetime_format_date'] = $oInput->post('datetime_format_date', true);
                    $aData['datetime_format_time'] = $oInput->post('datetime_format_time', true);

                    if ($oInput->post('password', true)) {
                        $aData['password'] = $oInput->post('password', true);
                    }

                    //  Set meta data
                    foreach ($this->data['user_meta_cols'] as $col => $value) {

                        $mValue = $oInput->post($col, true);

                        //  Should the field be made null on empty?
                        if (!empty($value['nullOnEmpty']) && empty($mValue)) {
                            $mValue = null;
                        }

                        switch ($value['datatype']) {

                            case 'bool':
                            case 'boolean':
                                //  Convert all to boolean from string
                                $aData[$col] = stringToBoolean($mValue);
                                break;

                            case 'file':
                            case 'upload':
                                //  File uploads should be an integer, or if empty, null
                                $aData[$col] = (int) $mValue ?: null;
                                break;

                            default:
                                $aData[$col] = $mValue;
                                break;
                        }
                    }

                    // --------------------------------------------------------------------------

                    //  Update account
                    if ($oUserModel->update($oInput->post('id'), $aData)) {

                        $name                  = $oInput->post('first_name', true) . ' ' . $oInput->post('last_name', true);
                        $this->data['success'] = lang('accounts_edit_ok', [title_case($name)]);
                        // --------------------------------------------------------------------------

                        //  Set Admin changelogs
                        $name = '#' . number_format($oInput->post('id'));

                        if ($aData['first_name']) {
                            $name .= ' ' . $aData['first_name'];
                        }

                        if ($aData['last_name']) {
                            $name .= ' ' . $aData['last_name'];
                        }

                        foreach ($aData as $field => $value) {
                            if (isset($oUser->$field)) {
                                $this->oChangeLogModel->add(
                                    'updated',
                                    'a',
                                    'user',
                                    $oInput->post('id'),
                                    $name,
                                    'admin/auth/accounts/edit/' . $oInput->post('id'),
                                    $field,
                                    $oUser->$field,
                                    $value,
                                    false
                                );
                            }
                        }

                        // --------------------------------------------------------------------------

                        //  refresh the user object
                        $oUser = $oUserModel->getById($oInput->post('id'));

                        //  The account failed to update, feedback to user
                    } else {

                        $this->data['error'] = lang(
                            'accounts_edit_fail',
                            implode(', ', $oUserModel->getErrors())
                        );
                    }
                }

                //  Update failed for another reason
            } else {

                $this->data['error'] = lang('fv_there_were_errors');
            }
        }
        //  End POST() check

        // --------------------------------------------------------------------------

        //  Get the user's meta data
        if ($this->data['user_meta_cols']) {

            $oDb->select(implode(',', array_keys($this->data['user_meta_cols'])));
            $oDb->where('user_id', $oUser->id);
            $aUserMeta = (array) $oDb->get(NAILS_DB_PREFIX . 'user_meta_app')->row();

        } else {
            $aUserMeta = [];
        }

        // --------------------------------------------------------------------------

        //  Get the user's email addresses
        $this->data['user_emails'] = $oUserModel->getEmailsForUser($oUser->id);

        // --------------------------------------------------------------------------

        $this->data['user_edit'] = $oUser;
        $this->data['user_meta'] = $aUserMeta;

        //  Page Title
        $this->data['page']->title = lang(
            'accounts_edit_title',
            title_case($oUser->first_name . ' ' . $oUser->last_name)
        );

        //  Get the groups, timezones and languages
        $oUserGroupModel      = Factory::model('UserGroup', 'nails/module-auth');
        $this->data['groups'] = $oUserGroupModel->getAll();

        $oLanguageService        = Factory::service('Language');
        $this->data['languages'] = $oLanguageService->getAllEnabledFlat();

        $oDateTimeService               = Factory::service('DateTime');
        $this->data['timezones']        = $oDateTimeService->getAllTimezone();
        $this->data['date_formats']     = $oDateTimeService->getAllDateFormat();
        $this->data['time_formats']     = $oDateTimeService->getAllTimeFormat();
        $this->data['default_timezone'] = $oDateTimeService->getTimezoneDefault();

        //  Fetch any user uploads
        if (Components::exists('nails/module-cdn')) {
            $oCdn                       = Factory::service('Cdn', 'nails/module-cdn');
            $this->data['user_uploads'] = $oCdn->getObjectsForUser($oUser->id);
        }

        // --------------------------------------------------------------------------

        if (activeUser('id') == $oUser->id) {

            switch (strtolower(activeUser('gender'))) {

                case 'male':
                    $this->data['notice'] = lang('accounts_edit_editing_self_m');
                    break;

                case 'female':
                    $this->data['notice'] = lang('accounts_edit_editing_self_f');
                    break;

                default:
                    $this->data['notice'] = lang('accounts_edit_editing_self_u');
                    break;
            }
        }

        $oUserPasswordModel          = Factory::model('UserPassword', 'nails/module-auth');
        $this->data['passwordRules'] = $oUserPasswordModel->getRulesAsString($oUser->group_id);

        // --------------------------------------------------------------------------

        //  Load views
        Helper::loadView('edit');
    }
266703
def get_allow_future(self):
        
        qs = self.get_queryset()
        post_edit_permission = '{}.edit_{}'.format(
            qs.model._meta.app_label, qs.model._meta.model_name
        )
        if self.request.user.has_perm(post_edit_permission):
            return True
        return False
1139456
def handle_error(self, error, req, schema):
        

        status_code = getattr(error, "status_code", self.DEFAULT_VALIDATION_STATUS)
        abort(status_code, exc=error, messages=error.messages, schema=schema)
334508
def return! request = nil, result = nil, & block
      if (200..207).include? code
        self
      elsif [301, 302, 307].include? code
        unless [:get, :head].include? args[:method]
          raise Exceptions::EXCEPTIONS_MAP[code].new(self, code)
        else
          follow_redirection(request, result, & block)
        end
      elsif code == 303
        args[:method] = :get
        args.delete :payload
        follow_redirection(request, result, & block)
      elsif Exceptions::EXCEPTIONS_MAP[code]
        raise Exceptions::EXCEPTIONS_MAP[code].new(self, code)
      else
        raise RequestFailed.new(self, code)
      end
    end
600168
def invalid(cls, data, context=None):
        """"""
        return cls(cls.TagType.INVALID, data, context)
1074537
def reject():
    """"""

    auth_message = ('Could not verify your access level for that URL.'
                    'Please login with proper credentials.')
    auth_message = json.dumps({'_status': 'Unauthorized',
                               'message': auth_message})

    headers = {'WWW-Authenticate': 'Basic realm="Login required"'}
    return flask.Response(auth_message, 401, headers=headers,
                          content_type='application/json')
1218716
def validate(user_input, ret_errs=False, print_errs=False):
    

    errs = run_validator(user_input)
    passed = len(errs) == 0

    if print_errs:
        for err in errs:
            print(err)

    if ret_errs:
        return passed, errs

    return passed
1248372
def valid_action_request(method):
    

    @functools.wraps(method)
    def _wrapper(self, *args, **kwargs):
        assert isinstance(self, BaseRequestHandler)
        if not self.is_request_valid:
            return self.reply_bad_request()

        try:
            return method(self, *args, **kwargs)
        except UserWarning as e:
            return self.reply_server_error(e)
        except Exception as e:
            return self.reply_server_error(e)

    return _wrapper
1028930
def _handle_post(self, request):
        # type: (Post) -> CallbackResponses
        """"""
        method_name = request.path[1]

        method = self._block[method_name]
        assert isinstance(method, MethodModel), \
            "Cannot Post to %s which is a %s" % (method.path, type(method))
        self.check_field_writeable(method)

        post_function = self.get_post_function(method_name)
        args = method.validate(request.parameters)

        with self.lock_released:
            result = post_function(**args)

        # Don't need to serialize as the result should be immutable
        ret = [request.return_response(result)]
        return ret
326712
def _cancel_callback(self, request_id):
        """"""
        def callback(future):
            if future.cancelled():
                self.notify(CANCEL_METHOD, {'id': request_id})
                future.set_exception(JsonRpcRequestCancelled())
        return callback
1029922
def validate(self, postdata, user = None):
        """"""
        clam.common.util.printdebug("Validating inputtemplate " + self.id + "...")
        errors, parameters, _  = processparameters(postdata, self.parameters, user)
        return errors, parameters
1273960
function validationMiddleware (err, req, res, next) {
  if (!err instanceof ValidationError) return next(err);
  return res.status(err.status).send({ errors: err.errors });
}
176038
def abort(code, error=None, message=None):
    
    if error is None:
        flask_abort(code)
    elif isinstance(error, Response):
        error.status_code = code
        flask_abort(code, response=error)
    else:
        body = {
            "status": code,
            "error": error,
            "message": message
        }
        flask_abort(code, response=export(body, code))
1177820
def validate(self, qstr, editing=True):
        """"""
        if self.selected_text == qstr and qstr != '':
            self.valid.emit(True, True)
            return

        valid = self.is_valid(qstr)
        if editing:
            if valid:
                self.valid.emit(True, False)
            else:
                self.valid.emit(False, False)
1329384
def form_invalid(self, form):
        
        meta = getattr(self.model, '_meta')

        #noinspection PyUnresolvedReferences
        messages.error(
            self.request,
            _(u'The {0} could not be saved due to errors.').format(
                meta.verbose_name.lower()
            )
        )

        return super(BaseEditView, self).form_invalid(form)
262410
def can_edit(self, user=None, request=None):
        
        can = False
        if request and not self.owner:
            if (getattr(settings, "UMAP_ALLOW_ANONYMOUS", False)
                    and self.is_anonymous_owner(request)):
                can = True
        if self.edit_status == self.ANONYMOUS:
            can = True
        elif not user.is_authenticated:
            pass
        elif user == self.owner:
            can = True
        elif self.edit_status == self.EDITORS and user in self.editors.all():
            can = True
        return can