Esempio n. 1
0
def validacao_senha_redefinicao(request):
    senha = loads(request.body)['valor']
    resposta = {}

    tamanho_minimo = MinimumLengthValidator(8)
    numerica = NumericPasswordValidator()
    comum = CommonPasswordValidator()
    similar = UserAttributeSimilarityValidator(('nome', 'sobrenome', 'email'),
                                               max_similarity=0.7)

    # Checando se a senha tem no mínimo 8 caracteres
    try:
        tamanho_minimo.validate(senha)
    except ValidationError:
        tamanho_minimo = False

    # Checando se a senha é totalmente numérica
    try:
        numerica.validate(senha)
    except ValidationError:
        numerica = False

    # Checando se a senha é comum
    try:
        comum.validate(senha)
    except ValidationError:
        comum = False

    # Checando se a senha é similar a outras informações do usuário

    try:
        similar.validate(senha, request.user)
    except ValidationError as e:
        similar = False

    if not tamanho_minimo:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha deve conter pelo menos 8 caracteres'
    elif not numerica:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha não pode ser inteiramente numérica'
    elif not comum:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Essa senha é muito comum. Tente outra'
    elif not similar:
        status = 400
        resposta['status'] = 'inválido'
        resposta[
            'erro'] = 'Essa senha é muito parecida com seu e-mail ou com seu nome'
    else:
        status = 200
        resposta['status'] = 'válido'

    return JsonResponse(resposta, status=status)
Esempio n. 2
0
def auth_redir(request):
    try:
        User_name = request.POST['name']
        User_email = request.POST['email']
        User_password = request.POST['password']

        minlengthpass = MinimumLengthValidator()
        commonpass = CommonPasswordValidator()

        try:
            minlengthpass.validate(User_password)
        except:
            minlength_error = "Пароль слишком короткий, он должен содержать минимум 8 символов"
            return render(request, 'cooking/auth.html',
                          {'minlength_error': minlength_error})

        try:
            commonpass.validate(User_password)
        except:
            common_error = "Пароль слишком простой"
            return render(request, 'cooking/auth.html',
                          {'common_error': common_error})

        hasher = PBKDF2PasswordHasher()
        salt = get_random_string(
            12,
            "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890")
        User_password = hasher.encode(password=User_password,
                                      salt=salt,
                                      iterations=180000)
        if UserInfo.objects.filter(user_name=User_name).exists():
            user_error = "Пользователь с таким именем уже существует"
            return render(request, 'cooking/auth.html',
                          {'user_error': user_error})
        else:
            secret = get_random_string(
                50,
                'qwertyuiopasdfghjlkzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&*()_-'
            )
            Userinfo = UserInfo(user_name=User_name,
                                user_img=" ",
                                user_email=User_email,
                                user_password=User_password,
                                user_soup_list=" ",
                                user_secret=secret)
            Userinfo.save()
            response = HttpResponseRedirect('/cooking/')
            if request.COOKIES.get('livetime'):
                time = int(request.COOKIES.get('livetime'))
                response.set_cookie('wasauthorised', secret, time)
            else:
                response.set_cookie('wasauthorised', secret, 1209600)
            return response
    except:
        return HttpResponseRedirect('/cooking/register/')
Esempio n. 3
0
    def test_validate(self):
        expected_error = "This password is too short. It must contain at least %d characters."
        self.assertIsNone(MinimumLengthValidator().validate('12345678'))
        self.assertIsNone(MinimumLengthValidator(min_length=3).validate('123'))

        with self.assertRaises(ValidationError) as cm:
            MinimumLengthValidator().validate('1234567')
        self.assertEqual(cm.exception.messages, [expected_error % 8])
        self.assertEqual(cm.exception.error_list[0].code, 'password_too_short')

        with self.assertRaises(ValidationError) as cm:
            MinimumLengthValidator(min_length=3).validate('12')
        self.assertEqual(cm.exception.messages, [expected_error % 3])
Esempio n. 4
0
    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 and password2 and password1 != password2:
            raise ValidationError("Password don't match")

        user = User(
            username=self.cleaned_data.get("username"),
            email=self.cleaned_data.get("email"),
            password=self.cleaned_data.get("password2"),
        )
        password_validators = [
            MinimumLengthValidator(),
            UserAttributeSimilarityValidator(),
            CommonPasswordValidator(),
            NumericPasswordValidator(),
        ]

        try:
            validate_password(
                password=self.cleaned_data["password2"],
                user=user,
                password_validators=password_validators,
            )
        except ValidationError as e:
            logger.error("validation failed")
            raise ValidationError(e)
        return self.cleaned_data["password2"]
Esempio n. 5
0
def validate_password(pw):
    try:
        MinimumLengthValidator(8).validate(pw)
        NumericPasswordValidator().validate(pw)
        return True
    except ValidationError:
        return False
Esempio n. 6
0
 def clean_password(self):
     password = self.cleaned_data.get('password')
     password_validation.validate_password(
         password,
         password_validators=(MinimumLengthValidator(min_length=6),
                              NumericPasswordValidator(),
                              CommonPasswordValidator()))
     return password
Esempio n. 7
0
    def patch(self, request, token):
        username = request.data.get('username')
        email = request.data.get('email')
        token = Token.objects.get(key=token)
        user = AdvUser.objects.get(id=token.user_id)
        if username:
            if AdvUser.objects.exclude(username=user.username).filter(
                    username=username):
                response_data = {'username': '******'}
                return Response(response_data,
                                status=status.HTTP_400_BAD_REQUEST)
        if email:
            if AdvUser.objects.exclude(email=user.email).filter(email=email):
                response_data = {'email': 'this email is already in use'}
                return Response(response_data,
                                status=status.HTTP_400_BAD_REQUEST)
        shipping_address_id, billing_address_id = get_addresses(user)
        password = request.data.get('password')
        print(password, flush=True)
        token = Token.objects.get(key=token)
        true_password = AdvUser.objects.get(id=token.user_id).password
        check = check_password(password, true_password)
        print(f'check: {check}', flush=True)
        if not check:
            response_data = {'current_password': '******'}
            return Response(response_data, status=status.HTTP_401_UNAUTHORIZED)
        request.data.pop('password')
        if request.data.get('new_password'):
            new_password = request.data.get('new_password')
            try:
                validate_password(new_password,
                                  new_password,
                                  password_validators=[
                                      MinimumLengthValidator(min_length=8),
                                      NumericPasswordValidator
                                  ])
            except ValidationError:
                return Response({'change_password': '******'},
                                status=status.HTTP_401_UNAUTHORIZED)
            if new_password.isalpha():
                return Response({'change_password': '******'},
                                status=status.HTTP_401_UNAUTHORIZED)
        serializer = PatchSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
        user = AdvUser.objects.get(id=token.user_id)
        response_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'billing_address_id': billing_address_id,
            'shipping_adress_id': shipping_address_id
        }
        print('res:', response_data)

        return Response(response_data, status=status.HTTP_200_OK)
Esempio n. 8
0
class RegisterForm(forms.ModelForm):

    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
        'email_occupation': 'Данный адрес почты уже используется',
    }

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        for key in self.fields:
            self.fields[key].required = True

    password1 = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput,
        validators=[
            MinimumLengthValidator(min_length=8).validate,
            UserAttributeSimilarityValidator().validate,
            CommonPasswordValidator().validate,
            NumericPasswordValidator().validate
        ])

    password2 = forms.CharField(
        label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data.get("email")
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                self.error_messages['email_occupation'],
                code='email_occupation',
            )
        return email

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()

        return user
Esempio n. 9
0
    def validate(self, data):
        password = data.get('password')
        if password:
            validate_password(
                password,
                password_validators=[MinimumLengthValidator()]
            )

        return super().validate(data)
Esempio n. 10
0
def validacao_senha_registro(request):
    senha = loads(request.body)['valor']
    resposta = {}

    tamanho_minimo = MinimumLengthValidator(8)
    numerica = NumericPasswordValidator()
    comum = CommonPasswordValidator()

    # Checando se a senha tem no mínimo 8 caracteres
    try:
        tamanho_minimo.validate(senha)
    except ValidationError:
        tamanho_minimo = False

    # Checando se a senha é totalmente numérica
    try:
        numerica.validate(senha)
    except ValidationError:
        numerica = False

    # Checando se a senha é comum
    try:
        comum.validate(senha)
    except ValidationError:
        comum = False

    if not tamanho_minimo:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha deve conter pelo menos 8 caracteres'
    elif not numerica:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha não pode ser inteiramente numérica'
    elif not comum:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Essa senha é muito comum. Tente outra.'
    else:
        status = 200
        resposta['status'] = 'válido'

    return JsonResponse(resposta, status=status)
class ProfileEditForm(forms.ModelForm):
    """
    Форма для редактирования пользователя.
    """
    password = forms.CharField(widget=forms.PasswordInput(), \
         label=_('Новый пароль'), required=False, validators=[
                UserAttributeSimilarityValidator(), MinimumLengthValidator(),
                CommonPasswordValidator(), NumericPasswordValidator()
             ])

    password_confirm = forms.CharField(widget=forms.PasswordInput(), \
         label=_('Подтвердите новый пароль'), required=False)

    class Meta:
        model = get_user_model()
        fields = ['username', 'email']
        labels = {
            'username': _('Username'),
            'email': _('Email'),
        }
        help_texts = {
            'username': _('Латинские буквы, цифры и @ / . / + / - / _')
        }
        error_messages = {
            'username': {
                'unique': _('Пользователь с таким username уже существует')
            }
        }

    def clean(self):
        """
        Валидация всей формы, в целом.
        """
        cleaned_data = super(ProfileEditForm, self).clean()

        password = cleaned_data.get('password')
        password_confirm = cleaned_data.get('password_confirm')

        if password != password_confirm:
            raise forms.ValidationError(_('Пароли не совпадают'))

    def save(self, commit=True):
        """
        Сохранение отредактированной формы в БД.
        """
        hr_user = super(ProfileEditForm, self).save(commit=False)

        password = self.cleaned_data['password']
        if password is not None and password:
            hr_user.set_password(password)

        if commit:
            hr_user.save()

        return hr_user
Esempio n. 12
0
 def clean(self):
     word = self.cleaned_data['password']
     repass = self.cleaned_data['re_password']
     if MinimumLengthValidator().validate(password=word) is not None:
         raise ValidationError
     if NumericPasswordValidator().validate(password=word) is not None:
         raise ValidationError
     if word != repass:
         raise ValidationError('Passwords do not match')
     if User.objects.all().filter(username=self.cleaned_data['username']):
         raise ValidationError('This Username is already taken')
Esempio n. 13
0
    def clean_password(self):
        password = self.cleaned_data.get('password')
        print(password)

        if CommonPasswordValidator().validate(password):
            raise forms.ValidationError(
                "Password too common, Please chose some other password")
        elif MinimumLengthValidator().validate(password):
            raise forms.ValidationError(
                "Password must be of minimum 9 characters length")
        else:
            return password
Esempio n. 14
0
def check_password(password):
    """
    密码要求
    1 至少8位
    2 大小写+数字
    """
    try:
        MinimumLengthValidator().validate(password)
    except ValidationError:
        return False, '密码至少需要设置8位'
    if re.match(r'^(?=.*[A-Za-z])(?=.*[0-9])\w{8,}$', password):
        return True, ''
    else:
        return False, '密码应该为大小写字母与数字的组合'
Esempio n. 15
0
    def mutate_and_get_payload(cls,
                               root,
                               info,
                               email,
                               password,
                               date_of_birth,
                               first_name,
                               last_name,
                               display_name,
                               country,
                               recaptcha_token,
                               avatar=None):
        validate_recaptcha_v2(recaptcha_token)

        if avatar is not None and not re.search(r'^.*\.(jpg|jpeg|png)$',
                                                str(avatar), re.IGNORECASE):
            raise Exception(
                'Invalid image format #@user.avatar.alert.mime.error@')

        user = User(email=email,
                    date_of_birth=date_of_birth,
                    first_name=first_name,
                    last_name=last_name,
                    display_name=display_name,
                    country=country,
                    avatar=avatar)

        # image_moderation_score = moderate_image_s3(user.avatar)
        # if image_moderation_score >= ImageModerationScore.WARNING:
        #     s3 = boto3.resource('s3')
        #     s3.Object(
        #         os.environ['AWS_STORAGE_BUCKET_NAME'],
        #         user.avatar
        #     ).delete()
        #     raise Exception('Inappropriate image, select a different image')

        password_validators = [
            MinimumLengthValidator(),
            UpperCaseValidator(),
            NumericalValidator(),
        ]
        validate_password(password,
                          user,
                          password_validators=password_validators)
        user.set_password(password)

        user.save()

        return CreateUser(user=user)
Esempio n. 16
0
class SignUpSerializer(BaseSerializer):
    email = serializers.EmailField(max_length=254)
    password = serializers.CharField(
        max_length=128,
        validators=[
            UserAttributeSimilarityValidator(
                user_attributes=('username', 'email')).validate,
            MinimumLengthValidator().validate,
            CommonPasswordValidator().validate,
            NumericPasswordValidator().validate,
        ])

    @staticmethod
    def get_account_creation_data(validated_data: dict):
        creation_data = {
            'organization_slug': validated_data['organization_slug'],
            'username': validated_data.get('username') or 'master',
            'email': validated_data['email'],
            'password': validated_data['password'],
        }
        return creation_data
Esempio n. 17
0
 def test_help_text(self):
     self.assertEqual(
         MinimumLengthValidator().get_help_text(),
         "Your password must contain at least 8 characters."
     )
Esempio n. 18
0
    def post(self, request, ref_code=None):
        request_data_init = request.data
        try:
            username = request_data_init['username']
            email = request_data_init['email']
            password = request_data_init['password']
            request_ip = request_data_init['ip']
        except:
            request_data = request_data_init['_content']
            request_data = json.loads(request_data)
            print(f'request_data: {request_data}')
            username = request_data['username']
            email = request_data['email']
            password = request_data['password']
            request_ip = request_data['ip']
        try:
            validate_password(password,
                              password,
                              password_validators=[
                                  MinimumLengthValidator(min_length=8),
                                  NumericPasswordValidator
                              ])
        except ValidationError:
            return Response('Password is not valid',
                            status=status.HTTP_401_UNAUTHORIZED)
        if password.isalpha():
            return Response('Password is not valid',
                            status=status.HTTP_401_UNAUTHORIZED)

        #checking if credentials are occupied
        try:
            user = AdvUser.objects.create_user(username, email, password)
            user.save()
        except IntegrityError as e:
            err = repr(e)[80]
            if err == 'u':
                response_data = {'username': '******'}
            elif err == 'e':
                response_data = {'email': 'this email is already in use'}
            else:
                response_data = {'uncatched': 'something is wrong'}
            return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
        user.generate_keys()
        user.save()

        # referral block
        # ref_code = request.COOKIES.get('referral')
        if ref_code:
            try:
                ref_user = AdvUser.objects.get(own_ref_code=ref_code)
            except Exception as e:
                print(e, flush=True)
                response_data = {'error': 'insufficient referral code'}
                return Response(response_data,
                                status=status.HTTP_400_BAD_REQUEST)

            user.ref_user = ref_user
            user.save()
            print('REF CODE', user.ref_user.own_ref_code, flush=True)

        #geolocation block
        agent = request.META.get('HTTP_USER_AGENT')
        ip = get_client_ip(request)
        if ip[0:3] == '172':
            ip = request_ip
        geo = check_ip(ip)
        user.agent = agent
        user.geolocation = geo
        user.save()

        #creating token
        token, created = Token.objects.get_or_create(user=user)
        print(token)
        response_data = {'status': 'OK'}
        print('res:', response_data)

        return Response(response_data, status=status.HTTP_200_OK)
Esempio n. 19
0
    def post(self, request, *args, **kwargs):
        username = request.data.get("username", "")
        password = request.data.get("password", "")
        email = request.data.get("email", "")
        first_name = request.data.get("first_name", "")
        last_name = request.data.get("last_name", "")

        if not username and not password and not email:
            return Response(data={
                "message":
                "username, password and email is required to register a user"
            },
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            validate_email(email)
        except ValidationError as e:
            return Response(
                data={"message": "please provide proper email address"},
                status=status.HTTP_400_BAD_REQUEST)

        try:
            validate_password(
                password,
                password_validators=[MinimumLengthValidator(min_length=6)])
        except ValidationError as e:
            return Response(
                data={"message": "password length should be 6 or longer"},
                status=status.HTTP_400_BAD_REQUEST)

        try:
            hunter = PyHunter(EMAILHUNTER_API_KEY)
            email_verifier = hunter.email_verifier(email)
            if (not email_verifier
                    or email_verifier['result'] == 'undeliverable'):
                return Response(data={
                    "message":
                    "email address: {} is not deliverable".format(email)
                },
                                status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response(data={"message": e.args[0]},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            new_user = User.objects.create_user(username=username,
                                                password=password,
                                                email=email,
                                                first_name=first_name,
                                                last_name=last_name)
        except IntegrityError as e:
            if 'UNIQUE constraint' in e.args[0]:
                return Response(data={
                    "message":
                    "username {} already exists".format(username)
                },
                                status=status.HTTP_409_CONFLICT)

        try:
            clearbit.key = CLEARBIT_API_KEY
            profile_data_clearbit = clearbit.Enrichment.find(email=email,
                                                             stream=True)
        except Exception as e:
            return Response(data={"message": e.args[0]},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        if profile_data_clearbit and 'person' in profile_data_clearbit:
            new_user.profile.bio = profile_data_clearbit['person']['bio']
            new_user.profile.site = profile_data_clearbit['person']['site']
            new_user.profile.location = profile_data_clearbit['person'][
                'location']
            new_user.profile.timezone = profile_data_clearbit['person'][
                'timeZone']
            new_user.profile.utc_offset = profile_data_clearbit['person'][
                'utcOffset']
            new_user.profile.company_name = profile_data_clearbit['person'][
                'employment']['name']
            new_user.profile.company_role = profile_data_clearbit['person'][
                'employment']['role']
            new_user.profile.facebook_handle = profile_data_clearbit['person'][
                'facebook']['handle']
            new_user.profile.twitter_handle = profile_data_clearbit['person'][
                'twitter']['handle']
            new_user.profile.github_handle = profile_data_clearbit['person'][
                'github']['handle']
            new_user.profile.linkedin_handle = profile_data_clearbit['person'][
                'linkedin']['handle']
            new_user.profile.googleplus_handle = profile_data_clearbit[
                'person']['googleplus']['handle']
            new_user.save()

        return Response(data=UserSerializer(new_user).data,
                        status=status.HTTP_201_CREATED)