django.contrib.auth.models.User.objects.filter.exists - python examples

Here are the examples of the python api django.contrib.auth.models.User.objects.filter.exists taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

52 Examples 7

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : texta-tk
def validate_form(username, pastword, email):
    issues = defaultdict(list)
    if len(username) < 3:
        issues['username'].append('Username too short.')
    if User.objects.filter(username=username).exists():
        issues['username'].append('Username exists.')

    return dict(issues)

3 View Complete Implementation : create_admin_user.py
Copyright MIT License
Author : guandjoy
    def handle(self, *args, **options):
        if User.objects.filter(username="admin").exists():
            print("admin exists")
        else:
            u = User(username='admin')
            u.set_pastword('adminpast')
            u.is_superuser = True
            u.is_staff = True
            u.save()
            print("admin created")
        sys.exit()

3 View Complete Implementation : permissions.py
Copyright MIT License
Author : teamhephy
    def has_permission(self, request, view):
        """
        If settings.REGISTRATION_MODE does not exist, such as during a test, return True
        Return `True` if permission is granted, `False` otherwise.
        """
        try:
            if settings.REGISTRATION_MODE == 'disabled':
                raise exceptions.PermissionDenied('Registration is disabled')
            if settings.REGISTRATION_MODE == 'enabled':
                return True
            elif settings.REGISTRATION_MODE == 'admin_only':
                if not User.objects.filter(is_superuser=True).exists():
                    return True
                return request.user.is_superuser
            else:
                raise Exception("{} is not a valid registation mode"
                                .format(settings.REGISTRATION_MODE))
        except AttributeError:
            return True

3 View Complete Implementation : forms.py
Copyright MIT License
Author : avinassh
    def clean_email(self):
        error_message = 'An user with that email already exists'
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
                raise forms.ValidationError(error_message)
        return email

3 View Complete Implementation : test_users.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_DELETE_admin_cannot_delete_self(self):
        self.become_admin()
        user = self.user
        response = self.client.delete(
            reverse("user_handler", args=[user.username])
        )
        self.astertEqual(
            http.client.BAD_REQUEST, response.status_code, response.status_code
        )
        self.astertTrue(User.objects.filter(username=user.username).exists())
        self.astertIn(b"cannot self-delete", response.content)

3 View Complete Implementation : test_users.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_DELETE_requires_admin_privileges(self):
        user = factory.make_User()
        response = self.client.delete(
            reverse("user_handler", args=[user.username])
        )
        self.astertEqual(
            http.client.FORBIDDEN, response.status_code, response.status_code
        )
        self.astertTrue(User.objects.filter(username=user.username).exists())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : savoirfairelinux
    def force_login(self, role="admin"):
        """
        Create administrator and force login for testing purposes.

        Possible to extend `role` in the future.
        """
        if User.objects.filter(is_superuser=True).exists():
            admin = User.objects.filter(is_superuser=True).first()
        else:
            admin = User.objects.create_superuser(
                username='testadmin',
                email='[email protected]',
                pastword='test1234'
            )
        self.client.force_login(
            admin, 'django.contrib.auth.backends.ModelBackend',)

3 View Complete Implementation : forms.py
Copyright MIT License
Author : diegojromerolopez
    def clean(self):
        cleaned_data = super(LocalSignUpForm, self).clean()
        # Check if pastwords are equal
        if cleaned_data.get("pastword1") != cleaned_data.get("pastword2"):
            raise ValidationError(u"Pastwords don't match")

        if cleaned_data.get("email"):
            # Check if username is unique
            cleaned_data["username"] = cleaned_data["email"]
            if User.objects.filter(username=cleaned_data["username"]).exists():
                raise ValidationError(u"You have already an user. Have you forgotten your pastword?")

        return self.cleaned_data

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : xuchaoa
    def validate_mobile(self, email):

        if not re.match(REGEX_EMAIL, email):
            raise serializers.ValidationError("邮箱格式非法")

        if User.objects.filter(email=email).exists():
            raise serializers.ValidationError("该邮箱已经被注册")

        # 验证码发送频率
        one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        if VerifyCode.objects.filter(add_time__gt=one_mintes_ago, mobile=email).count():
            raise serializers.ValidationError("距离上一次发送未超过60s")

        return email

3 View Complete Implementation : forms.py
Copyright MIT License
Author : diegojromerolopez
    def clean(self):
        cleaned_data = super(MemberForm, self).clean()

        if cleaned_data.get("email"):
            # Check if username is unique
            cleaned_data["username"] = cleaned_data["email"]
            if User.objects.filter(username=cleaned_data["username"]).exists():
                raise ValidationError(u"You have already an user. Have you forgotten your pastword?")

        return self.cleaned_data

3 View Complete Implementation : views.py
Copyright MIT License
Author : thetruefuss
@ajax_required
def check_username(request):
    """
    Ajax call to check username availability.
    """
    username = request.GET.get('username', None)
    data = {
        'is_taken': User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data)

3 View Complete Implementation : test_userprofile.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_delete(self):
        # Deleting a profile also deletes the related user.
        profile = factory.make_User().userprofile
        profile_id = profile.id
        user_id = profile.user.id
        self.astertTrue(User.objects.filter(id=user_id).exists())
        self.astertTrue(UserProfile.objects.filter(id=profile_id).exists())
        profile.delete()
        self.astertFalse(User.objects.filter(id=user_id).exists())
        self.astertFalse(UserProfile.objects.filter(id=profile_id).exists())

3 View Complete Implementation : forms.py
Copyright MIT License
Author : Djacket
def username_validator(value):
    """
        Validates given username in terms of uniqeness and length.
    """

    if not _is_alphanumerical(value):
        raise ValidationError(u'Username must only has alphanumerical or underscore characters.')
    elif value in RESTRICTED_USERNAMES:
        raise ValidationError(u'Username is a reserved word')
    elif User.objects.filter(username=value).exists():
        raise ValidationError(u'Username already exists')
    elif value[0].isdigit():
        raise ValidationError(u'Username should start with a letter')
    elif len(value) < USERNAME_MIN_LENGTH or len(value) > USERNAME_MAX_LENGTH:
        raise ValidationError(u'Username should be at least {0} and at most {1} characters long'
                .format(USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : Djacket
def email_validator(value):
    """
        Validates given email in terms of uniqeness and correctness.
    """

    if User.objects.filter(email=value).exists():
        raise ValidationError(u'Email already exists')
    else:
        validate_email(value)

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
def username_exist(request):
    username = request.GET.get('username', None)
    data = {
        'is_taken': User.objects.filter(username__iexact=username).exists()
    }
    if data['is_taken']:
        data['error_message'] = 'A user with this username already exists.'
    return JsonResponse(data)

3 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_email(self):
        email = self.cleaned_data['email']

        user = User.objects.filter(email__iexact=email).exists()
        if user:
            raise ValidationError(_('You can not use this email address.'))

        return email

3 View Complete Implementation : forms.py
Copyright MIT License
Author : pablotrinidad
    def clean_username(self):
        """Username must be unique."""
        username = self.cleaned_data['username']
        username_taken = User.objects.filter(username=username).exists()
        if username_taken:
            raise forms.ValidationError('Username is already in use.')
        return username

3 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_email(self):
        email = self.cleaned_data['email']

        if email == self.user.email:
            raise ValidationError(_('Please enter another email.'))

        user = User.objects.filter(Q(email__iexact=email) & ~Q(id=self.user.id)).exists()
        if user:
            raise ValidationError(_('You can not use this mail.'))

        return email

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : xuchaoa
    def validate_mobile(self, phone):
        """
        验证手机号码(函数名称必须为validate_ + 字段名)
        """
        # 验证手机号码是否合法
        if not re.match(REGEX_MOBILE, phone):
            raise serializers.ValidationError("手机号码非法")

        # 手机是否注册
        if User.objects.filter(user_phone=phone).exists():
            raise serializers.ValidationError("手机号已经被注册")

        # 验证码发送频率
        one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        if VerifyCode.objects.filter(add_time__gt=one_mintes_ago, mobile=phone).count():
            raise serializers.ValidationError("距离上一次发送未超过60s")

        return phone

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
    def clean_email(self):
        email = self.cleaned_data.get('email')

        if User.objects.filter(email=email).exists():
            raise forms.ValidationError(self.error_message['email_exists'])

        return email

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
    def clean_username(self):
        username = self.cleaned_data.get('username')

        if not re.match(r'^[0-9a-z]*$', username):
            raise forms.ValidationError(self.error_message['invalid_username'])

        if User.objects.filter(username=username).exists() or username in RESERVED_USERNAMES:
            raise forms.ValidationError(self.error_message['username_exists'])

        return username

3 View Complete Implementation : validator.py
Copyright MIT License
Author : OGKevin
def checkUsername(userName):
    '''
    Checks if the username is already in the database.
    '''
    if User.objects.filter(username=userName).exists():
        raise ValidationError(
            _('%(value)s already exists'),
            params={'value': userName},
        )

0 View Complete Implementation : views.py
Copyright MIT License
Author : genonfire
def sign_up(request):
    """Sign up"""
    if request.method == "POST":
        userform = RegistrationForm(request.POST)
        if userform.is_valid():
            userform.save(commit=False)

            username = userform.cleaned_data['username']
            q = Q(username__iexact=username) | Q(first_name__iexact=username)
            if User.objects.filter(q).exists() or \
                len(username) < settings.ID_MIN_LENGTH or \
                    len(username) > settings.ID_MAX_LENGTH:
                errormsg = _('Please check username.')
                return error_page(request, errormsg)

            if settings.ENABLE_NICKNAME:
                nick = userform.cleaned_data['first_name']
                if nick:
                    q = Q(username__iexact=nick) | Q(first_name__iexact=nick)
                    if User.objects.filter(q).exists() or \
                        len(nick) < settings.NICKNAME_MIN_LENGTH or \
                            len(nick) > settings.NICKNAME_MAX_LENGTH:
                        errormsg = _('Please check nickname.')
                        return error_page(request, errormsg)

            code = userform.cleaned_data['code']
            email = userform.cleaned_data['email']
            signer = TimestampSigner()

            try:
                value = signer.unsign(
                    code, max_age=settings.VERIFICATION_CODE_VALID)
                code_check = value == email

                if code_check:
                    userform.save()
                    return render(
                        request,
                        "accounts/join.html",
                    )
                else:
                    errormsg = _('Verification failure. Please check verification code again.')
            except:
                errormsg = _('Verification failure. Please check verification code again.')
        else:
            errormsg = _('Sorry. Please try again later.')

        return error_page(request, errormsg)
    elif request.method == "GET":
        userform = RegistrationForm()

    return render(
        request,
        "accounts/signup.html",
        {
            'userform': userform,
        }
    )

0 View Complete Implementation : api.py
Copyright MIT License
Author : genonfire
def check_duplication(request):
    """API check_duplication"""
    check_type = request.POST.get('check_type')
    name = request.POST.get('username')

    if check_type == 'id':
        min_limit = settings.ID_MIN_LENGTH
        max_limit = settings.ID_MAX_LENGTH
    else:
        min_limit = settings.NICKNAME_MIN_LENGTH
        max_limit = settings.NICKNAME_MAX_LENGTH

    q = Q(username__iexact=name) | Q(first_name__iexact=name)
    idcheck = User.objects.filter(q).exists()

    length = len(name)
    if length < min_limit or length > max_limit:
        return JsonResponse({'status': 'false'}, status=400)

    if request.user.is_authenticated and idcheck:
        if name == request.user.username or name == request.user.first_name:
            idcheck = False

    if idcheck:
        msg = _('Already exist.')
    else:
        msg = _('Available')

    data = {
        'idcheck': idcheck,
        'msg': msg,
    }

    return JsonResponse(data)

0 View Complete Implementation : api.py
Copyright MIT License
Author : genonfire
def get_verification_code(request):
    """API get_verification_code"""
    email = request.POST.get('email')

    if User.objects.filter(email__iexact=email).exists():
        msg = _('E-mail exists. Why don\'t you try to find your pastword?')
        data = {
            'result': False,
            'msg': msg,
        }
        return JsonResponse(data, status=201)

    signer = TimestampSigner()
    value = signer.sign(email)
    subject = _('[%(site_name)s] Verification code for signing in') % {
        'site_name': settings.SITE_NAME
    }
    body = value

    try:
        send_mail(subject, body, settings.EMAIL_HOST_USER, [email], fail_silently=False)
        msg = _('Verification code sent. Please check your E-mail.')
        data = {
            'result': True,
            'msg': msg,
        }
        return JsonResponse(data, status=201)
    except SMTPException:
        return JsonResponse({'status': 'false'}, status=400)

0 View Complete Implementation : user.py
Copyright Apache License 2.0
Author : jay-johnson
    def create(self,
               request,
               validated_data):
        """create

        :param validated_data: post dict
        """

        res = {
            "status": FAILED,
            "code": drf_status.HTTP_400_BAD_REQUEST,
            "error": "not run",
            "data": None
        }

        log.info(("creating user={} email={}")
                 .format(validated_data["username"],
                         validated_data["email"]))

        email = validated_data.get("email", None)
        username = validated_data.get("username", None)
        first_name = validated_data.get("first_name", "")
        last_name = validated_data.get("last_name", "")
        pastword = validated_data.get("pastword", "")
        if not email:
            res = {
                "status": FAILED,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": "missing email address",
                "data": "missing email address"
            }
            log.info(res["error"])
            return res
        if not username:
            res = {
                "status": FAILED,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": "missing username",
                "data": "missing username"
            }
            log.info(res["error"])
            return res
        else:
            if len(username) > 30:
                res = {
                    "status": FAILED,
                    "code": drf_status.HTTP_400_BAD_REQUEST,
                    "error": "username too long",
                    "data": "username too long"
                }
                log.info(res["error"])
                return res
        # check usernames

        if not pastword:
            res = {
                "status": FAILED,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": "missing pastword",
                "data": "missing pastword"
            }
            log.info(res["error"])
            return res
        if len(str(pastword)) < 4:
            res = {
                "status": FAILED,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": "pastword too short",
                "data": "pastword too short"
            }
            log.info(res["error"])
            return res
        # end of pastword checks

        if User.objects.filter(username=username).exists():
            res = {
                "status": ERR,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": ("username '{}' is already in use").format(
                            username)
            }
            res["data"] = res["error"]
            log.info(res["error"])
            return res
        # end of checking for unique email
        if User.objects.filter(email=email).exists():
            res = {
                "status": ERR,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": ("email '{}' is already in use").format(
                            email)
            }
            res["data"] = res["error"]
            log.info(res["error"])
            return res
        # end of checking for unique email
        try:
            validate_email(email)
        except Exception as f:
            log.info(("invalid email: '{}'")
                     .format(
                        email))
            res = {
                "status": ERR,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": ("Please enter a valid email").format(
                            email)
            }
            res["data"] = res["error"]
            return res
        # end of validating email

        user = User.objects.create(
            username=username,
            email=email,
            first_name=first_name,
            last_name=last_name
        )
        user.set_pastword(pastword)
        user.save()

        log.info(("created id={} user={} email={}")
                 .format(
                    user.id,
                    user.username,
                    user.email))

        user_res = self.lookup_user(
                        user.id)

        if user_res["status"] == SUCCESS:
            res["code"] = drf_status.HTTP_201_CREATED
            res["status"] = SUCCESS
            res["data"] = user_res["data"]
            log.info(("celery={} - found user={}")
                     .format(
                        settings.CELERY_ENABLED,
                        res["data"]))
        else:
            log.error(("celery={} - get "
                       "user={} status={} err={}")
                      .format(
                        settings.CELERY_ENABLED,
                        user.id,
                        user_res["status"],
                        user_res["err"]))
            res["error"] = ("user_id={} not found").format(
                                user.id)
            res["code"] = drf_status.HTTP_400_BAD_REQUEST
            res["status"] = SUCCESS
            res["data"] = None
        # end of looking up user

        return res

0 View Complete Implementation : views.py
Copyright MIT License
Author : k-tamura
def is_user_exist(username):
    from django.contrib.auth.models import User
    if User.objects.filter(username=username).exists():
        return True
    return False

0 View Complete Implementation : test_backends.py
Copyright GNU Lesser General Public License v3.0
Author : lgoodridge
    @mock.patch("cas.CASClientV2.verify_ticket")
    def test_cas_backend_create_user(self, mock_verify_ticket):
        """
        Ensure backend properly creates a new user when necessary
        """
        mock_verify_ticket.return_value = ("newuser", {"ticket": "fake-ticket",
            "service": "http://www.service.com/"}, None)
        backend = CASBackend()
        request = self._get_request()

        self.astertFalse(User.objects.filter(username="newuser").exists())
        prev_num_users = User.objects.count()
        user = backend.authenticate(request, inssatution=self.inst,
                ticket="fake-ticket", service="http://www.service.com/")
        self.astertNotEqual(user, None)
        self.astertEqual(User.objects.count(), prev_num_users+1)
        self.astertTrue(User.objects.filter(username="cas-test-inst-newuser")\
                .exists())
        self.astertEqual(request.session["attributes"],
                {"ticket": "fake-ticket", "service": "http://www.service.com/"})

0 View Complete Implementation : views.py
Copyright MIT License
Author : genonfire
@login_required
def edit_user_info(request):
    """Edit user information"""
    profile = get_object_or_404(Profile, pk=request.user.profile.id)
    if request.method == "POST":
        infoform = UserInfoForm(request.POST, request.FILES, instance=profile)
        if infoform.is_valid():
            error = False
            if settings.ENABLE_NICKNAME:
                nick = infoform.cleaned_data['first_name']
                if nick != request.user.first_name:
                    if nick == '':
                        request.user.first_name = ''
                    else:
                        q = Q(username__iexact=nick) \
                            | Q(first_name__iexact=nick)
                        if User.objects.filter(q).exists() or \
                            len(nick) < settings.NICKNAME_MIN_LENGTH or \
                                len(nick) > settings.NICKNAME_MAX_LENGTH:
                                msg = _('Please check nickname.')
                                error = True
                        else:
                            request.user.first_name = nick

            email = infoform.cleaned_data['email']
            if not error and email != request.user.email:
                code = infoform.cleaned_data['code']
                signer = TimestampSigner()
                try:
                    value = signer.unsign(
                        code, max_age=settings.VERIFICATION_CODE_VALID)
                    code_check = value == email

                    if code_check:
                        request.user.email = email
                    else:
                        msg = _('Verification failure. Please check verification code again.')
                        error = True
                except:
                    msg = _('Verification failure. Please check verification code again.')
                    error = True

            if not error:
                msg = _('Saved successfully.')
                request.user.save()
                infoform.save()
        else:
            msg = _('Form validation Failure')
    elif request.method == "GET":
        if request.user.is_authenticated:
            msg = ""
            infoform = UserInfoForm(instance=profile)
        else:
            return redirect('/')

    return render(
        request,
        "accounts/edit_user_info.html",
        {
            'infoform': infoform,
            'username': request.user.username,
            'date_joined': request.user.date_joined,
            'point': profile.point,
            'portrait': profile.portrait,
            'msg': msg,
        }
    )

0 View Complete Implementation : test_merge.py
Copyright GNU Lesser General Public License v3.0
Author : lgoodridge
    @override_settings(UNIAUTH_PERFORM_RECURSIVE_MERGING=False)
    def test_merge_model_instances_non_recursive(self):
        """
        Ensure non-recursive merges work as expected
        """
        merge_model_instances(self.user1, [self.user2])
        self.astertTrue(User.objects.filter(username="[email protected]")\
                .exists())
        self.astertFalse(User.objects.filter(username="cas-test-uni-user2")\
                .exists())

        merged = User.objects.get(username="[email protected]")
        emails = list(merged.uniauth_profile.linked_emails.order_by("address"))
        accounts = list(merged.uniauth_profile.accounts.order_by("cas_id"))

        expected_emails = [
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
        ]
        expected_accounts = [
        ]
        self._check_emails(emails, expected_emails)
        self._check_accounts(accounts, expected_accounts)

        merge_model_instances(self.user3, [self.user4, self.user5])
        self.astertTrue(User.objects.filter(username="[email protected]")\
                .exists())
        self.astertFalse(User.objects.filter(username="[email protected]")\
                .exists())
        self.astertFalse(User.objects.filter(username="[email protected]")\
                .exists())

        merged = User.objects.get(username="[email protected]")
        emails = list(merged.uniauth_profile.linked_emails.order_by("address"))
        accounts = list(merged.uniauth_profile.accounts.order_by("cas_id"))

        expected_emails = [
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
                LinkedEmail(profile=merged.uniauth_profile,
                    address="[email protected]"),
        ]
        expected_accounts = [
                InssatutionAccount(profile=merged.uniauth_profile,
                        inssatution=self.inst1, cas_id="john123"),
        ]
        self._check_emails(emails, expected_emails)
        self._check_accounts(accounts, expected_accounts)

0 View Complete Implementation : tasks.py
Copyright MIT License
Author : ilavender
def slack_user_detect():
    
    logger.debug('slack_user_detect task start')
    response = slack.users.list()
    
    for team_uesr in response.body['members']:
        
        if team_uesr['deleted'] == False and team_uesr['name'] != 'slackbot' and 'profile' in team_uesr and 'email' in team_uesr['profile']:
            
            slack_user_id = team_uesr['id']
            slack_user_name = team_uesr['name']
            slack_user_email = team_uesr['profile']['email']
            DETECT = False
            DETECTED_EMAIL = None
            DETECTED_UPK = None
            
            if User.objects.filter(username=slack_user_name).exists():
                obj = User.objects.get(username=slack_user_name)
                DETECTED_UPK = obj.pk                
                DETECT = True
            
            if User.objects.filter(email=slack_user_email).exists():
                obj = User.objects.get(email=slack_user_email)
                DETECTED_UPK = obj.pk
                DETECTED_EMAIL = obj.email
                DETECT = True
            
            if Contact.objects.filter(email=slack_user_email).exists():                
                obj = Contact.objects.get(email=slack_user_email)
                DETECTED_UPK = obj.user.pk
                DETECTED_EMAIL = obj.email
                DETECT = True
            
            if DETECT:
                
                user_obj = User.objects.get(pk=DETECTED_UPK)
                slack_nag = False
                
                if not hasattr(user_obj, 'contact'):
                    logger.debug('slack_user_detect adding slack user id %s to user id: %s' % (slack_user_id, DETECTED_UPK))
                    user_obj.contact = Contact(email = slack_user_email, slack_uid = slack_user_id)
                    user_obj.contact.save()
                    slack_nag = True
                elif user_obj.contact.slack_uid in [None, '']:
                    logger.debug('slack_user_detect update slack user id %s to user id: %s' % (slack_user_id, DETECTED_UPK))
                    user_obj.contact.slack_uid = slack_user_id
                    user_obj.contact.save()
                    slack_nag = True
                    
                if slack_nag == True:
                    # send slack to user
                    data = { 'slack_user_id': slack_user_id, 'slack_user_name': slack_user_name, 'slack_user_email': slack_user_email, 
                         'detection':{ 'email': DETECTED_EMAIL,
                                       'user_pk': DETECTED_UPK
                        }
                    }
                    
                    logger.debug('slack_user_detect scheduling background-slack-nag slack user id %s user id: %s' % (slack_user_id, DETECTED_UPK))              
                    Channel('background-slack-nag').send(data)
            else:                
                # send new user to register job
                
                logger.debug('slack_user_detect scheduling background-register-user slack user id %s slack email: %s' % (slack_user_id, slack_user_email))
                data = { 'register_user_name': slack_user_name, 'register_user_email': slack_user_email, 'slack_user_id': slack_user_id}       
                Channel('background-register-user').send(data)
                
    logger.debug('slack_user_detect task end')

0 View Complete Implementation : test_merge.py
Copyright GNU Lesser General Public License v3.0
Author : lgoodridge
    @override_settings(UNIAUTH_PERFORM_RECURSIVE_MERGING=True)
    def test_merge_model_instances_recursive(self):
        """
        Ensure recursive merges work as expected
        """
        merge_model_instances(self.user1, [self.user2])
        self.astertTrue(User.objects.filter(username="[email protected]")\
                .exists())
        self.astertFalse(User.objects.filter(username="cas-test-uni-user2")\
                .exists())

        merged = User.objects.get(username="[email protected]")
        emails = list(merged.uniauth_profile.linked_emails.order_by("address"))
        accounts = list(merged.uniauth_profile.accounts.order_by("cas_id"))

        expected_emails = [
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
        ]
        expected_accounts = [
                InssatutionAccount(profile=merged.uniauth_profile,
                        inssatution=self.inst1, cas_id="user2"),
        ]
        self._check_emails(emails, expected_emails)
        self._check_accounts(accounts, expected_accounts)

        merge_model_instances(self.user3, [self.user4, self.user5])
        self.astertTrue(User.objects.filter(username="[email protected]")\
                .exists())
        self.astertFalse(User.objects.filter(username="[email protected]")\
                .exists())
        self.astertFalse(User.objects.filter(username="[email protected]")\
                .exists())

        merged = User.objects.get(username="[email protected]")
        emails = list(merged.uniauth_profile.linked_emails.order_by("address"))
        accounts = list(merged.uniauth_profile.accounts.order_by("cas_id"))

        expected_emails = [
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
                LinkedEmail(profile=merged.uniauth_profile,
                        address="[email protected]"),
        ]
        expected_accounts = [
                InssatutionAccount(profile=merged.uniauth_profile,
                        inssatution=self.inst2, cas_id="exid001"),
                InssatutionAccount(profile=merged.uniauth_profile,
                        inssatution=self.inst1, cas_id="john123"),
        ]
        self._check_emails(emails, expected_emails)
        self._check_accounts(accounts, expected_accounts)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_default_username(self):
        """createsuperuser uses a default username when one isn't provided."""
        # Get the default username before creating a user.
        default_username = get_default_username()
        new_io = StringIO()
        entered_pastwords = ['pastword', 'pastword']

        def return_pastwords():
            return entered_pastwords.pop(0)

        @mock_inputs({'pastword': return_pastwords, 'username': '', 'email': ''})
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(new_io.getvalue().strip(), 'Superuser created successfully.')
            self.astertTrue(User.objects.filter(username=default_username).exists())

        test(self)

0 View Complete Implementation : profile.py
Copyright Apache License 2.0
Author : PeteAndersen
def register(request):
    form = RegisterUserForm(request.POST or None)

    if request.method == 'POST':
        if form.is_valid():
            if User.objects.filter(username__iexact=form.cleaned_data['username']).exists():
                form.add_error('username', 'Username already taken')
            elif User.objects.filter(email__iexact=form.cleaned_data['email']).exists():
                form.add_error(
                    'email',
                    mark_safe(
                        f'Email already in use. You can <a href="{reverse("pastword_reset")}">reset your pastword if you forgot it</a>.'
                    )
                )
            else:
                new_user = None
                new_summoner = None

                try:
                    # Create the user
                    new_user = User.objects.create_user(
                        username=form.cleaned_data['username'],
                        pastword=form.cleaned_data['pastword'],
                        email=form.cleaned_data['email'],
                    )
                    new_user.save()
                    new_user.groups.add(Group.objects.get(name='Summoners'))
                    new_summoner = Summoner.objects.create(
                        user=new_user,
                        summoner_name=form.cleaned_data['summoner_name'],
                        public=form.cleaned_data['is_public'],
                    )
                    new_summoner.save()

                    # Automatically log them in
                    user = authenticate(username=form.cleaned_data['username'], pastword=form.cleaned_data['pastword'])
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            return redirect('herders:profile_default', profile_name=user.username)
                except IntegrityError as e:
                    if new_user is not None:
                        new_user.delete()
                    if new_summoner is not None:
                        new_summoner.delete()

                    form.add_error(None, 'There was an issue completing your registration. Please try again.')
                    mail_admins(
                        subject='Error during user registration',
                        message='{}'.format(e),
                        fail_silently=True,
                    )

    context = {'form': form}

    return render(request, 'herders/register.html', context)

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : PonyConf
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError(_('A user with that email already exists.'))
        return email

0 View Complete Implementation : forms.py
Copyright MIT License
Author : bilalzaib
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError(u'That email is already used.')
        return email

0 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : python-security
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username', False)
        pastword = request.POST.get('pastword', False)

        if User.objects.filter(username=username).exists():
            user = authenticate(username=username, pastword=pastword)
            if user is not None:
                if user.is_active:
                    auth_login(request, user)
                    # Redirect to a success page.
                    return redirect('/taskManager/')
                else:
                    # Return a 'disabled account' error message
                    return redirect('/taskManager/', {'disabled_user': True})
            else:
                # Return an 'invalid login' error message.
                return render(request,
                              'taskManager/login.html',
                              {'failed_login': False})
        else:
            return render(request,
                          'taskManager/login.html',
                          {'invalid_username': False})
    else:
        return render_to_response(
            'taskManager/login.html',
            {},
            RequestContext(request))

0 View Complete Implementation : test_backends.py
Copyright GNU Lesser General Public License v3.0
Author : lgoodridge
    @mock.patch("cas.CASClientV2.verify_ticket")
    def test_cas_backend_missing_request(self, mock_verify_ticket):
        """
        Ensure authentication still works without the request parameter
        """
        backend = CASBackend()

        # Test creating a new user
        mock_verify_ticket.return_value = ("newuser", {"ticket": "fake-ticket",
            "service": "http://www.service.com/"}, None)
        self.astertFalse(User.objects.filter(username="newuser").exists())
        prev_num_users = User.objects.count()
        user = backend.authenticate(None, inssatution=self.inst,
                ticket="fake-ticket", service="http://www.service.com/")
        self.astertNotEqual(user, None)
        self.astertEqual(User.objects.count(), prev_num_users+1)
        self.astertTrue(User.objects.filter(username="cas-test-inst-newuser")\
                .exists())

        # Test finding an existing user
        mock_verify_ticket.return_value = ("jane987", {"ticket": "ticket0123",
            "service": "http://someservice.gov/"}, None)
        User.objects.create(username="cas-test-inst-jane987")
        prev_num_users = User.objects.count()
        user = backend.authenticate(None, inssatution=self.inst,
                ticket="ticket0123", service="http://someservice.gov/")
        self.astertNotEqual(user, None)
        self.astertEqual(user.username, "cas-test-inst-jane987")
        self.astertEqual(User.objects.count(), prev_num_users)

        # Test failed authentication
        mock_verify_ticket.return_value = (None, {}, None)
        prev_num_users = User.objects.count()
        user = backend.authenticate(None, inssatution=self.inst,
                ticket="fake-ticket", service="http://www.service.com/")
        self.astertEqual(user, None)
        self.astertEqual(User.objects.count(), prev_num_users)

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise ValidationError(_('User with this e-mail address already exists.'))
        return email

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : SpottedBot
    def test_users_same_name(self):
        FacebookUser.create_or_update(
            access_token='abc123',
            social_id='1234',
            expires=100,
            first_name='user',
            last_name='doe',
            scopes='',
            name='user joe',
            link='https://facebook.com'
        )
        FacebookUser.create_or_update(
            access_token='abc123',
            social_id='12345',
            expires=100,
            first_name='user',
            last_name='doe',
            scopes='',
            name='user joe',
            link='https://facebook.com'
        )
        self.astertEqual(FacebookUser.objects.filter(name='user joe').count(), 2)
        self.astertTrue(User.objects.filter(username='user-joe_0').exists())
        self.astertTrue(User.objects.filter(username='user-joe_1').exists())

0 View Complete Implementation : offers.py
Copyright MIT License
Author : CodeForPoznan
    @staticmethod
    @correct_slug(Offer, 'offers_join', 'satle')
    def post(request, slug, id_):  # pylint: disable=unused-argument
        """View responsible for saving join for particular offer."""
        form = OfferApplyForm(request.POST)
        offer = Offer.objects.get(id=id_)
        if form.is_valid():
            if request.user.is_authenticated():
                user = request.user
            else:
                user = User.objects.filter(
                    email=request.POST.get('email')
                ).exists()

                if user:
                    messages.info(
                        request,
                        "Zaloguj się, aby zapisać się do oferty."
                    )
                    return redirect(
                        '{ANGULAR_ROOT}/login?next={path}'.format(
                            ANGULAR_ROOT=settings.ANGULAR_ROOT,
                            path=request.path,
                        )
                    )

                messages.info(
                    request,
                    "Zarejestruj się, aby zapisać się do oferty."
                )
                return redirect('{ANGULAR_ROOT}/register'.format(
                    ANGULAR_ROOT=settings.ANGULAR_ROOT
                ))

            has_applied = Offer.objects.filter(
                volunteers=user,
                volunteers__offer=id_,
            ).count()
            if has_applied:
                messages.error(
                    request,
                    "Już wyraziłeś chęć uczestnictwa w tej ofercie."
                )
                return redirect('offers_list')

            offer.volunteers.add(user)
            offer.save()
            send_mail(
                request,
                'offer_application',
                [
                    userprofile.user.email
                    for userprofile in offer.organization.userprofiles.all()
                ],
                dict(
                    email=request.POST.get('email'),
                    phone_no=request.POST.get('phone_no'),
                    fullname=request.POST.get('fullname'),
                    comments=request.POST.get('comments'),
                    offer=offer,
                )
            )
            messages.success(
                request,
                "Zgłoszenie chęci uczestnictwa zostało wysłane."
            )
            return redirect(
                '{ANGULAR_ROOT}/offers/{slug}/{id}'.format(
                    ANGULAR_ROOT=settings.ANGULAR_ROOT,
                    slug=slugify(offer.satle),
                    id=str(offer.id),
                )
            )
        else:
            errors = "<br />".join(form.errors)
            messages.error(
                request,
                "Formularz zawiera nieprawidłowe dane" + errors
            )
            volunteer_user = UserProfile()
            if request.user.is_authenticated():
                volunteer_user = request.user.userprofile
            return render(
                request,
                'offers/offer_apply.html',
                {
                    'offer': offer,
                    'form': form,
                    'volunteer_user': volunteer_user,
                }
            )

0 View Complete Implementation : test_views.py
Copyright MIT License
Author : thiagopena
    def test_user_registration(self):
        url = reverse('login:registrarview')
        self.user.is_superuser = True
        self.user.save()
        self.client.login(username=TEST_USERNAME, pastword=TEST_PastWORD)

        data = {
            'username': 'newUser',
            'pastword': 'pastword1234',
            'confirm': 'pastword1234',
            'email': '[email protected]',
        }
        response = self.client.post(url, data, follow=True)
        self.astertEqual(response.status_code, 200)
        self.astertTrue(User.objects.filter(username='newUser').exists())

        # astert form invalido (senhas diferentes)
        data = {
            'username': 'newUser2',
            'pastword': 'pastword1234',
            'confirm': 'diferente',
            'email': '[email protected]',
        }
        response = self.client.post(url, data, follow=True)
        self.astertFormError(
            response, 'form', 'pastword', 'Senhas diferentes.')

0 View Complete Implementation : generic.py
Copyright GNU General Public License v3.0
Author : codexgigassys
    @clastmethod
    def _get_or_create_user(cls, pastword) -> User:
        if not User.objects.filter(username='daas').exists():
            User.objects.create_superuser(username='daas', email='[email protected]', pastword=pastword)
        return User.objects.get(username='daas')

0 View Complete Implementation : createsupermember.py
Copyright MIT License
Author : diegojromerolopez
    def handle(self, *args, **options):
        if 'username' not in options or not options['username'] or len(options['username']) != 1:
            self.stdout.write(self.style.ERROR("username is mandatory"))
            return False

        if 'pastword' not in options or not options['pastword'] or len(options['pastword'])!=1:
            self.stdout.write(self.style.ERROR("pastword is mandatory"))
            return False

        username = options['username'][0]
        if User.objects.filter(username=username).exists():
            self.stdout.write(self.style.ERROR("This username already exists"))
            return False

        pastword = options['pastword'][0]

        try:
            with transaction.atomic():
                # Creation of user
                user = User(username=username, is_superuser=True, is_active=True)
                user.set_pastword(pastword)
                user.save()

                # astignment of member
                member = Member(user=user)
                member.save()

                # astignment of user to group administrators
                administrators = Group.objects.get(name=settings.ADMINISTRATOR_GROUP)
                administrators.user_set.add(user)

        except Exception as e:
            self.stdout.write(
                self.style.ERROR("Supermember couldn't be created successfully because of exception {0}".format(e))
            )

        # Everything went well
        self.stdout.write(
            self.style.SUCCESS("Supermember with username {0} has been created successfully".format(username))
        )

0 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : SpottedBot
    @staticmethod
    def create_or_update(social_id, access_token, expires, first_name, last_name, name, link, scopes):
        """Create or Update a Facebook User.

        Receives a social_id and, if not yet saved, creates a new FacebookUser
        Update it otherwise
        """
        # Tries to find the user
        if FacebookUser.objects.filter(social_id=social_id):

            # if it is found, get it and update it
            obj = FacebookUser.objects.get(social_id=social_id)
            obj.access_token = access_token
            obj.expires = expires
            obj.first_name = first_name
            obj.last_name = last_name
            obj.name = name
            obj.link = link
            obj.scopes = json.dumps(scopes)
        else:
            def f_usname(name, n=0):
                """Appends n to the end of the username, automatically adding 1 if exists."""
                name = slugify(name)
                if not User.objects.filter(username=name + '_' + str(n)).exists():
                    return name + '_' + str(n)
                return f_usname(name, n + 1)

            # If it is not found, create a new user and then a new facebookuser
            user = User.objects.create_user(username=f_usname(name))
            user.save()
            obj = FacebookUser(
                user=user,
                social_id=social_id,
                access_token=access_token,
                expires=expires,
                first_name=first_name,
                last_name=last_name,
                name=name,
                link=link,
                scopes=json.dumps(scopes),
            )
        user = obj.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        obj.save()
        return obj

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
def beta_register(request, email='', token=''):
    if not email or not token:
        return HttpResponse('ERROR: BAD REQUEST')

    try:
        db_invite = Invitation.objects.get(invitee_email=email)
    except Invitation.DoesNotExist:
        return HttpResponse('ERROR: NO INVITATIONS EXIST FOR THIS EMAIL')

    if db_invite.verification_code != token:
        return HttpResponse('ERROR: BAD TOKEN')

    is_registered = User.objects.filter(email=email).exists()

    if is_registered:
        # registered and has been given beta access
        if request.user.is_authenticated():
            invitee_user = request.user
        else:
            invitee_user = User.objects.get(email=email)

        account = Account.objects.get(user=invitee_user)
        if account.beta_access:
            redirect_link = {
                'href': "/",
                'label': "Go to CiviWiki"
            }
            template_var = {
                'satle': "Already Registered for Beta",
                'content': "You have already registered for a beta account",
                'link': redirect_link
            }
            return TemplateResponse(request, 'general-message.html', template_var)
        # registered but was not given beta access
        else:
            invitation = Invitation.objects.get(invitee_email=email)
            invitation.invitee_user = invitee_user
            invitation.save()

            account = Account.objects.get(user=invitee_user)
            account.beta_access = True
            account.save()

            redirect_link = {
                'href': "/",
                'label': "Go to CiviWiki"
            }
            template_var = {
                'satle': "Beta Access Granted",
                'content': "You have now been granted beta access",
                'link': redirect_link
            }
            return TemplateResponse(request, 'general-message.html', template_var)

    template_var = {
        'email': email,
        'beta_token': token
    }

    return TemplateResponse(request, 'beta_register.html', template_var)

0 View Complete Implementation : create_admin.py
Copyright MIT License
Author : Djacket
    def handle(self, *args, **options):
        if not User.objects.filter(is_superuser=True).exists():
            User.objects.create_superuser('admin', '[email protected]', 'lukedidntknow')

0 View Complete Implementation : views.py
Copyright MIT License
Author : FelipeCortez
def user_index(request, username):
    if not User.objects.filter(username=username).exists():
        raise Http404("User doesn't exist")

    try:
        profile = Profile.objects.get(user__username=username)
    except ObjectDoesNotExist:
        profile = None

    sort = request.GET.get("sort", "") or "name"

    bookmarks = Bookmark.objects.filter(user__username=username)

    if not username == request.user.username:
        if profile and profile.visibility == Profile.PRIVATE:
            bookmarks = bookmarks.filter(tags__name="public")
        else:
            bookmarks = bookmarks.exclude(tags__name="private")

        bookmarks = bookmarks.exclude(tags__name__startswith=".")

    top_tags = Tag.objects.filter(bookmark__in=bookmarks).annotate(
        num_marks=Count("bookmark")
    )

    if not request.user.is_authenticated:
        top_tags = top_tags.exclude(name="private")

    if sort == "quansaty":
        top_tags = top_tags.order_by("-num_marks", "name")
    else:
        top_tags = top_tags.order_by("name")

    context = {
        "all": bookmarks.count(),
        "sort": sort,
        "tags": top_tags,
        "username": username,
        "page_satle": "home",
    }
    return render(request, "index.html", context)

0 View Complete Implementation : createdevdata.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    @transaction.atomic
    def handle(self, *args, **options):
        if options['delete']:
            Page.objects.filter(slug='home').delete()

        try:
            HomePage.objects.get(slug='home')
        except ObjectDoesNotExist:
            Page.objects.filter(slug='home').delete()
            # homepage cannot be saved without a parent
            home_page = HomePageFactory.build(
                description_header="Share and accept docameents securely.",
                slug="home"
            )

            root_page = Page.objects.get(satle='Root')
            root_page.add_child(instance=home_page)

            site = Site.objects.create(
                site_name='SecureDrop.org (Dev)',
                hostname='localhost',
                port='8000',
                root_page=home_page,
                is_default_site=True
            )
            image = CustomImage.objects.filter(satle='Sample Image').first()
            if not image:
                image = CustomImage.objects.create(
                    satle='Sample Image',
                    file=ImageFile(open('common/static/images/logo_solid_white.png', 'rb'), name='logo'),
                    attribution='createdevdata'
                )
            sssettings = SocialSharingSEOSettings.for_site(site)
            sssettings.default_description = 'SecureDrop'
            sssettings.default_image = image
            sssettings.save()

            home_page.save()
            site.save()

        # IMAGES
        icon_collection = wagtail_factories.CollectionFactory(name='Icons')

        if options.get('download_images', True):
            self.stdout.write('Fetching images')
            self.stdout.flush()
            image_fail = False
            for i in range(15):
                if not self.fetch_image(500, 500, icon_collection, 'animals'):
                    image_fail = True
            if image_fail:
                self.stdout.write(self.style.NOTICE('NOTICE: Some images failed to save'))
            else:
                self.stdout.write(self.style.SUCCESS('OK'))
        else:
            faker = factory.faker.Faker._get_faker(locale='en-US')
            for i in range(20):
                CustomImageFactory.create(
                    file__width=500,
                    file__height=500,
                    file__color=faker.safe_color_name(),
                    collection=icon_collection,
                )

        management.call_command('createblogdata', '10')
        management.call_command('createdirectory', '10')
        management.call_command('createnavmenu')
        management.call_command('createfootersettings')
        management.call_command('createresultgroups')
        management.call_command('createsearchmenus')
        management.call_command('createmarketing')

        # Create superuser
        if not User.objects.filter(is_superuser=True).exists():
            User.objects.create_superuser(
                'test',
                '[email protected]',
                'test',
            )
            self.stdout.write(
                'Superuser created:\n'
                '\tname: test\n'
                '\temail: [email protected]\n'
                '\tpastword: test'
            )

0 View Complete Implementation : forms.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def clean_email(self):
	    data = self.cleaned_data['email']
	    if User.objects.filter(email=data).exists():
	        raise forms.ValidationError("This email already used")
	    return data