def create_organization_object(org_name, creator, attrs=None): '''Creates an OrganizationProfile object without saving to the database''' attrs = attrs if attrs else {} name = attrs.get('name', org_name) if attrs else org_name first_name, last_name = _get_first_last_names(name) email = attrs.get('email', u'') if attrs else u'' new_user = User( username=org_name, first_name=first_name, last_name=last_name, email=email, is_active=getattr( settings, 'ORG_ON_CREATE_IS_ACTIVE', True)) new_user.save() try: registration_profile = RegistrationProfile.objects.create_profile( new_user) except IntegrityError: raise ValidationError(_( u"%s already exists" % org_name )) if email: site = Site.objects.get(pk=settings.SITE_ID) registration_profile.send_activation_email(site) profile = OrganizationProfile( user=new_user, name=name, creator=creator, created_by=creator, city=attrs.get('city', u''), country=attrs.get('country', u''), organization=attrs.get('organization', u''), home_page=attrs.get('home_page', u''), twitter=attrs.get('twitter', u'')) return profile
def validate_against_all_terms(self): course_terms = CourseTerm.get_terms_for_semester( semester=self.semester, day=self.dayOfWeek, classrooms=[self.classroom], start_time=self.start_time, end_time=self.end_time) from .term import Term candidate_days = self.semester.get_all_days_of_week( self.dayOfWeek, start_date=max(datetime.now().date(), self.semester.lectures_beginning)) terms = Term.get_terms_for_dates(dates=candidate_days, classroom=self.classroom, start_time=self.start_time, end_time=self.end_time) msg_list = [] if course_terms: for t in course_terms: msg_list.append( 'W tym samym czasie w tej sali odbywają się zajęcia: ' + t.group.course.name + ' ' + str(t)) if terms: for t in terms: if t.event.reservation != self and t.event.type != Event.TYPE_CLASS: msg_list.append( 'W tym samym czasie ta sala jest zarezerwowana (wydarzenie): ' + str(t.event) + ' ' + str(t)) if len(msg_list) > 0: raise ValidationError(message={'__all__': msg_list}, code='overlap')
def clean(self): super().clean() # Validate the field's default value (if any) if self.default is not None: try: self.validate(self.default) except ValidationError as err: raise ValidationError({"default": f'Invalid default value "{self.default}": {err.message}'}) # Minimum/maximum values can be set only for numeric fields if self.validation_minimum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER: raise ValidationError({"validation_minimum": "A minimum value may be set only for numeric fields"}) if self.validation_maximum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER: raise ValidationError({"validation_maximum": "A maximum value may be set only for numeric fields"}) # Regex validation can be set only for text fields regex_types = ( CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_URL, ) if self.validation_regex and self.type not in regex_types: raise ValidationError( {"validation_regex": "Regular expression validation is supported only for text and URL fields"} ) # Choices can be set only on selection fields if self.choices and self.type != CustomFieldTypeChoices.TYPE_SELECT: raise ValidationError({"choices": "Choices may be set only for custom selection fields."}) # A selection field must have at least two choices defined if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.choices and len(self.choices) < 2: raise ValidationError({"choices": "Selection fields must specify at least two choices."}) # A selection field's default (if any) must be present in its available choices if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.default and self.default not in self.choices: raise ValidationError( {"default": f"The specified default value ({self.default}) is not listed as an available choice."} )
def clean(self): # todo: use this validation in user form as well cleaned_data = super().clean() errors = {} # At least 1 url has to be defined if not (cleaned_data.get('url_program') or cleaned_data.get('url_mou') or cleaned_data.get('url_assess') or cleaned_data.get('url_job') or cleaned_data.get('url_other')): msg = 'You must provide at least one link to more information. Please ensure at least one of the boxes in this section is filled in.' errors.update({ 'url_program': msg, 'url_mou': msg, 'url_assess': msg, 'url_job': msg, 'url_other': msg, }) # Exactly 1 strategy must be primary! strategies = [ 'strategy_adaptation', 'strategy_adoption', 'strategy_awareness', 'strategy_curation', 'strategy_pedagogy', 'strategy_publication', 'strategy_review', 'strategy_research' ] primary = sum(1 for strategy in strategies if cleaned_data.get(strategy, '') == 'primary') if primary != 1: msg = 'Must select exactly one option as Primary. May select any number (including 0) as Secondary.' errors.update({strategy: msg for strategy in strategies}) if errors: raise ValidationError(errors) return cleaned_data
def signin(request): print 'form data valid' if request.method == 'POST': login_form = SignInForm(request.POST) if login_form.is_valid(): print 'form data valid' cleaned_cred = login_form.cleaned_data print cleaned_cred user = authenticate(username=cleaned_cred['email'], password=cleaned_cred['password']) if user: if user.is_active: django_login(request, user) # check if the user has created entity profile role = request.user.role id = request.user.id if not request.user.gender: url = reverse_user_edit(role) return HttpResponseRedirect( reverse(url, kwargs={'pk': id})) else: raise ValidationError( "Please check your email and validate your account") else: print 'incorrect login' messages.error(request, 'Invalid login details') return HttpResponseRedirect(reverse('projects:view-startup')) else: print login_form.is_valid() print login_form.errors return render(request, 'index/signin.html', {'form': login_form}) else: login_form = SignInForm() return render(request, 'index/signin.html', {'form': login_form})
def validate_course_key(self, course_key, branch=ModuleStoreEnum.BranchName.draft): """ Validates the course_key that would be used by maintenance app views. Arguments: course_key (string): a course key branch: a course locator branch, default value is ModuleStoreEnum.BranchName.draft . values can be either ModuleStoreEnum.BranchName.draft or ModuleStoreEnum.BranchName.published. Returns: course_usage_key (CourseLocator): course usage locator """ if not course_key: raise ValidationError(COURSE_KEY_ERROR_MESSAGES['empty_course_key']) course_usage_key = CourseKey.from_string(course_key) if not modulestore().has_course(course_usage_key): raise ItemNotFoundError(COURSE_KEY_ERROR_MESSAGES['course_key_not_found']) # get branch specific locator course_usage_key = course_usage_key.for_branch(branch) return course_usage_key
def clean(self): errors = defaultdict(list) local_domain = settings.MAILBOXES_LOCAL_DOMAIN if local_domain: forwards = self.forward.split() for ix, forward in enumerate(forwards): if forward.endswith('@%s' % local_domain): name = forward.split('@')[0] if Mailbox.objects.filter(name=name).exists(): forwards[ix] = name self.forward = ' '.join(forwards) if self.account_id: for mailbox in self.get_forward_mailboxes(): if mailbox.account_id == self.account_id: errors['forward'].append( _("Please use mailboxes field for '%s' mailbox.") % mailbox) if self.domain: for forward in self.forward.split(): if self.email == forward: errors['forward'].append( _("'%s' forwards to itself.") % forward) if errors: raise ValidationError(errors)
def clean(self): regex = re.compile(r'^[a-zA-Z\']+$', re.U) if not regex.match(self.first_name): raise ValidationError({"first_name": 'Invalid name'}) if not regex.match(self.last_name): raise ValidationError({"last_name": 'Invalid name'}) if self.date_of_birth: if self.date_of_birth > datetime.now().date(): raise ValidationError({ 'date_of_birth': _("Date of birth cannot be greater than today's date.") }) if self.relationship == "O" and (self.relationship_description is None or self.relationship_description == ""): raise ValidationError({ 'relationship_description': _("Explain the relationship with dependant."), }) if not self.pk: # Validate dependant count if self.member.policy is None: raise ValidationError( _("%(member)s has not been registered for a policy yet."), params={ 'member': self.member.full_name, }) else: policy = self.member.policy if self.member.dependant_count + 1 > policy.dependants_per_holder: raise ValidationError(_( "You can only have %(dependants)s dependants under the %(policy)s policy." ), params={ 'dependants': policy.dependants_per_holder, 'policy': policy.name.title(), }) super(Dependant, self).clean()
def clean(self): if self.task_owner_key == self.provider_eth_account: raise ValidationError({ 'provider_eth_account': 'Provider ethereum account address must be diffrent than task owner key' }) if not isinstance(self.amount_pending, int) or self.amount_pending <= 0: raise ValidationError({ 'amount_pending': 'Amount pending must be an integer and bigger than 0' }) if not isinstance(self.amount_paid, int) or self.amount_paid < 0: raise ValidationError({ 'amount_paid': 'Amount paid must be an integer and bigger than or equal 0' }) if not isinstance(self.task_owner_key, bytes) or not len( self.task_owner_key) == TASK_OWNER_KEY_LENGTH: raise ValidationError({ 'task_owner_key': f'Task owner key must be a bytes string with {TASK_OWNER_KEY_LENGTH} characters' }) if not isinstance(self.provider_eth_account, str) or not len( self.provider_eth_account) == ETHEREUM_ADDRESS_LENGTH: raise ValidationError({ 'provider_eth_account': f'Provider ethereum account address must be a string with {ETHEREUM_ADDRESS_LENGTH} characters' }) if not isinstance(self.pending_response, PendingResponse): raise ValidationError({ 'pending_response': 'PaymentInfo should be related with Pending Response' })
def clean(self): """ checks input in relation to item_type 1. header items cannot be shortlinks or startitems, since they are no links 2. lesson_item: relation to lesson is required 3. lessonstep_item: relation to lesson_step is required 4. forum_item: relationship to forum is required """ # 1. header item: not start_item, no relationships allowed if self.item_type == self.MENU_ITEM_TYPE.header_item: if self.is_start_item: raise ValidationError( 'Überschrift kann nicht Startpunkt sein!') if self.is_shortlink: raise ValidationError( 'Überschrift kann nicht ins Kurzmenü eingehägt werden!') # 2. lesson item: only relationship to lesson is required if self.item_type == self.MENU_ITEM_TYPE.lesson_item: if self.classlesson: if not self.classlesson.is_lesson(): raise ValidationError( '''Lektions-Eintrag muss zu einer Lektion verlinken.''', code='invalid_object') if self.forum: raise ValidationError('''Bei diesem Eintragstyp kann kein Forum angegeben werden.''') # 4. forum_item: only relationships forum, is required if self.item_type == self.MENU_ITEM_TYPE.forum_item: if not self.forum: raise ValidationError( '''Forum-Eintrag muss zu einem Forum verlinken. Bitte ein Forum auswählen.''') if self.classlesson: raise ValidationError('''Bei Eintragstyp kann keine Lektion angegeben werden.''')
def clean_name(self): value = self.cleaned_data['name'] if '傻逼' in value: raise ValidationError('含有敏感词"傻逼"') else: return value
def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手机号码格式错误') #自定义验证规则的时候,如果不符合你的规则,需要自己发起错误
def do_create_account(form, custom_form=None): """ Given cleaned post variables, create the User and UserProfile objects, as well as the registration for this user. Returns a tuple (User, UserProfile, Registration). Note: this function is also used for creating test users. """ # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation if not configuration_helpers.get_value( 'ALLOW_PUBLIC_ACCOUNT_CREATION', settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True) ): raise PermissionDenied() errors = {} errors.update(form.errors) if custom_form: errors.update(custom_form.errors) if errors: raise ValidationError(errors) proposed_username = form.cleaned_data["username"] user = User( username=proposed_username, email=form.cleaned_data["email"], is_active=False ) password = normalize_password(form.cleaned_data["password"]) user.set_password(password) registration = Registration() # TODO: Rearrange so that if part of the process fails, the whole process fails. # Right now, we can have e.g. no registration e-mail sent out and a zombie account try: with transaction.atomic(): user.save() if custom_form: custom_model = custom_form.save(commit=False) custom_model.user = user custom_model.save() except IntegrityError: # Figure out the cause of the integrity error # TODO duplicate email is already handled by form.errors above as a ValidationError. # The checks for duplicate email/username should occur in the same place with an # AccountValidationError and a consistent user message returned (i.e. both should # return "It looks like {username} belongs to an existing account. Try again with a # different username.") if username_exists_or_retired(user.username): raise AccountValidationError( USERNAME_EXISTS_MSG_FMT.format(username=proposed_username), field="username" ) elif email_exists_or_retired(user.email): raise AccountValidationError( _("An account with the Email '{email}' already exists.").format(email=user.email), field="email" ) else: raise registration.register(user) profile_fields = [ "name", "level_of_education", "gender", "mailing_address", "city", "country", "goals", "year_of_birth" ] profile = UserProfile( user=user, **{key: form.cleaned_data.get(key) for key in profile_fields} ) extended_profile = form.cleaned_extended_profile if extended_profile: profile.meta = json.dumps(extended_profile) try: profile.save() except Exception: log.exception("UserProfile creation failed for user {id}.".format(id=user.id)) raise return user, profile, registration
def protected_domains_validator(value): if is_protected(value): raise ValidationError( 'Protected domain/subdomain', params={'value': value}, )
def rename(self, new_name): if os.path.splitext( self.file_name)[1] != os.path.splitext(new_name)[1]: raise ValidationError( _("Cannot change file type when renaming resource")) self.file_name = new_name
def api_submit(request): "Automated submission entrypoint" submission = None def err(code, text): return HttpResponse(text, status=code, content_type='text/plain') if request.method == 'GET': return render(request, 'submit/api_submit_info.html') elif request.method == 'POST': e = None try: form = SubmissionAutoUploadForm(request, data=request.POST, files=request.FILES) if form.is_valid(): username = form.cleaned_data['user'] user = User.objects.filter(username=username) if user.count() == 0: return err(404, "No such user: %s" % username) if user.count() > 1: return err(500, "Multiple matching accounts for %s" % username) user = user.first() if not hasattr(user, 'person'): return err(404, "No person with username %s" % username) authors, abstract, file_name, file_size = get_draft_meta(form) submission = get_submission(form) fill_in_submission(form, submission, authors, abstract, file_size) apply_checkers(submission, file_name) create_submission_event(request, submission, desc="Uploaded submission") errors = validate_submission(submission) if errors: raise ValidationError(errors) errors = [ c.message for c in submission.checks.all() if c.passed==False ] if errors: raise ValidationError(errors) if not user.username in [ a['email'] for a in authors ]: raise ValidationError('Submitter %s is not one of the document authors' % user.username) submission.submitter = user.person.formatted_email() docevent_from_submission(request, submission, desc="Uploaded new revision") requires_group_approval = (submission.rev == '00' and submission.group and submission.group.type_id in ("wg", "rg", "ietf", "irtf", "iab", "iana", "rfcedtyp") and not Preapproval.objects.filter(name=submission.name).exists()) requires_prev_authors_approval = Document.objects.filter(name=submission.name) sent_to, desc, docDesc = send_confirmation_emails(request, submission, requires_group_approval, requires_prev_authors_approval) msg = u"Set submitter to \"%s\" and %s" % (submission.submitter, desc) create_submission_event(request, submission, msg) docevent_from_submission(request, submission, docDesc, who="(System)") return HttpResponse( "Upload of %s OK, confirmation requests sent to:\n %s" % (submission.name, ',\n '.join(sent_to)), content_type="text/plain") else: raise ValidationError(form.errors) except IOError as e: return err(500, "IO Error: %s" % str(e)) except ValidationError as e: return err(400, "Validation Error: %s" % str(e)) except Exception as e: raise return err(500, "Exception: %s" % str(e)) finally: if e and submission: remove_submission_files(submission) submission.delete() else: return err(405, "Method not allowed")
def clean(self): super().clean() # An MPTT model cannot be its own parent if self.pk and self.parent_id == self.pk: raise ValidationError({"parent": "Cannot assign self as parent."})
def clean(self, *args, **kwargs): ori = self.origen des = self.destino if ori == des: raise ValidationError("Origen y destino no pueden ser iguales") return
def clean(self): if self.field.type != CF_TYPE_SELECT: raise ValidationError( "Custom field choices can only be assigned to selection fields." )
def validar_entrada_nombre(value): if not len(value) > 10: raise ValidationError('Minimo 10 caracteres')
def raise_required(): raise ValidationError(Field.default_error_messages['required'])
def validar_entrada_entero(value): if not len(str(value)) == 4: raise ValidationError('Minimo una cifra de 4 digitos')
def clean(self): if not self.prospect_campaign_relation.attempted: raise ValidationError( 'Prospect must be attempted to save attempt result')
def number_only(value): if (re.match(r'^[0~9]*$', value) == None): raise ValidationError( '%(value)s is not Number!', params={'value': value}, )
def clean_description(self): desc = self.cleaned_data.get('description') if len(desc) < 10: raise ValidationError("Description too short") return desc
def __call__(self, value): if not isinstance(value, int): from django.core.validators import ValidationError value_type = type(value) raise ValidationError("Requires a type of <class 'int'> not {}".format(value_type), code=self.code) super(IntegerValidator, self).__call__(value)
def check_hook(instance, **kwargs): if 'loaddata' in sys.argv or kwargs.get('raw', False): # noce return errors = instance.handlers.validate(instance) if errors: raise ValidationError(errors)
def clean(self, *args, **kwargs): if self.duration < 0: raise ValidationError("Duration Cannot be Negative") super(AudiobookModel, self).clean(*args, **kwargs)
def create_account_with_params(request, params): """ Given a request and a dict of parameters (which may or may not have come from the request), create an account for the requesting user, including creating a comments service user object and sending an activation email. This also takes external/third-party auth into account, updates that as necessary, and authenticates the user for the request's session. Does not return anything. Raises AccountValidationError if an account with the username or email specified by params already exists, or ValidationError if any of the given parameters is invalid for any other reason. Issues with this code: * It is non-transactional except where explicitly wrapped in atomic to alleviate deadlocks and improve performance. This means failures at different places in registration can leave users in inconsistent states. * Third-party auth passwords are not verified. There is a comment that they are unused, but it would be helpful to have a sanity check that they are sane. * The user-facing text is rather unfriendly (e.g. "Username must be a minimum of two characters long" rather than "Please use a username of at least two characters"). * Duplicate email raises a ValidationError (rather than the expected AccountValidationError). Duplicate username returns an inconsistent user message (i.e. "An account with the Public Username '{username}' already exists." rather than "It looks like {username} belongs to an existing account. Try again with a different username.") The two checks occur at different places in the code; as a result, registering with both a duplicate username and email raises only a ValidationError for email only. """ # Copy params so we can modify it; we can't just do dict(params) because if # params is request.POST, that results in a dict containing lists of values params = dict(params.items()) # allow to define custom set of required/optional/hidden fields via configuration extra_fields = configuration_helpers.get_value( 'REGISTRATION_EXTRA_FIELDS', getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {}) ) # registration via third party (Google, Facebook) using mobile application # doesn't use social auth pipeline (no redirect uri(s) etc involved). # In this case all related info (required for account linking) # is sent in params. # `third_party_auth_credentials_in_api` essentially means 'request # is made from mobile application' third_party_auth_credentials_in_api = 'provider' in params is_third_party_auth_enabled = third_party_auth.is_enabled() if is_third_party_auth_enabled and (pipeline.running(request) or third_party_auth_credentials_in_api): params["password"] = generate_password() # in case user is registering via third party (Google, Facebook) and pipeline has expired, show appropriate # error message if is_third_party_auth_enabled and ('social_auth_provider' in params and not pipeline.running(request)): raise ValidationError( {'session_expired': [ _(u"Registration using {provider} has timed out.").format( provider=params.get('social_auth_provider')) ]} ) do_external_auth, eamap = pre_account_creation_external_auth(request, params) extended_profile_fields = configuration_helpers.get_value('extended_profile_fields', []) # Can't have terms of service for certain SHIB users, like at Stanford registration_fields = getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {}) tos_required = ( registration_fields.get('terms_of_service') != 'hidden' or registration_fields.get('honor_code') != 'hidden' ) and ( not settings.FEATURES.get("AUTH_USE_SHIB") or not settings.FEATURES.get("SHIB_DISABLE_TOS") or not do_external_auth or not eamap.external_domain.startswith(settings.SHIBBOLETH_DOMAIN_PREFIX) ) form = AccountCreationForm( data=params, extra_fields=extra_fields, extended_profile_fields=extended_profile_fields, do_third_party_auth=do_external_auth, tos_required=tos_required, ) custom_form = get_registration_extension_form(data=params) # Perform operations within a transaction that are critical to account creation with outer_atomic(read_committed=True): # first, create the account (user, profile, registration) = do_create_account(form, custom_form) third_party_provider, running_pipeline = _link_user_to_third_party_provider( is_third_party_auth_enabled, third_party_auth_credentials_in_api, user, request, params, ) new_user = authenticate_new_user(request, user.username, params['password']) django_login(request, new_user) request.session.set_expiry(0) post_account_creation_external_auth(do_external_auth, eamap, new_user) # Check if system is configured to skip activation email for the current user. skip_email = _skip_activation_email( user, do_external_auth, running_pipeline, third_party_provider, ) if skip_email: registration.activate() else: compose_and_send_activation_email(user, profile, registration) # Perform operations that are non-critical parts of account creation create_or_set_user_attribute_created_on_site(user, request.site) preferences_api.set_user_preference(user, LANGUAGE_KEY, get_language()) if settings.FEATURES.get('ENABLE_DISCUSSION_EMAIL_DIGEST'): try: enable_notifications(user) except Exception: # pylint: disable=broad-except log.exception(u"Enable discussion notifications failed for user {id}.".format(id=user.id)) _track_user_registration(user, profile, params, third_party_provider) # Announce registration REGISTER_USER.send(sender=None, user=user, registration=registration) create_comments_service_user(user) try: _record_registration_attributions(request, new_user) # Don't prevent a user from registering due to attribution errors. except Exception: # pylint: disable=broad-except log.exception('Error while attributing cookies to user registration.') # TODO: there is no error checking here to see that the user actually logged in successfully, # and is not yet an active user. if new_user is not None: AUDIT_LOG.info(u"Login success on new account creation - {0}".format(new_user.username)) return new_user
def validate_BDP_url(value): logger.debug("checking bdpurl %s" % value) if not len(str(value)): raise ValidationError("BDP url is empty") return str(value)