class PasswordSerializer(serializers.Serializer): current_password = PasswordField(required=False) password = PasswordField() password_confirmation = PasswordField(required=False) def validate_current_password(self, value): current_user = self.context.get('current_user') if current_user and not current_user.check_password(value): raise serializers.ValidationError('Invalid password') return value def validate_password_confirmation(self, value): current_user = self.context.get('current_user') if current_user and value != self.initial_data['password']: raise serializers.ValidationError('Passwords should be equals') return value def create(self, validated_data): return make_password(validated_data['password'], salt=None) def update(self, instance, validated_data): instance['password'] = make_password(validated_data['password'])
def __init__(self, *args, **kwargs): """Dynamically add the USERNAME_FIELD to self.fields.""" super(JSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() self.fields['password'] = PasswordField(write_only=True)
class CustomJSONWebTokenSerializer(Serializer): username = serializers.CharField(max_length=25) password = PasswordField(write_only=True) def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') credentials = {'username': username, 'password': password} if all(credentials.values()): user = authenticate(**credentials) if user: payload = jwt_payload_handler(user) return {'token': jwt_encode_handler(payload), 'user': user} else: msg = _('User doesnt exists') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg)
def __init__(self, *args, **kwargs): """ Dynamically add the USERNAME_FIELD to self.fields. """ super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField( required=False) self.fields['password'] = PasswordField(write_only=True, required=False)
def __init__(self): """初始化""" super().__init__() self.fields[self.LOGIN_KEY] = serializers.CharField(max_length=30, validators=[]) self.fields['code'] = serializers.CharField(max_length=6, required=False) # 验证码 self.fields['password'] = PasswordField(write_only=True, required=False) self.fields['way'] = serializers.ChoiceField(choices=self.LOGIN_WAY)
def __init__(self, *args, **kwargs): """ Dynamically add the USERNAME_FIELD to self.fields. """ super(JSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields[ self.username_field] = serializers.CharField() # username field self.fields['password'] = PasswordField( write_only=True ) # password field 使用默认的ObtainJSONWebToken 作为获取token的view的时要提交 usernamefield 和 password 两个字段
class JSONWebTokenSerializer(Serializer): """ Serializer class used to validate a company name, email and password. Returns a JSON Web Token that can be used to authenticate later calls. """ email = serializers.EmailField() password = PasswordField(write_only=True) def validate(self, attrs): credentials = { 'email': attrs.get('email'), 'password': attrs.get('password') } if all(credentials.values()): # it's required to get User object from email try: user = CustomUser.objects.get(email=credentials['email']) except CustomUser.DoesNotExist: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) user = authenticate(username=user.email, password=credentials['password']) if user: user_logged_in.send(sender=user.__class__, request=self.context['request'], user=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': { 'email': credentials['email'] } } else: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "email" and "password".') raise serializers.ValidationError(msg)
def __init__(self, *args, **kwargs): """ Dynamically add the USERNAME_FIELD to self.fields. """ super().__init__(*args, **kwargs) # 先初始化 # 动态根据model字段名向OrderDict中添加键 # 唯一验证 # 自定义验证 self.fields[self.LOGIN_KEY] = serializers.CharField(max_length=30) self.fields['password'] = PasswordField(write_only=True, required=False) self.fields['next'] = serializers.CharField() # 前一页url self.fields['code'] = serializers.CharField(max_length=6, required=False) # 验证码 self.fields['is_remember'] = serializers.BooleanField() # 是否记住用户名 self.fields['way'] = serializers.ChoiceField(choices=self.LOGIN_WAY)
class RequestMFS(GenericAPIView): permission_classes = [IsMFSInactive] serializer_class = type('', (Serializer,), {'password': PasswordField( required=True, max_length=50, allow_blank=False, allow_null=False)}) def post(self, request, **kwargs): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if not request.user.check_password(serializer.validated_data['password']): return Response({ 'status': 'Invalid operation', 'message': "Invalid password" }, status=400) member = request.user.member # TODO: Add code to register MFS account return Response({'status': 'success', 'message': 'Successfully created MFS account'}, status=200)
class CustomJWTSerializer(JSONWebTokenSerializer): username_field = 'username_or_email' username_or_email = serializers.CharField(required=False) password = PasswordField(write_only=True, required=False) def validate(self, attrs): password = attrs.get("password") user_obj = User.objects.filter( Q(username=attrs.get('username_or_email')) | Q(email=attrs.get('username_or_email'))).first() msg = None if user_obj is not None: credentials = { 'username': user_obj.username, 'password': password } if all(credentials.values()): user = authenticate(**credentials) if user: if not user.is_active: msg = _('User account is disabled.') payload = jwt_payload_handler(user) return { 'token': jwt_encode_handler(payload), 'user': user } else: msg = _('Unable to log in with provided credentialss.') else: msg = _('Must include "{username_field}" and "password".') msg = msg.format(username_field=self.username_field) else: msg = _('Account with this email/username does not exists') if msg: raise CustomJWTException(msg) return attrs
class DataliveJSONWebTokenSerializer(serializers.Serializer): """ Serializer class used to validate a username/email and password of a user. Returns a JSON Web Token that can be used to authenticate later calls. """ username = serializers.CharField(required=False) email = serializers.CharField(required=False) password = PasswordField(required=True) @property def object(self): return self.validated_data def validate(self, attrs): # Raise error if both username and email are missing if not attrs.get('username') and not attrs.get('email'): msg = _('Must include either "username" or "email".') raise serializers.ValidationError(msg) credentials = { 'username': attrs.get('username'), 'email': attrs.get('email'), 'password': attrs.get('password') } # Authenticate the user and return the token if successful 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} else: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg)
class UserSerializer(serializers.ModelSerializer): password = PasswordField(write_only=True) class Meta: model = User fields = ('id', 'name', 'username', 'picture', 'birth_date', 'email', 'password') extra_kwargs = { 'id': { 'read_only': True }, 'name': { 'required': True }, 'username': { 'required': True }, 'email': { 'required': True }, 'birth_date': { 'required': True }, } def create(self, validated_data): return User.objects.create_user(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.picture = validated_data.get('picture', instance.picture) instance.is_active = validated_data.get('is_active', instance.is_active) instance.birth_date = validated_data.get('birth_date', instance.birth_date) instance.save() return instance
def __init__(self, *args, **kwargs): super(TokenSerializer, self).__init__(*args, **kwargs) self.fields['email'] = serializers.CharField(label=_("Email")) self.fields['password'] = PasswordField(label=_('password'), write_only=True)
def __init__(self, *args, **kwargs): super(JSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields[get_username_field()] = get_field_by_name( UserModel._meta, get_username_field()) self.fields['password'] = PasswordField(write_only=True)
class JSONWebTokenSerializer(Serializer): """ Serializer class used to validate API key, API secret, username and password. 'username' is identified by the custom UserModel.USERNAME_FIELD. Returns a JSON Web Token that can be used to authenticate later calls. """ api_key = serializers.CharField(write_only=True) api_secret = serializers.CharField(write_only=True) password = PasswordField(write_only=True, required=False) def __init__(self, *args, **kwargs): """ Dynamically add the USERNAME_FIELD to self.fields. """ super(JSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField( required=False) @property def username_field(self): return get_username_field() def validate(self, attrs): api_key = attrs['api_key'] api_secret = attrs['api_secret'] try: api_access = APIAccess.objects.get(key=api_key, secret=api_secret) except APIAccess.DoesNotExist: raise serializers.ValidationError(_("Invalid API key or secret.")) username = attrs.get(self.username_field) user = AnonymousUser() if username: credentials = { self.username_field: username, 'password': attrs.get('password') } if all(credentials.values()): user = authenticate(**credentials) if user: if not user.is_active: raise serializers.ValidationError( _('User account is disabled.')) else: raise serializers.ValidationError( _('Unable to log in with provided credentials.')) else: msg = _('Must include "{username_field}" and "password".') msg = msg.format(username_field=self.username_field) raise serializers.ValidationError(msg) payload = jwt_payload_handler(user, api_access=api_access, shop=self.context["request"].shop) return {'token': jwt_encode_handler(payload), 'user': user}
def __init__(self, *args, **kwargs): super(JSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields['email'] = serializers.EmailField() self.fields['password'] = PasswordField(write_only=True)
def __init__(self, *args, **kwargs): """Se agrega dinámicamente USERNAME_FIELD a self.fields.""" super(JSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields[self.username_field] = CharField() self.fields['password'] = PasswordField(write_only=True)
def __init__(self, *args, **kwargs): super(Serializer, self).__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() self.fields['password'] = PasswordField(write_only=True)
def __init__(self, *args, **kwargs): super(CustomJSONWebTokenSerializer, self).__init__(*args, **kwargs) self.fields['username'] = serializers.CharField() self.fields['password'] = PasswordField(write_only=True)
def __init__(self, *args, **kwargs): super(CustomJWTSerializer, self).__init__(*args, **kwargs) self.fields['password'] = PasswordField(write_only=True, required=False) self.fields['reset'] = serializers.BooleanField(required=False, write_only=True)