Пример #1
0
    def create(self, validated_data):
        try:
            request = self.context.get('request')
            user = request.user
            tenants = validated_data.get('tenants')
            created_by = validated_data.get('created_by')
            owned_by = validated_data.get('owned_by')
            with transaction.atomic():
                for tenant in tenants:
                    industry = tenant.pop(
                                    'industry'
                                    ) if 'industry' in tenant else None
                    regions = tenant.pop(
                                    'regions'
                                    ) if 'regions' in tenant else None
                    exists = Tenant.objects.filter(
                        user=user, domain=tenant.get(
                            'domain')).exists()
                    if exists:
                        raise CustomAPIException(
                            None,
                            "This domain is already taken",
                            status_code=status.HTTP_400_BAD_REQUEST
                        )

                    Tenant.objects.create(
                        user=user, created_by=created_by, owned_by=owned_by,
                        industry_id=industry, regions_id=regions, **tenant
                        )
                return validated_data

        except Exception as e:
            raise e
Пример #2
0
    def create(self, validated_data):
        try:
            request = self.context.get('request')
            user = request.user
            org_admin = Tenant.objects.filter(org_admin=user)
            if org_admin:
                tenant_id = org_admin.get().id
                domains = validated_data.get('domains')
                created_by = validated_data.get('created_by')
                owned_by = validated_data.get('owned_by')
                with transaction.atomic():
                    for domain in domains:
                        exists = Domains.objects.filter(domain=domain).exists()
                        if exists:
                            raise CustomAPIException(
                                None,
                                domain + " domain is already taken",
                                status_code=status.HTTP_400_BAD_REQUEST)

                        Domains.objects.create(tenant_id=tenant_id,
                                               domain=domain,
                                               created_by=created_by,
                                               owned_by=owned_by)
                    return validated_data

        except Exception as e:
            raise e
Пример #3
0
 def _exist_or_not_validator(self, exists_or_not):
     if exists_or_not:
         raise CustomAPIException(None,
                                  "email already exists",
                                  status_code=status.HTTP_400_BAD_REQUEST)
     else:
         return True
Пример #4
0
    def post(self, request, format=None):
        data = {}
        with transaction.atomic():
            user_is_active = self.queryset.filter(email=request.data['email'],
                                                  is_active=True)
            if not user_is_active:
                raise CustomAPIException(
                    None,
                    'sorry, Account is not active !',
                    status_code=status.HTTP_400_BAD_REQUEST)
            serializer = AuthTokenSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            user = serializer.validated_data['user']
            response = super(LoginView, self).post(request, format=None)
            if not user.is_superuser:
                user_detials = self.queryset.get(email=user)
                data['token'] = response.data['token']
                data['token_expiry'] = response.data['expiry']
                data['user_details'] = {
                    "user_id": user_detials.id,
                    "name": user_detials.name,
                    "email": user_detials.email,
                }

            return Response(data)
Пример #5
0
    def post(self, request, *args, **kwargs):
        user = self.queryset
        if request.data.get('email_id'):
            email_id = request.data['email_id']
        else:
            email_id = None
        new_password = request.data['new_password']
        confirm_password = request.data['confirm_password']
        try:
            if email_id:
                user_details_exiest = self.queryset.get(email=email_id).id

        except (TypeError, ValueError, OverflowError,
                get_user_model().DoesNotExist):
            raise CustomAPIException(None,
                                     'Matching User does not exist !',
                                     status_code=status.HTTP_404_NOT_FOUND)
        print("user_details_exiest", user_details_exiest)
        if user_details_exiest:
            if new_password == confirm_password:
                user = user.get(id=user_details_exiest)
                if not user.check_password(new_password):
                    user.set_password(new_password)  # set password...
                    user.save()
                else:
                    msg = 'Your new password is similar to old password.\
                             Please try with another password.'

                    raise CustomAPIException(
                        None, msg, status_code=status.HTTP_409_CONFLICT)
            return Response(
                {
                    'request_status': 1,
                    'result': {
                        'msg': "New Password Save Success..."
                    }
                },
                status=status.HTTP_200_OK)
        else:
            raise APIException({
                'request_status': 0,
                'result': {
                    'msg': "User does not exist."
                }
            })
Пример #6
0
 def post(self, request, format=None):
     serializer = self.serializer_class(data=request.data)
     if serializer.is_valid(raise_exception=True):
         data = {}
         with transaction.atomic():
             user_exist = self.queryset.filter(
                 email=request.data['email']).exists()
             if not user_exist:
                 raise CustomAPIException(
                     None,
                     'You Have Entered An Invalid Email Address',
                     status_code=status.HTTP_400_BAD_REQUEST)
             user_is_active = self.queryset.filter(
                 email=request.data['email'],
                 is_active=True)
             if not user_is_active:
                 raise CustomAPIException(
                     None,
                     "sorry, Account is not active !",
                     status=status.HTTP_400_BAD_REQUEST
                 )
             user = serializer.validated_data['user']
             response = super(LoginView, self).post(request, format=None)
             user_detials = self.queryset.get(email=user)
             user_detials.last_login = datetime.now()
             user_detials.save()
             profile_query = Profile.objects.filter(user=user)
             if profile_query:
                 first_name = profile_query.get().firstname
                 data['message'] = f'Hello {first_name}, Welcome Back!'
             data['token'] = response.data['token']
             data['token_expiry'] = response.data['expiry']
             data['user_details'] = {
                         "user_id": user_detials.id,
                         "name": user_detials.name,
                         "email": user_detials.email,
             }
             return Response(data)
     else:
         return Response(
             serializer.errors,
             status=status.HTTP_400_BAD_REQUEST
         )
Пример #7
0
    def validate(self, attrs):
        """Validate and authenticate the user"""
        email = attrs.get('email')
        password = attrs.get('password')

        user = authenticate(request=self.context.get('request'),
                            email=email,
                            password=password)
        if not user:
            msg = _('unable to authenticate with provided credential')
            raise CustomAPIException(None,
                                     msg,
                                     status_code=status.HTTP_400_BAD_REQUEST)

        attrs['user'] = user
        return attrs
Пример #8
0
    def create(self, validated_data):
        try:
            names = validated_data.get('names')
            with transaction.atomic():
                if not names:
                    raise CustomAPIException(
                        None,
                        "field is empty",
                        status_code=status.HTTP_400_BAD_REQUEST)
                for name in names:
                    Regions.objects.create(name=name)

                return validated_data

        except Exception as e:
            raise e
Пример #9
0
    def validate(self, attrs):
        """Validate and authenticate the user"""
        email = attrs.get('email')
        password = attrs.get('password')

        user = authenticate(request=self.context.get('request'),
                            email=email,
                            password=password)
        if not user:
            msg = _(
                'Invalid Login Credentials. Please Check Your Username & Password'
            )
            raise CustomAPIException(None,
                                     msg,
                                     status_code=status.HTTP_400_BAD_REQUEST)
        attrs['user'] = user
        return attrs
Пример #10
0
    def post(self, request, format=None):
        try:
            with transaction.atomic():
                email = request.data["email"]
                exist = User.objects.filter(email=email)
                if exist:
                    name = exist.get().name
                    send_mail_forgot_password.delay(name, email)
                    return Response(
                        {
                            'request_status': 1,
                            'msg': 'please check your mailid'
                        },
                        status=status.HTTP_200_OK)
                else:
                    raise CustomAPIException(
                        None,
                        'Email address does not belong to any account',
                        status_code=status.HTTP_404_NOT_FOUND)

        except ValueError as v:
            return v
Пример #11
0
    def post(self, request, format=None):
        try:
            data = {}
            with transaction.atomic():
                serializer = AuthTokenSerializer(data=request.data)
                serializer.is_valid(raise_exception=True)
                user = serializer.validated_data['user']
                response = super(LoginView, self).post(request, format=None)
                if not user.is_superuser:
                    user_detials = self.queryset.get(email=user)
                    # data['token'] = response.data['token']
                    # data['token_expiry'] = response.data['expiry']
                    # user_detials = User.objects.get(username=user)
                    role = RoleUserMappingTable.objects.filter(
                        user=user_detials.id)
                    menu_details_final = []
                    if role:
                        role_data = role.get().role
                        role_details = {
                            'id': role_data.id,
                            'role_name': role_data.name,
                        }
                        menu_details = RoleMenuMappingTable.objects.filter(
                            role=role_data.id,
                            is_deleted=False).values('menu', 'menu__name',
                                                     'menu__url',
                                                     'menu__parent_id',
                                                     'menu__icon')
                        print("menu_details", menu_details)

                        for menu in menu_details:
                            if menu['menu__parent_id'] == 'None':
                                data_dict = {
                                    'id': menu['menu'],
                                    'name': menu['menu__name'],
                                    'url': menu['menu__url'],
                                    'icon': menu['menu__icon'],
                                    "linkProps": {
                                        "queryParams": {}
                                    }
                                }

                                menu_details_final.append(data_dict)
                            else:
                                parent_data = Menu.objects.filter(
                                    id=menu['menu__parent_id']).values(
                                        'id', 'name', 'url', 'icon')
                                print("parent_data", parent_data)

                                if parent_data:
                                    check_id = parent_data[0]['id']
                                    print("check_id", check_id)
                                    danger_flag = 0
                                    for check_data in menu_details_final:
                                        if check_data['id'] == check_id:
                                            danger_flag = 1
                                    if danger_flag == 0:
                                        child_list = []
                                        meta_child = {}
                                        data_dict = parent_data[0]
                                        child_data = menu_details.filter(
                                            menu__parent_id=menu[
                                                'menu__parent_id']).values(
                                                    'menu', 'menu__name',
                                                    'menu__url',
                                                    'menu__parent_id',
                                                    'menu__icon', 'is_create',
                                                    'is_read', 'is_delete',
                                                    'is_edit')
                                        print("child_data", child_data)
                                        for child in child_data:
                                            meta_child = {
                                                'id': child['menu'],
                                                'name': child['menu__name'],
                                                'url': child['menu__url'],
                                                'icon': child['menu__url'],
                                                "linkProps": {
                                                    "queryParams": {
                                                        "is_create":
                                                        menu['is_create'],
                                                        "is_read":
                                                        menu['is_read'],
                                                        "is_delete":
                                                        menu['is_delete'],
                                                        "is_edit":
                                                        menu['is_edit']
                                                    }
                                                }
                                            }
                                            child_list.append(meta_child)
                                        data_dict['children'] = child_list
                                        if data_dict not in menu_details_final:
                                            menu_details_final.append(
                                                data_dict)

                    else:
                        role_details = {}
                        menu_details_final = []

                    data['token'] = response.data['token']
                    data['token_expiry'] = response.data['expiry']
                    data['role_details'] = role_details
                    data['menu_details'] = menu_details_final
                    data['user_details'] = {
                        "user_id": user_detials.id,
                        "name": user_detials.name,
                        "email": user_detials.email,
                    }

                return Response(data)
        except Exception:
            raise CustomAPIException(
                None,
                'Unable to login with provided credential',
                status_code=status.HTTP_400_BAD_REQUEST)
Пример #12
0
    def create(self, validated_data):

        user = self.context['request'].user
        created_by = validated_data.get('created_by')
        owned_by = validated_data.get('owned_by')
        upload_file = validated_data.get('report_file')
        file_name = upload_file.name
        file_exist = ReportDumpUploadbkp.objects.filter(
            file_name=file_name
            ).exists()
        file_data = xml_to_json(upload_file)
        file_json = json.loads(file_data)

        if file_exist:
            raise CustomAPIException(
                None,
                "Duplicate ! The file with same name is already in data base ",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        domain_list = Tenant.objects.filter(
                                            user=user
                                            ).values_list('domain', flat=True)
        to_check = file_json['feedback']['policy_published']['domain']
        if to_check not in domain_list:
            raise CustomAPIException(
                None,
                "sorry ! Report does not belong to any of registered domain" +
                " please add "+to_check+" to upload this report",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        with transaction.atomic():

            ReportDumpUploadbkp.objects.create(
                user=user,
                data=file_json,
                file_name=file_name,
                created_by=created_by,
                owned_by=owned_by
                )

            meta_data_report = ReportFeedbackMetaData.objects.create(
                user=user,
                org_name=file_json['feedback']['report_metadata']['org_name'],
                email=file_json['feedback']['report_metadata']['email'],
                extra_contact_info=file_json['feedback'][
                                    'report_metadata'][
                                        'extra_contact_info'
                                        ] if 'extra_contact_info' in file_json[
                                            'feedback'][
                                    'report_metadata'] else None,
                report_id=file_json['feedback'][
                                    'report_metadata'][
                                        'report_id'],
                begin=datetime.fromtimestamp(int(
                    file_json['feedback'][
                                    'report_metadata'][
                                        'date_range']['begin'])),
                end=datetime.fromtimestamp(int(
                    file_json['feedback'][
                        'report_metadata'][
                            'date_range']['end']
                    )),
                domain=file_json['feedback'][
                                'policy_published']['domain'],
                adkim=file_json['feedback'][
                                'policy_published']['adkim'],
                aspf=file_json['feedback']['policy_published']['aspf'],
                p=file_json['feedback']['policy_published']['p'],
                sp=file_json['feedback']['policy_published']['sp'],
                pct=file_json['feedback']['policy_published']['pct'],
                created_by=created_by,
                owned_by=owned_by
            )
            records = file_json['feedback']['record']
            if isinstance(records, (list)):
                for record in records:
                    try:
                        rev_name = reversename.from_address(
                            record['row']['source_ip'])
                        reversed_dns = str(resolver.query(rev_name, "PTR")[0])
                    except Exception:
                        reversed_dns = record['row']['source_ip']
                    records_created = ReportFeedbackRecord.objects.create(
                        meta_report=meta_data_report,
                        source_ip=record['row']['source_ip'],
                        ip_name=reversed_dns,
                        count=record['row']['count'],
                        disposition=record['row'][
                                    'policy_evaluated']['disposition'],
                        dkim=record['row'][
                                    'policy_evaluated']['dkim'],
                        spf=record['row'][
                                        'policy_evaluated']['spf'],
                        header_from=record[
                            'identifiers'][
                            'header_from'] if 'header_from'in record[
                                'identifiers'] else None,
                        envelope_from=record[
                            'identifiers'][
                            'envelope_from'] if 'envelope_from' in record[
                            'identifiers'] else None,
                    )
                    auth_dkim = record[
                        'auth_results']['dkim'] if 'dkim' in record[
                        'auth_results'] else None
                    auth_spf = record[
                        'auth_results']['spf'] if 'spf' in record[
                        'auth_results'] else None
                    if auth_dkim:
                        if isinstance(auth_dkim, (list)):
                            for au_dkim in auth_dkim:
                                ReportFeedbackRecordAuthResultsDkim.objects.\
                                 create(
                                    record=records_created,
                                    domain=au_dkim[
                                        'domain'
                                        ] if 'domain' in au_dkim else None,
                                    selector=au_dkim[
                                        'selector'
                                        ] if 'selector' in au_dkim else None,
                                    result=au_dkim[
                                        'result'
                                        ] if 'result' in au_dkim else None,
                                    created_by=created_by,
                                    owned_by=owned_by
                                    )
                        else:
                            ReportFeedbackRecordAuthResultsDkim.objects.create(
                                    record=records_created,
                                    domain=auth_dkim[
                                        'domain'
                                        ] if 'domain' in auth_dkim else None,
                                    selector=auth_dkim[
                                        'selector'
                                        ] if 'selector' in auth_dkim else None,
                                    result=auth_dkim[
                                        'result'
                                        ]if 'result' in auth_dkim else None,
                                    created_by=created_by,
                                    owned_by=owned_by
                                )
                    if auth_spf:
                        if isinstance(auth_spf, (list)):
                            for au_spf in auth_spf:
                                ReportFeedbackRecordAuthResultsSpf.objects.\
                                 create(
                                    record=records_created,
                                    domain=au_spf[
                                        'domain'
                                        ] if 'domain' in au_spf else None,
                                    scope=au_spf[
                                        'scope'
                                        ] if 'scope' in au_spf else None,
                                    result=au_spf[
                                        'result'
                                        ] if 'result' in au_spf else None,
                                    created_by=created_by,
                                    owned_by=owned_by

                                    )
                        else:
                            ReportFeedbackRecordAuthResultsSpf.objects.create(
                                    record=records_created,
                                    domain=auth_spf[
                                        'domain'
                                        ] if 'domain' in auth_spf else None,
                                    scope=auth_spf[
                                        'scope'
                                        ] if 'scope' in auth_spf else None,
                                    result=auth_spf[
                                        'result'
                                        ] if 'result' in auth_spf else None,
                                    created_by=created_by,
                                    owned_by=owned_by
                                )
            else:
                try:
                    rev_name = reversename.from_address(
                        records['row']['source_ip'])
                    reversed_dns = str(resolver.query(rev_name, "PTR")[0])
                except Exception:
                    reversed_dns = records['row']['source_ip']
                records_created = ReportFeedbackRecord.objects.create(
                        meta_report=meta_data_report,
                        source_ip=records['row']['source_ip'],
                        ip_name=reversed_dns,
                        count=records['row']['count'],
                        disposition=records['row']['policy_evaluated'][
                                            'disposition'],
                        dkim=records['row']['policy_evaluated'][
                                            'dkim'],
                        spf=records['row']['policy_evaluated'][
                                            'spf'],
                        header_from=records['identifiers'][
                                            'header_from'
                                            ] if 'header_from' in records[
                                                'identifiers'] else None,
                        envelope_from=records[
                                        'identifiers'
                                        ][
                                            'envelope_from'
                                            ] if 'envelope_from' in records[
                                                'identifiers'
                                                ] else None,
                        )
                auth_dkim = records['auth_results'][
                                'dkim'
                                ] if 'dkim' in records[
                                    'auth_results'] else None
                auth_spf = records['auth_results'][
                                'spf'] if 'spf' in records[
                                    'auth_results'] else None
                if auth_dkim:
                    if isinstance(auth_dkim, (list)):
                        for au_dkim in auth_dkim:
                            ReportFeedbackRecordAuthResultsDkim.objects.create(
                                record=records_created,
                                domain=au_dkim[
                                        'domain'
                                        ] if 'domain' in au_dkim else None,
                                selector=au_dkim[
                                          'selector'
                                         ] if 'selector' in au_dkim else None,
                                result=au_dkim[
                                        'result'
                                        ] if 'result' in au_dkim else None,
                                created_by=created_by,
                                owned_by=owned_by
                            )
                    else:
                        ReportFeedbackRecordAuthResultsDkim.objects.create(
                                record=records_created,
                                domain=auth_dkim[
                                         'domain'
                                         ] if 'domain' in auth_dkim else None,
                                selector=auth_dkim[
                                          'selector'
                                        ] if 'selector' in auth_dkim else None,
                                result=auth_dkim[
                                        'result'
                                        ] if 'result' in auth_dkim else None,
                                created_by=created_by,
                                owned_by=owned_by
                            )
                if auth_spf:
                    if isinstance(auth_spf, (list)):
                        for au_spf in auth_spf:
                            ReportFeedbackRecordAuthResultsSpf.objects.create(
                                record=records_created,
                                domain=au_spf[
                                        'domain'
                                        ] if 'domain' in au_spf else None,
                                scope=au_spf[
                                        'scope'
                                        ] if 'scope' in au_spf else None,
                                result=au_spf[
                                        'result'
                                        ] if 'result' in au_spf else None,
                                created_by=created_by,
                                owned_by=owned_by

                            )
                    else:
                        ReportFeedbackRecordAuthResultsSpf.objects.create(
                                record=records_created,
                                domain=auth_spf[
                                        'domain'
                                        ] if 'domain' in auth_spf else None,
                                scope=auth_spf[
                                        'scope'
                                        ] if 'scope' in auth_spf else None,
                                result=auth_spf[
                                        'result'
                                        ] if 'result' in auth_spf else None,
                                created_by=created_by,
                                owned_by=owned_by
                            )

        validated_data.pop('report_file')
        validated_data['file_data'] = file_json
        return validated_data
Пример #13
0
    def create(self, validated_data):
        """Create a new user with encrypted password and return it"""
        try:
            request = self.context.get('request')
            company_name = validated_data.pop('company_name')
            primary_domain_name = validated_data.pop('primary_domain_name')
            firstname = validated_data.get('firstname')
            lastname = validated_data.get('lastname')

            if len(validated_data.get('password')) < 8:
                raise CustomAPIException(
                    None,
                    "length of password must be equal or greater than 8 char ",
                    status_code=status.HTTP_400_BAD_REQUEST)

            exists_or_not = get_user_model().objects.filter(
                email=validated_data.get('email')).exists()
            if exists_or_not:
                raise CustomAPIException(
                    None,
                    "email already exists",
                    status_code=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                try:
                    user = get_user_model().objects.\
                                    create_user(
                                        email=validated_data.get('email'),
                                        name=firstname+" "+lastname,
                                        password=validated_data.get('password')
                                    )
                    user.is_active = False
                    user.save()
                    current_site = get_current_site(request)
                    print("current_site", current_site)
                    Profile.objects.create(user=user,
                                           firstname=firstname,
                                           lastname=lastname,
                                           email=validated_data.get('email'))

                except Exception:
                    raise CustomAPIException(
                        None,
                        "error ! bad request please check input",
                        status_code=status.HTTP_400_BAD_REQUEST)
                try:
                    if primary_domain_name:
                        domain_exist = Domains.objects.filter(
                            domain=primary_domain_name).exists()
                        if not domain_exist:
                            tenant, created = Tenant.objects.get_or_create(
                                org_admin=user,
                                company_name=company_name,
                            )
                            Domains.objects.create(tenant=tenant,
                                                   domain=primary_domain_name)
                            TenantUserMapping.objects.create(tenant=tenant,
                                                             user=user)
                        else:
                            raise CustomAPIException(
                                None,
                                "sorry! domain " + primary_domain_name +
                                " is already taken ",
                                status_code=status.HTTP_400_BAD_REQUEST)
                    validated_data['company_name'] = company_name
                    validated_data['user'] = user
                    validated_data['primary_domain_name'] = primary_domain_name
                except Exception as e:
                    raise e
            role = Role.objects.filter(name='ADMIN')
            if role:
                role_id = role.get().id
            RoleUserMappingTable.objects.create(user=user, role_id=role_id)
            email = validated_data.get('email')
            name = firstname + " " + lastname
            if current_site.domain.lower() == 'localhost':
                domain = current_site.domain + ':8089'
            else:
                domain = current_site.domain
            uid = urlsafe_base64_encode(force_bytes(user.pk))
            token = generate_token.make_token(user)
            send_mail_for_account_activation.delay(email, name, domain, uid,
                                                   token)

            validated_data.pop('password')
            return validated_data
        except Exception as e:
            raise e
Пример #14
0
    def create(self, validated_data):
        try:
            request = self.context.get('request')
            created_by = validated_data.get('created_by')
            owned_by = validated_data.get('owned_by')
            is_admin = models.RoleUserMappingTable.objects.filter(
                user=request.user).values_list('role__name', flat=True)
            with transaction.atomic():
                firstname = validated_data.get(
                    'firstname') if validated_data.get('firstname') else ""
                lastname = validated_data.get(
                    'lastname') if validated_data.get('lastname') else ""
                email = validated_data.get('email') if validated_data.get(
                    'email') else None
                password = validated_data.get(
                    'password') if validated_data.get('password') else None
                confirm_password = validated_data.get(
                    'confirm_password') if validated_data.get(
                        'confirm_password') else None
                role = validated_data.get('role') if validated_data.get(
                    'role') else ""
                if email is None or password is None:
                    raise CustomAPIException(
                        None,
                        "Please provide both email and password ",
                        status_code=status.HTTP_400_BAD_REQUEST)
                else:
                    if password == confirm_password:
                        if models.User.objects.filter(email=email).exists():
                            raise CustomAPIException(
                                None,
                                "Email ID already exist ",
                                status_code=status.HTTP_409_CONFLICT)
                        else:
                            if 'ADMIN' in is_admin:
                                user = models.User.objects.create_user(
                                    email=email,
                                    name=firstname + ' ' + lastname)
                                user.set_password(password)
                                user.is_active = True
                                user.save()

                                models.Profile.objects.create(
                                    user=user,
                                    firstname=firstname,
                                    lastname=lastname,
                                    email=validated_data.get('email'))

                                models.RoleUserMappingTable.\
                                    objects.create(
                                        user=user,
                                        role_id=role,
                                        created_by=created_by,
                                        owned_by=owned_by
                                        )
                            else:
                                raise CustomAPIException(
                                    None,
                                    "Access denied !",
                                    status_code=status.HTTP_409_CONFLICT)
                    else:
                        raise CustomAPIException(
                            None,
                            "Password did not matched",
                            status_code=status.HTTP_409_CONFLICT)

                validated_data['is_active'] = user.is_active
                validated_data['user'] = {
                    'user_id': user.__dict__['id'],
                    'user_email': user.__dict__['email']
                }

                return validated_data

        except Exception as e:
            raise e
Пример #15
0
    def create(self, validated_data):
        """Create a new user with encrypted password and return it"""
        try:
            company_name = validated_data.pop('company_name')
            primary_domain_name = validated_data.pop('primary_domain_name')
            firstname = validated_data.get('firstname')
            lastname = validated_data.get('lastname')

            if len(validated_data.get('password')) < 8:
                raise CustomAPIException(
                    None,
                    "length of password must be equal or greater than 8 char ",
                    status_code=status.HTTP_400_BAD_REQUEST
                    )

            exists_or_not = get_user_model().objects.filter(
                                    email=validated_data.get(
                                        'email'
                                        )
                                    ).exists()
            if exists_or_not:
                raise CustomAPIException(
                    None,
                    "email already exists",
                    status_code=status.HTTP_400_BAD_REQUEST
                    )

            with transaction.atomic():
                try:
                    user = get_user_model().objects.\
                                    create_user(
                                        email=validated_data.get('email'),
                                        name=firstname+" "+lastname,
                                        password=validated_data.get('password')
                                    )
                    Profile.objects.create(
                        user=user,
                        firstname=firstname,
                        lastname=lastname,
                        email=validated_data.get('email')
                    )

                except Exception:
                    raise CustomAPIException(
                        None,
                        "error ! bad request please check input",
                        status_code=status.HTTP_400_BAD_REQUEST
                    )
                try:
                    if primary_domain_name:
                        Tenant.objects.get_or_create(
                            user=user,
                            company_name=company_name,
                            domain=primary_domain_name
                            )
                    validated_data['company_name'] = company_name
                    validated_data['user'] = user
                    validated_data['primary_domain_name'] = primary_domain_name
                except Exception:
                    raise CustomAPIException(
                        None,
                        "error ! bad request please check input",
                        status_code=status.HTTP_400_BAD_REQUEST
                    )
            validated_data.pop('password')
            return validated_data
        except Exception as e:
            raise e