def validate(self, attrs): token = attrs['token'] payload = self._check_payload(token=token) user = self._check_user(payload=payload) # Get and check 'orig_iat' orig_iat = payload.get('orig_iat') if orig_iat: # Verify expiration refresh_limit = api_settings.JWT_REFRESH_EXPIRATION_DELTA if isinstance(refresh_limit, timedelta): refresh_limit = (refresh_limit.days * 24 * 3600 + refresh_limit.seconds) expiration_timestamp = orig_iat + int(refresh_limit) now_timestamp = timegm(datetime.utcnow().utctimetuple()) if now_timestamp > expiration_timestamp: msg = _('Refresh has expired.') raise serializers.ValidationError(msg) else: msg = _('orig_iat field is required.') raise serializers.ValidationError(msg) new_payload = jwt_payload_handler(user) new_payload['orig_iat'] = orig_iat return {'token': jwt_encode_handler(new_payload), 'user': user}
def validate(self, attrs): credentials = { self.username_field: attrs.get(self.username_field), 'password': attrs.get('password') } if all(credentials.values()): user = authenticate(**credentials) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) payload = jwt_payload_handler(user) return { 'token': jwt_encode_handler(payload), 'user': user, 'profile': '111' } else: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "{username_field}" and "password".') msg = msg.format(username_field=self.username_field) raise serializers.ValidationError(msg)
def _check_payload(self, token): # Check payload valid (based off of JSONWebTokenAuthentication, # may want to refactor) try: payload = jwt_decode_handler(token) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise serializers.ValidationError(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise serializers.ValidationError(msg) return payload
def validate(self, attrs): self.set_password_form = self.set_password_form_class(user=self.user, data=attrs) if not self.set_password_form.is_valid(): raise serializers.ValidationError(self.set_password_form.errors) return attrs
def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email
def validate_email(self, value): # Create PasswordResetForm with the serializer self.reset_form = self.password_reset_form_class( data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(self.reset_form.errors) return value
def validate_old_password(self, value): invalid_password_conditions = (self.old_password_field_enabled, self.user, not self.user.check_password(value)) if all(invalid_password_conditions): raise serializers.ValidationError('Invalid password') return value
def _check_user(self, payload): username = jwt_get_username_from_payload(payload) if not username: msg = _('Invalid payload.') raise serializers.ValidationError(msg) # Make sure user exists try: user = User.objects.get_by_natural_key(username) except User.DoesNotExist: msg = _("User doesn't exist.") raise serializers.ValidationError(msg) if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) return user
def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: user = self._validate_email(email, password) # Authentication through username elif app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: user = self._validate_username(username, password) # Authentication through either username or email else: user = self._validate_username_email(username, email, password) else: # Authentication without using allauth if email: try: username = UserModel.objects.get( email__iexact=email).get_username() except UserModel.DoesNotExist: pass if username: user = self._validate_username_email(username, '', password) # Did we get back an active user? if user: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise exceptions.ValidationError(msg) # If required, is the email verified? if 'mind_auth.registration' in settings.INSTALLED_APPS: from allauth.account import app_settings if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY: email_address = user.emailaddress_set.get(email=user.email) if not email_address.verified: raise serializers.ValidationError( _('E-mail is not verified.')) attrs['user'] = user return attrs
def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(request=self.context.get('request'), username=username, password=password) # The authenticate call simply returns None for is_active=False # users. (Assuming the default ModelBackend authentication # backend.) if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs
def validate(self, attrs): view = self.context.get('view') request = self._get_request() if not view: raise serializers.ValidationError( "View is not defined, pass it as a context variable" ) adapter_class = getattr(view, 'adapter_class', None) if not adapter_class: raise serializers.ValidationError("Define adapter_class in view") adapter = adapter_class(request) app = adapter.get_provider().get_app(request) access_token = attrs.get('access_token') token_secret = attrs.get('token_secret') request.session['oauth_api.twitter.com_access_token'] = { 'oauth_token': access_token, 'oauth_token_secret': token_secret, } token = SocialToken(token=access_token, token_secret=token_secret) token.app = app try: login = self.get_social_login(adapter, app, token, access_token) complete_social_login(request, login) except OAuthError as e: raise serializers.ValidationError(str(e)) if not login.is_existing: login.lookup() login.save(request, connect=True) attrs['user'] = login.account.user return attrs
def test_nested_validation_error_detail(self): """ Ensure nested validation error detail is rendered correctly. """ e = serializers.ValidationError({ 'nested': { 'field': ['error'], } }) assert serializers.as_serializer_error(e) == { 'nested': { 'field': ['error'], } }
def validate(self, attrs): self._errors = {} # Decode the uidb64 to uid to get User object try: uid = force_text(uid_decoder(attrs['uid'])) self.user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): raise ValidationError({'uid': ['Invalid value']}) self.custom_validation(attrs) # Construct SetPasswordForm instance self.set_password_form = self.set_password_form_class(user=self.user, data=attrs) if not self.set_password_form.is_valid(): raise serializers.ValidationError(self.set_password_form.errors) if not default_token_generator.check_token(self.user, attrs['token']): raise ValidationError({'token': ['Invalid value']}) return attrs
def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError(_("The two password fields didn't match.")) return data
def validate(self, attrs): raise serializers.ValidationError('Non field error')
def validate(self, attrs): raise serializers.ValidationError({'char': 'Field error'})
def validate(self, attrs): raise serializers.ValidationError("serializer invalid")
def validate_renamed(self, value): if len(value) < 3: raise serializers.ValidationError('Minimum 3 characters.') return value
def validate(self, attrs): view = self.context.get('view') request = self._get_request() if not view: raise serializers.ValidationError( _("View is not defined, pass it as a context variable") ) adapter_class = getattr(view, 'adapter_class', None) if not adapter_class: raise serializers.ValidationError(_("Define adapter_class in view")) adapter = adapter_class(request) app = adapter.get_provider().get_app(request) # More info on code vs access_token # http://stackoverflow.com/questions/8666316/facebook-oauth-2-0-code-and-token # Case 1: We received the access_token if attrs.get('access_token'): access_token = attrs.get('access_token') # Case 2: We received the authorization code elif attrs.get('code'): self.callback_url = getattr(view, 'callback_url', None) self.client_class = getattr(view, 'client_class', None) if not self.callback_url: raise serializers.ValidationError( _("Define callback_url in view") ) if not self.client_class: raise serializers.ValidationError( _("Define client_class in view") ) code = attrs.get('code') provider = adapter.get_provider() scope = provider.get_scope(request) client = self.client_class( request, app.client_id, app.secret, adapter.access_token_method, adapter.access_token_url, self.callback_url, scope ) token = client.get_access_token(code) access_token = token['access_token'] else: raise serializers.ValidationError( _("Incorrect input. access_token or code is required.")) social_token = adapter.parse_token({'access_token': access_token}) social_token.app = app try: login = self.get_social_login(adapter, app, social_token, access_token) complete_social_login(request, login) except HTTPError: raise serializers.ValidationError(_("Incorrect value")) if not login.is_existing: # We have an account already signed up in a different flow # with the same email address: raise an exception. # This needs to be handled in the frontend. We can not just # link up the accounts due to security constraints if allauth_settings.UNIQUE_EMAIL: # Do we have an account already with this email address? account_exists = get_user_model().objects.filter( email=login.user.email, ).exists() if account_exists: raise serializers.ValidationError( _("User is already registered with this e-mail address.") ) login.lookup() login.save(request, connect=True) attrs['user'] = login.account.user return attrs
def validate_foo(self, attrs, source): raise serializers.ValidationError("foo invalid")