def save_user(validated_data):
     user = User(email=validated_data['email'])
     user.set_password(validated_data['password'])
     user.first_name = validated_data.get('first_name', None)
     user.last_name = validated_data.get('last_name', None)
     user.is_active = True
     user.save()
Exemple #2
0
 def save_user(validated_data):
     invitation = InvitationToUserAndWarehouseAdmin.objects.filter(email=validated_data['email']).first()
     if invitation is not None:
         if invitation.accepted:
             user = User(email=validated_data['email'])
             user.set_password(validated_data['password'])
             user.first_name = invitation.first_name
             user.last_name = invitation.last_name
             user.is_staff = False
             user.is_active = True
             user.role = invitation.role
             user.email_confirmation_token = generate_unique_key(user.email)
             user.save()
             if user.role == 'general':
                 company_general_user = CompanyUser(user=user, company=invitation.company)
                 company_general_user.save()
             elif user.role == 'warehouse':
                 warehouse_admin = CompanyWarehouseAdmins(user=user, company=invitation.company)
                 warehouse_admin.save()
             msg = "%s %s (%s) accepted your invitation." % (
                 invitation.first_name, invitation.first_name, invitation.role)
             from_invited_user = User.objects.filter(pk=invitation.user).first()
             print(from_invited_user)
             if from_invited_user.role == 'warehouse':
                 notif = WarehouseAdminNotifications(user=from_invited_user.id, text=msg, seen=False)
                 notif.save()
             notification = CompanyAdminsNotification(company=invitation.company, text=msg)
             notification.save()
             InvitationToUserAndWarehouseAdmin.objects.filter(email=validated_data['email']).delete()
         else:
             raise serializers.ValidationError({'detail': 'Account not accepted.'})
     else:
         raise serializers.ValidationError({'detail': 'Invalid email'})
Exemple #3
0
 def save_user(validated_data):
     user = User(email=validated_data['email'])
     user.set_password(validated_data['password'])
     user.is_staff = False
     user.is_active = True
     user.email_confirmation_token = generate_unique_key(user.email)
     user.save()
Exemple #4
0
    def post(self, request):
        """
        对注册页面发送过来的form表单数据进行处理
        :return:
        """
        # 获取post请求参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        uphone = request.POST.get('mobile')
        code = request.POST.get('code')
        email = request.POST.get('email')
        allow = request.POST.get('allow')  # 用户协议,勾选后得到:on
        print('手机 验证码', uphone, code, request.session.get('message_code'))
        # todo:检验参数合法性
        # 判断参数不能为空
        if not all([username, password, password2, email, uphone, code]):
            return render(request, 'register.html', {'errmsg': "注册信息不能为空"})
        # 判断两次输入的密码是否一致
        if password != password2:
            return render(request, 'register.html', {'errmsg': "两次密码不一致"})
        # 判断邮箱合法
        if not re.match('^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',
                        email):
            return render(request, 'register.html', {'errmsg': "邮箱不合法"})
        # 判断是否勾选用户协议
        if allow != 'on':
            return render(request, 'register.html', {'errmsg': "请勾选用户协议"})
        # 判断手机输入是否正确
        if not re.match('^1[345678]\d{9}$', uphone):
            return render(request, 'register.html', {'errmsg': "手机输入不合法"})
        # 判断验证码是否正确
        if code != request.session.get('message_code'):
            return render(request, 'register.html', {'errmsg': "验证码校验错误"})
        # 处理业务:保存用户到数据表中
        # django提供的方法,会对密码进行加密
        user = User()
        try:
            user = User.objects.create_user(username,
                                            email,
                                            password,
                                            uphone=uphone)  # type: User
            # 修改用户状态为未激活
            user.is_active = False
            user.save()
        except IntegrityError:
            # 判断用户是否存在
            return render(request, 'register.html', {'errmsg': "用户名已存在"})

        # todo:发送激活邮件
        token = user.generate_active_token()
        # 同步发送:会阻塞
        # RegisterView.send_active_email(username, email, token)
        # 使用celery异步发送:不会阻塞
        # 会保存方法名
        send_active_email.delay(username, email, token)

        return HttpResponse("注册成功!")
Exemple #5
0
 def save_user(validated_data):
     """
     Saving signed up user to db,
     Send email address confirmation email to user.
     """
     user = User(email=validated_data['email'])
     user.set_password(validated_data['password'])
     user.is_active = False
     user.first_name = validated_data['first_name']
     user.last_name = validated_data['last_name']
     user.is_active = False
     user.email_confirmation_token = generate_unique_key(user.email)
     user.save()
     send_email_job(
         user.email,
         'account_confirmation',
         {'token': user.email_confirmation_token},
         'Email Confirmation',
     )
Exemple #6
0
    def save_user(validated_data):
        user = User(email=validated_data['email'],
                    name=validated_data['name'],
                    phone_number=validated_data['phone_number'])
        user.set_password(validated_data['password'])
        user.is_active = False
        user.email_confirmation_token = generate_unique_key(user.email)
        user.save()

        send_email_job_registration(
            'Print Studio',
            user.email,
            'account_confirmation',
            {
                'token': user.email_confirmation_token,
                'name': user.name
            },
            'Welcome to Print Studio',
        )
def set_new_social_user_inactive(sender, instance: User, **_kwargs):
    if instance._state.adding is not True:
        return
    if instance.id:
        return
    if instance.origin != User.USER_ORIGIN_SOCIAL:
        return

    from apps.users.app_vars import ALLOWED_EMAIL_DOMAINS, AUTO_REG_EMAIL_DOMAINS

    email = instance.email
    is_auto_reg_email = email_follows_pattern(email,
                                              AUTO_REG_EMAIL_DOMAINS.val)
    if is_auto_reg_email:
        return

    is_allowed_email = email_follows_pattern(email, ALLOWED_EMAIL_DOMAINS.val)
    if is_allowed_email:
        # this is a new social account registration - we'll make it inactive
        # until the administrator confirms the user account
        instance.is_active = False
        return
    logger.error(f'email "{email}" is not allowed')
    raise PermissionDenied()
Exemple #8
0
class TestUser:
    def setup_method(self):

        self.data = {
            'email': '*****@*****.**',
            'password': '******',
            'active': True,
            'full_name': 'Teste',
            'cpf_cnpj': '11111111111'
        }

        # Crio uma instancia do modelo User
        self.model = User(**self.data)

    def test_email_field_exists(self):
        """
        Verifico se o campo email existe
        """
        assert 'email' in self.model._fields

    def test_email_field_is_required(self):
        """
        Verifico se o campo email é requirido
        """
        assert self.model._fields['email'].required is True

    def test_email_field_is_unique(self):
        """
        Verifico se o campo email é unico
        """
        assert self.model._fields['email'].unique is True

    def test_email_field_is_str(self):
        """
        Verifico se o campo email é do tipo string
        """
        assert isinstance(self.model._fields['email'], StringField)

    def test_active_field_exists(self):
        assert 'active' in self.model._fields

    def test_active_field_is_default_true(self):
        assert self.model._fields['active'].default is False

    def test_is_active_is_false(self):
        assert self.model.is_active() is True

    def test_active_field_is_bool(self):
        """
        Verifico se o campo active é booleano
        """
        assert isinstance(self.model._fields['active'], BooleanField)

    def test_full_name_field_exists(self):
        """
        Verifico se o campo full_name existe
        """
        assert 'full_name' in self.model._fields

    def test_full_name_field_is_str(self):
        assert isinstance(self.model._fields['full_name'], StringField)

    def test_full_name_field_is_required(self):
        """
        Verifico se o campo full_name é requirido
        """
        assert self.model._fields['full_name'].required is True

    def test_cpf_cnpj_field_exists(self):
        """
        Verifico se o campo cpf_cnpj existe
        """
        assert 'cpf_cnpj' in self.model._fields

    def test_cpf_cnpj_field_is_required(self):
        """
        Verifico se o campo cpf_cnpj é requirido
        """
        assert self.model._fields['cpf_cnpj'].required is False

    def test_cpf_cnpj_field_is_unique(self):
        """
        Verifico se o campo cpf_cnpj é unico
        """
        assert self.model._fields['cpf_cnpj'].unique is False

    def test_cpf_cnpj_field_is_str(self):
        """
        Verifico se o campo cpf_cnpj é do tipo string
        """
        assert isinstance(self.model._fields['cpf_cnpj'], StringField)

    def test_cpf_cnpj_field_is_default_true(self):
        assert self.model._fields['cpf_cnpj'].default == ''

    def test_all_fields_in_model(self):
        """
        Verifico se todos os campos estão de fato no meu modelo
        """
        fields = [
            'active', 'address', 'cpf_cnpj', 'created', 'email', 'full_name',
            'id', 'password', 'roles'
        ]

        model_keys = [i for i in self.model._fields.keys()]

        fields.sort()
        model_keys.sort()

        assert fields == model_keys
Exemple #9
0
    def register(self, request):
        """
        # Register  a new user.

            NOTE. the 'photo' param is required only in this documentation.
        ---
        request_serializer: RegisterSerializer
        response_serializer: UserSerializer
        parameters_strategy: merge
        consumes:
            - application/json

        produces:
            - application/json
        """

        serializer = RegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        application = PlatformApp.objects.get(
            client_id=serializer.data["client_id"],
            client_secret=serializer.data["client_secret"],
        )

        #  ------------------------------------------------------------------------------
        #     ADD application perms in here
        #  ------------------------------------------------------------------------------

        _data = serializer.data.copy()
        del _data["client_id"]
        del _data["client_secret"]
        del _data["password"]

        registered, reason = self.is_user_already_registered(_data)

        if not registered:
            # Create user
            user = User(**_data)
            user.is_staff = False

            # Set activate
            user.is_active = not application.has_confirmation

            # Set password
            user.set_password(serializer.data["password"])
            user.save()

            action = UserAction(
                user=user,
                type=UserAction.ACTION_ENABLE_ACCOUNT,
            )

            action.token = get_uuid()
            action.creation_date, action.expiration_date = get_lapse()
            action.save()

            # Send email
            if application.has_confirmation:
                messaging.send_account_activation(request, action)
            else:
                messaging.send_welcome(request, action)

            user_registered_signal.send(sender=user.__class__, user=user)

            return Response(UserSerializer(user, many=False).data,
                            status=status.HTTP_201_CREATED)

        else:
            raise ValidationError(
                detail=reason,
                code=codes.REGISTERED_USER,
            )