Exemplo n.º 1
0
    def _add_user(self, userdata):
        email = userdata['Email']
        username = userdata['Username']

        user_exists = User.objects.filter(
            models.Q(email=email)
            | models.Q(username=username))

        email_exists = EmailAddress.objects.filter(email=email)

        if user_exists or email_exists:
            print('Skipping user {} <{}>'.format(username, email))
        else:
            user = User(
                username=username,
                email=email,
                date_joined=userdata['Creation date'],
                password="******" + userdata['Password hash'],
            )
            user.save()
            email = EmailAddress(
                user=user,
                email=userdata['Email'],
                verified=True,
                primary=True,
            )
            email.save()
Exemplo n.º 2
0
def sync_user(user, userdata):
    """Overwrite user details with data from the remote auth server"""

    for k in ['email', 'first_name', 'last_name']:
        if getattr(user, k) != userdata[k]:
            setattr(user, k, userdata[k])

    user.save()

    try:
        from allauth.account.models import EmailAddress
    except ImportError:
        return

    # Sync email address list
    for e in user.emailaddress_set.all():
        if e.email not in userdata['email_addresses']:
            e.delete()

    for e in userdata['email_addresses']:
        if user.emailaddress_set.filter(email=e).exists():
            continue
        emailaddress = EmailAddress(email=e)
        emailaddress.save()
        user.emailaddress_set.add(emailaddress)
Exemplo n.º 3
0
def add_new_emails(sender, request, response, user, **kwargs):
    if "sociallogin" not in kwargs:
        return

    if not getattr(kwargs["sociallogin"], "autoconnect", False):
        return

    for e in kwargs["sociallogin"].email_addresses:
        try:
            existing = EmailAddress.objects.get(email__iexact=e.email.lower())
        except EmailAddress.DoesNotExist:
            new = EmailAddress(email=e.email,
                               verified=e.verified,
                               primary=False,
                               user=user)
            new.save()
            continue

        if existing.user != user:
            # TODO: what if this email is verified but the existing
            # email is unverified? Can this user steal it?
            continue
        elif e.verified and not existing.verified:
            existing.verified = True
            existing.save()
Exemplo n.º 4
0
 def verify_user(self):
     """Verify instance user account using django-allauth constructs"""
     account_emailaddresse = EmailAddress()
     account_emailaddresse.email = '*****@*****.**'
     account_emailaddresse.verified = True
     account_emailaddresse.user_id = self.user.id
     account_emailaddresse.save()
Exemplo n.º 5
0
    def handle(self, *args, **options):
        passwd = getpass.getpass("Enter password:"******"User with such email/username already exists.")

        u = user_model.objects.create_superuser(options['name'],
                                                options['email'], passwd)

        u.save()

        email_entity = EmailAddress(email=options['email'],
                                    verified=True,
                                    primary=True,
                                    user=u)
        email_entity.save()

        email_confirmation_entity = EmailConfirmation(
            email_address=email_entity,
            created=timezone.now() - datetime.timedelta(days=1),
            sent=timezone.now() - datetime.timedelta(hours=12),
            key=str(uuid.uuid4()).replace('-', ''))

        email_confirmation_entity.save()

        self.stdout.write(
            'Successfully created superuser {0} with confirmed email address {1}'
            .format(options['name'], options['email']))
Exemplo n.º 6
0
def update_profile(request):
    profile = request.user.profile

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            profile = form.save()
            user = request.user
            if user.email is None or user.email == '':
                if form.cleaned_data['email'].strip() != '':
                    user.email = form.cleaned_data['email']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.save()
            print "email: " + str(user.email)
            print str(user.email.strip()) != ''
            if user.email is not None and str(user.email.strip()) != '':
                try:
                    email_address = EmailAddress.objects.get(user=user)
                    email_address.email = user.email
                except EmailAddress.DoesNotExist:
                    email_address = EmailAddress(user=user, email=user.email, primary=True)
                email_address.save()
            return redirect(profile.get_absolute_url())
    else:
        form = UserProfileForm(instance=profile)

    return render(request, 'profile/edit.html', {
        'user': request.user,
        'form': form,
    })
Exemplo n.º 7
0
    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.add_account')

        # verify email unique
        query_set = get_user_model().objects.filter(email=input['email'])

        #Don't insert duplicate records in the DB. If this records exist, fetch and return it
        if query_set.exists():
            raise Exception(
                _('An account is already registered with this e-mail address'))

        account = get_user_model()(first_name=input['first_name'],
                                   last_name=input['last_name'],
                                   email=input['email'],
                                   username=input['email'])
        account.save()

        # Insert Allauth email address
        email_address = EmailAddress(user=account,
                                     email=account.email,
                                     verified=True,
                                     primary=True)
        email_address.save()

        # Insert Teacher profile
        account_teacher_profile = AccountTeacherProfile(account=account)
        account_teacher_profile.save()

        return CreateAccount(account=account)
Exemplo n.º 8
0
 def verify_user(self):
     """Verify instance user account using django-allauth constructs"""
     account_emailaddresse = EmailAddress()
     account_emailaddresse.email = '*****@*****.**'
     account_emailaddresse.verified = True
     account_emailaddresse.user_id = self.user.id
     account_emailaddresse.save()
Exemplo n.º 9
0
    def handle(self, *args, **options):
        # attempt to load username from command-line options
        # username can come from command-line flag OR from interactive input
        self._username = options.get(self.UserModel.USERNAME_FIELD)

        try:
            with transaction.atomic():
                # let the base class handle all the user-creation details
                super().handle(*args, **options)
                # now try to create the validated EmailAddress object
                user = self.UserModel.objects.get(username=self._username)
                # overriding the value of is_superuser set by parent (always True in parent)
                user.is_superuser = options[ADMIN]
                # create a verified primary EmailAddress for the user
                email_address = EmailAddress(user=user,
                                             email=user.email,
                                             verified=True,
                                             primary=True)
                email_address.save()
                user.save()
                if options["verbosity"] >= 1:
                    self.stdout.write(
                        'Simulated email address verification for user "%s"' %
                        self._username)
        except Exception as e:
            raise CommandError(e)
Exemplo n.º 10
0
 def _add_fake_data_to_courses(self, num):
     # create a pool of instructors
     instructor_data = [
         {'first_name': 'first', 'last_name': 'user', 'username': '******', 'email': '*****@*****.**'},
         {'first_name': 'second', 'last_name': 'user', 'username': '******', 'email': '*****@*****.**'},
         {'first_name': 'third', 'last_name': 'user', 'username': '******', 'email': '*****@*****.**'},
         {'first_name': 'fourth', 'last_name': 'user', 'username': '******', 'email': '*****@*****.**'},
         {'first_name': 'fifth', 'last_name': 'user', 'username': '******', 'email': '*****@*****.**'},
     ]
     instructors = []
     for instructor_datum in instructor_data:
         user = User.objects.create_user(instructor_datum['username'], email=instructor_datum['email'], password="******")
         email_address = EmailAddress(user=user, email=instructor_datum['email'], verified=True, primary=True)
         user.first_name = instructor_datum['first_name']
         user.last_name = instructor_datum['last_name']
         user.save()
         email_address.save()
         instructors.append(user)
         
     for idx in xrange(num):
         course = Course(
             instructor=instructors[idx % len(instructor_data)], 
             title='sample title ' + str(idx),
             slug='sample-title-' + str(idx),
             description=('sample description ' + str(idx) + '\t') * 25,
             is_public = True if idx % 2 == 0 else False,
             popularity=0
         )
         course.save()
         self._generate_course_pages(course)
Exemplo n.º 11
0
    def post(self, request, pk=None):
        if not pk:
            return redirect(reverse("dashboard"))

        client = Usuario.objects.get(pk=pk)

        form = ExtraInfoForm(request.POST, instance=client)
        if form.is_valid():
            
            state = State.objects.get_or_create(uf=request.POST.get('state'), cod_ibge=request.POST.get('cod_ibge'))[0]
            city = City.objects.get_or_create(name=request.POST.get('city'), latitude=request.POST.get('latitude'),longitude=request.POST.get('longitude'), state=state, cod_ibge=state.cod_ibge)[0]
            neighborhood = Neighborhood.objects.get_or_create(description=request.POST.get('neighborhood'), city=city)[0]
            place = Place.objects.get_or_create(zip_code=request.POST.get('zip_code'), city=city, latitude=city.latitude, longitude=city.longitude, neighborhood=neighborhood)[0]
            
            address = Address()
            address.street = request.POST.get('street')
            address.number = request.POST.get('number')
            address.complement = request.POST.get('complement')
            address.reference_point = request.POST.get('reference_point')
            address.place = place
            address.neighborhood = neighborhood
            address.city = city
            address.state = state
            address.latitude = city.latitude
            address.longitude = city.longitude
            address.save()

            # UPDATING CLIENT
            client = form.save(commit=False)
            client.address = address
            client.save()

            # ACTIVATING USER
            user = client.user
            user.is_active = True
            user.save()

            # ALLAUTH EMAIL
            try:
                auth_email = EmailAddress.objects.get(user=client.user, email=client.email)
            except:
                auth_email = EmailAddress()
                
            auth_email.user = client.user
            auth_email.email = client.email
            auth_email.save()

            # SENDING EMAIL CONFIRMATION
            auth_email.send_confirmation()

            response = {
                'status': 'success', 
                'message':'Usuário criado com sucesso', 
                'redirect':reverse("account_login")
            }

            return JsonResponse(response, status=200)

        return JsonResponse({'status': 'form_error', 'message':'Favor preencher todos os campos'}, status=400)
Exemplo n.º 12
0
def email(save=False, **kwargs):
    if 'user' not in kwargs:
        kwargs['user'] = user(save=True)
    if 'email' not in kwargs:
        kwargs['email'] = '%s@%s.com' % (random_str(), random_str())
    email = EmailAddress(**kwargs)
    if save:
        email.save()
    return email
Exemplo n.º 13
0
def email(save=False, **kwargs):
    if 'user' not in kwargs:
        kwargs['user'] = user(save=True)
    if 'email' not in kwargs:
        kwargs['email'] = '%s@%s.com' % (random_str(), random_str())
    email = EmailAddress(**kwargs)
    if save:
        email.save()
    return email
Exemplo n.º 14
0
def email(save=False, **kwargs):
    if "user" not in kwargs:
        kwargs["user"] = user(save=True)
    if "email" not in kwargs:
        kwargs["email"] = "%s@%s.com" % (get_random_string(), get_random_string())
    email = EmailAddress(**kwargs)
    if save:
        email.save()
    return email
Exemplo n.º 15
0
def create_token_signal(sender, instance=None, created=False, **kwargs):
    if created:
        if instance.is_superuser:
            email = EmailAddress(user=instance,
                                 verified=True,
                                 email=instance.email,
                                 primary=True)
            email.save()

        Token.objects.create(user=instance)
Exemplo n.º 16
0
def email(save=False, **kwargs):
    if 'user' not in kwargs:
        kwargs['user'] = user(save=True)
    if 'email' not in kwargs:
        kwargs['email'] = '{0!s}@{1!s}.com'.format(get_random_string(),
                                                   get_random_string())
    email = EmailAddress(**kwargs)
    if save:
        email.save()
    return email
Exemplo n.º 17
0
    def _on_populate_user(sender, user=None, ldap_user=None, **_kwargs):
        if user._state.adding:
            user.save()
        try:
            email = EmailAddress.objects.get(user=user, email=user.email)
            email.verified = True
        except ObjectDoesNotExist:
            email = EmailAddress(user=user, email=user.email, verified=True)

        if not EmailAddress.objects.filter(user=user, primary=True).exists():
            email.primary = True

        email.save()
Exemplo n.º 18
0
 def test_valid_form(self):
     email = EmailAddress(user=self.user, email=self.user.email,
                          verified=True, primary=True)
     email.save()
     form = {
         'login': self.user.email,
         'password': '******',
     }
     response = self.client.post(
         reverse('account_login'),
         form, follow=True
     )
     self.assertRedirects(response, reverse('dashboard'))
Exemplo n.º 19
0
    def _save_email_addresses(self, request):
        adapter = get_adapter()
        # user.email may not be listed as an EmailAddress ...
        user = self.account.user
        try:
            primary_email_address = EmailAddress.objects.get(user=user,
                                                             primary=True)
        except EmailAddress.DoesNotExist:
            primary_email_address = None

        if (user.email
                and (user.email.lower()
                     not in [e.email.lower() for e in self.email_addresses])):
            # ... so let's append it
            email_address \
                = EmailAddress(user=user,
                               email=user.email,
                               verified=adapter.is_email_verified(request,
                                                                  user.email),
                               primary=(not primary_email_address))
            if not primary_email_address:
                primary_email_address = email_address
            self.email_addresses.append(email_address)

        for email_address in self.email_addresses:
            # Pick up only valid ones...
            email = valid_email_or_none(email_address.email)
            if not email:
                continue
            # ... and non-conflicting ones...
            if (account_settings.UNIQUE_EMAIL and
                    EmailAddress.objects.filter(email__iexact=email).exists()):
                continue
            if email_address.primary:
                if not primary_email_address:
                    primary_email_address = email_address
                else:
                    email_address.primary = False
            email_address.user = user
            email_address.verified \
                = (email_address.verified
                   or adapter.is_email_verified(request,
                                                email_address.email))
            email_address.save()

        if primary_email_address and (
                not user.email
                or primary_email_address.email.lower() != user.email.lower()):
            user.email = primary_email_address.email
            user.save()
        adapter.stash_email_verified(request, None)
Exemplo n.º 20
0
    def test_unsubscribe(self, client, user):
        email = EmailAddress(user=user, email=user.email)
        email.save()

        user.settings["email"] = {"marketing": True}
        user.save()

        payload = {**PAYLOAD, "data[email]": user.email}
        response = client.post("/mailchimp/webhook/?key=123", data=payload)

        user.refresh_from_db()

        assert not user.settings["email"]["marketing"]
        assert response.status_code == 200
Exemplo n.º 21
0
def create_user_email(sender, instance, **kwargs):
    if instance.is_manager:

        email_address_object = EmailAddress.objects.filter(
            user=instance).first()
        if email_address_object:
            email_address_object.email = instance.email
        else:
            email_address_object = EmailAddress(user=instance,
                                                email=instance.email,
                                                verified=True,
                                                primary=True)

        email_address_object.save()
Exemplo n.º 22
0
 def save(self):
     email = self.cleaned_data["email"]
     user = User(username=self.cleaned_data["username"],
                 is_ff=True,
                 email=email)
     password = self.cleaned_data["password1"]
     user.set_password(password)
     user.save()
     email_obj = EmailAddress(user=user,
                              email=email,
                              verified=True,
                              primary=True)
     email_obj.save()
     return user
Exemplo n.º 23
0
    def _save_email_addresses(self, request):
        adapter = get_adapter()
        # user.email may not be listed as an EmailAddress ...
        user = self.account.user
        try:
            primary_email_address = EmailAddress.objects.get(user=user,
                                                             primary=True)
        except EmailAddress.DoesNotExist:
            primary_email_address = None


        if (user.email 
            and (user.email.lower() not in [e.email.lower() 
                                            for e in self.email_addresses])):
            # ... so let's append it
            email_address \
                = EmailAddress(user=user,
                               email=user.email,
                               verified=adapter.is_email_verified(request, 
                                                                  user.email),
                               primary=(not primary_email_address))
            if not primary_email_address:
                primary_email_address = email_address
            self.email_addresses.append(email_address)

        for email_address in self.email_addresses:
            # Pick up only valid ones...
            email = valid_email_or_none(email_address.email)
            if not email:
                continue
            # ... and non-conflicting ones...
            if (account_settings.UNIQUE_EMAIL 
                and EmailAddress.objects.filter(email__iexact=email).exists()):
                continue
            if email_address.primary:
                if not primary_email_address:
                    primary_email_address = email_address
                else:
                    email_address.primary = False
            email_address.user = user
            email_address.verified \
                = (email_address.verified 
                   or adapter.is_email_verified(request, 
                                                email_address.email))
            email_address.save()

        if primary_email_address and (not user.email or primary_email_address.email.lower() != user.email.lower()):
            user.email = primary_email_address.email
            user.save()
        adapter.stash_email_verified(request, None)
Exemplo n.º 24
0
 def _create_user(self, user_form, full_name):
     password = user_form.cleaned_data['password1']
     fm_email = user_form.cleaned_data['email']
     user = user_form.save()
     user.first_name = full_name
     user.set_password(password)
     user.username = fm_email.replace("@", "").replace(".", "")
     user.save()
     email = EmailAddress(user=user,
                          email=user.email,
                          verified=True,
                          primary=True)
     email.save()
     return user
Exemplo n.º 25
0
 def test_form_with_valid_username(self):
     # Should error as we only accept email addresses now
     email = EmailAddress(user=self.user, email=self.user.email,
                          verified=True, primary=True)
     email.save()
     form = {
         'login': self.user.username,
         'password': '******',
     }
     response = self.client.post(
         reverse('account_login'), form, follow=True
     )
     self.assertEqual(response.status_code, 200)
     self.assertIn('Enter a valid email address', response.content)
Exemplo n.º 26
0
 def form_valid(self, form):
     user = form.save(commit=False)
     fm_email = form.cleaned_data['email']
     user.username = fm_email.replace("@", "").replace(".", "")
     user.save()
     email = EmailAddress(user=user,
                          email=user.email,
                          verified=True,
                          primary=True)
     email.save()
     employee = Employees(user=user, administrator=True)
     employee.save()
     company = Company.objects.get(slug=self.kwargs.get('company_slug'))
     company.user.add(employee)
     company.save()
     return super(AddAdministratorView, self).form_valid(form)
Exemplo n.º 27
0
 def save_model(self, request, obj, form, change):
     data = dict(email=obj.email)
     user = User.objects.filter(email=data['email'])
     if user.exists() is False:
         obj.save()
         serializer = CustomUserCreateSerializer(data=data)
         serializer.is_valid(raise_exception=True)
         serializer.save()
         email_address = EmailAddress()
         email_address.user = user[0]
         email_address.verified = True
         email_address.primary = True
         email_address.email = data['email']
         email_address.save()
     else:
         obj.save()
Exemplo n.º 28
0
 def create_superuser(self, username, password, **extra_fields):
     email = '*****@*****.**'
     user = self.create_user(username, password=password, email=email, **extra_fields)
     user.is_admin = True
     user.is_active = True
     user.is_verified = True
     user.set_password(password)
     user.save(using=self._db)
     # Now add this user's email address to EmailAddress table
     # Otherwise, user won't be able to login.
     email_address = EmailAddress()
     email_address.user = user
     email_address.verified = True
     email_address.primary = True
     email_address.email = email
     email_address.save()
     return user
Exemplo n.º 29
0
def post_user_signed_up_checkinvitation(request, user, *args, **kwargs):
    Invitation = get_invitation_model()
    try:
        invite = Invitation.objects.get(email=user.email)
    except:
        logger.info("User is not an invited user. Register as admin")
        """
        is_admin is true
        is_organisation_default is true
        userorganization is blank
        """
    else:
        """
        is_admin is true
        is_organisation_default is true
        userorganization is blank
        """
        try:
            inviter_user = User.objects.get(pk=invite.inviter_id)
        except:
            logger.critical(
                "Error setting up invited user - Inviter user not found")
        else:
            user.userorganization = inviter_user.userorganization
            user.is_admin = False
            user.is_team_member = True
            user.is_organisation_default = False
            try:
                user.save()
            except:
                logger.critical("Error updating invited users")
            else:
                try:
                    emailAddress = EmailAddress.objects.get(email=user.email)
                except:
                    emailAddress = EmailAddress()
                    emailAddress.user = user.pk
                    emailAddress.email = user.email
                    emailAddress.verified = True
                    emailAddress.primary = True
                    try:
                        emailAddress.save()
                    except:
                        logger.critical("Error setting up verified email")
                else:
                    logger.info("Invited users - email already verified.")
Exemplo n.º 30
0
def new_user(email, username=''):
    User = get_user_model()
    if username:
        assert is_username_unique(username)
    else:
        basename = email.split('@')[0]
        username = make_unique_username(basename)
    if User.objects.filter(email=email):
        raise ValueError('Email "{}" not unique.'.format(email))
    user = User(username=username, email=email)
    user.save()

    # Set up email for allauth.
    ea = EmailAddress(user=user, email=email, primary=True, verified=False)
    ea.user = user
    ea.save()

    return user
Exemplo n.º 31
0
    def create_superuser(self, email, password, **extra_fields):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
            **extra_fields,
        )
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)

        new_allauth_email = EmailAddress()
        new_allauth_email.user = user
        new_allauth_email.email = email
        new_allauth_email.verified = True
        new_allauth_email.primary = True
        new_allauth_email.save()

        return user
Exemplo n.º 32
0
    def test_expired_email_verify_link(self):
        verified_count = EmailAddress.objects.filter(verified=True).count()

        # create a user
        user = self.create_user('username', '*****@*****.**', 'password')

        # create an unverified email address
        email = EmailAddress(user=user, email=user.email,
                             verified=False, primary=True)
        email.save()

        # create and email confirmation object
        confirmation = self._create_confirmation(
            email, datetime.now(tz) - timedelta(days=10)
        )

        response = self.client.post(reverse('account_confirm_email',
                                            args=(confirmation.key,)))
        self.assertEqual(response.status_code, 404)
        new_verified_count = EmailAddress.objects.filter(verified=True).count()
        self.assertEqual(verified_count, new_verified_count)
Exemplo n.º 33
0
    def post(self, request):
        context = {}
        serializer = serializers.RegisterSerializer(data=request.data)
        message = {}
        if serializer.is_valid():
            if Usuario.objects.filter(email=serializer.data['email']).exists():
                message = {'status': 'error', 'message': 'Email já cadastrado.'}
                return Response(message,status=500)
            else:
                try:
                    user = Usuario.objects.create_user(serializer.data['email'], serializer.data['password'])
                    user.nome = serializer.data['nome_completo']
                    user.nomecomleto = serializer.data['nome_completo']
                    user.is_active = True
                    user.token = binascii.b2a_hex(os.urandom(15))
                    user.save()
                except Exception as e:
                    user.delete()
                    message = {'status': 'error', 'message': str(e)}
                    return Response(message,status=500)
                
                try:
                    email_address = EmailAddress()
                    email_address.verified = False
                    email_address.user = user
                    email_address.email = user.email
                    email_address.save()

                except Exception as e:
                    user.delete()
                    email_address.delete()
                    message = {'status': 'error', 'message': str(e)}
                    return Response(message,status=500)
                    
            message = {'status':'success'}
            return Response(message,status=200)
        else:

            message = {'status':'error'}
            return Response(message,status=400)
    def handle(self, *args, **options):
        passwd = getpass.getpass("Enter password:"******"User with such email/username already exists.")

        u = user_model.objects.create_superuser(
            options['name'], options['email'], passwd
        )

        u.save()

        email_entity = EmailAddress(
            email=options['email'], verified=True,
            primary=True, user=u
        )
        email_entity.save()

        email_confirmation_entity = EmailConfirmation(
            email_address=email_entity,
            created=timezone.now() - datetime.timedelta(days=1),
            sent=timezone.now() - datetime.timedelta(hours=12),
            key=str(uuid.uuid4()).replace('-', '')
        )

        email_confirmation_entity.save()

        self.stdout.write(
            'Successfully created superuser {0} with confirmed email address {1}'.format(
                options['name'], options['email']
            )
        )
Exemplo n.º 35
0
    def obj_create(self, bundle, request=None, **kwargs):
        password = bundle.data['password']
        email = bundle.data['email']

        try:
            username = email
            bundle.obj = User.objects.create_user(username, email, password)

            email_address = EmailAddress(user=bundle.obj,
                                         email=email,
                                         verified=True,
                                         primary=True)
            email_address.save()

            #print "Success"
            #student = Student(user = bundle.obj)
            #print student
            #student.save()

            #try:
            #	student.gpa = bundle.data['gpa']
            #	student.save()
            #except ValueError:
            #	pass

            #try:
            #	student.zip_code = bundle.data['zip_code']
            #	student.save()
            #except ValueError:
            #	pass

            #bundle.obj = User(username = username, email = email, password = password)
            #bundle.obj.save()
        except IntegrityError:
            raise BadRequest('That username already exists')

        return bundle
Exemplo n.º 36
0
	def obj_create(self, bundle, request = None, **kwargs):
		password = bundle.data['password']
		email = bundle.data['email']

		try:
			username = email
			bundle.obj = User.objects.create_user(username, email, password)

			email_address = EmailAddress(user = bundle.obj, email = email, verified = True, primary = True)
			email_address.save()


			#print "Success"
			#student = Student(user = bundle.obj)
			#print student 
			#student.save()

			#try:
			#	student.gpa = bundle.data['gpa']
			#	student.save()
			#except ValueError:
			#	pass

			#try:
			#	student.zip_code = bundle.data['zip_code']
			#	student.save()
			#except ValueError:
			#	pass

			#bundle.obj = User(username = username, email = email, password = password)
			#bundle.obj.save()
		except IntegrityError:
			raise BadRequest('That username already exists')
		

		return bundle 
Exemplo n.º 37
0
def add_users_to_semester(request, pk=None):
    sem_users = UserSemester.objects.filter(semester_id=pk)
    if request.method == 'POST':
        form = AddUsersToSemesterForm(request.POST, request.FILES)
        if form.is_valid():
            semester_obj = Semester.objects.get(id=int(pk))

            file_handle = request.FILES['file']
            user_list_record = file_handle.get_records()
            user_titles_array = file_handle.get_array()[0]

            mandatory_titles = settings.STUDENTS_MANDATORY_FIELDS
            message = 'your Excel file does not have these titles:'
            excel_titles = []
            for key, value in mandatory_titles.items():
                if value not in user_titles_array:
                    message = message + (' ' + value + ',')
                    excel_titles.append(value)

            if len(excel_titles) == 0:
                user_creation_error = ''
                user_add_sem_error = ''
                sem_user_added = [
                ]  # list of users that already existed and were added to semester
                sem_user_created = [
                ]  # list of newly created users and added to semester
                already_existing_users = []

                for student in user_list_record:
                    prepared_dict = {
                        'student_no': student[mandatory_titles['student_no']],
                        'email': student[mandatory_titles['email']],
                        'first_name': student[mandatory_titles['first_name']],
                        'last_name': student[mandatory_titles['last_name']],
                        'username': student[mandatory_titles['username']],
                        'password': User.objects.make_random_password()
                    }

                    empty_valued_titles, filled_value_titles = divide_empty_and_full_dic_values(
                        prepared_dict)

                    if len(empty_valued_titles) > 0:
                        messages.error(
                            request,
                            ('The record with title \"{0}\" and'
                             ' value \"{1}\" has an empty value '
                             'for one or more mandatary field/fields').format(
                                 filled_value_titles[0][0],
                                 filled_value_titles[0][1]))
                        continue
                    elif not validate_email(
                            student[mandatory_titles['email']]):
                        messages.error(request, (
                            'System could not save the '
                            'record with email \"{0}\" because the email address does not have'
                            'a valid format').format(
                                student[mandatory_titles['email']]))
                        continue

                    error_message = '\"{0}({1})\", '.format(
                        prepared_dict['email'], prepared_dict['student_no'])
                    try:
                        obj = User.objects.get(
                            student_no=prepared_dict['student_no'],
                            email=prepared_dict['email'],
                            username=prepared_dict['username'])
                        semester_user_obj, created = UserSemester.objects.get_or_create(
                            user=obj, semester=semester_obj)
                        if created:
                            sem_user_added.append(semester_user_obj)
                        else:
                            already_existing_users.append(semester_user_obj)
                    except User.DoesNotExist:
                        try:
                            obj = User.objects.create(
                                first_name=prepared_dict['first_name'],
                                last_name=prepared_dict['last_name'],
                                student_no=prepared_dict['student_no'],
                                email=prepared_dict['email'],
                                username=prepared_dict['username'],
                                password=prepared_dict['password'])

                            new_email = EmailAddress(
                                user=obj,
                                email=prepared_dict['email'],
                                verified=True,
                                primary=True)
                            new_email.save()

                        except IntegrityError:
                            user_creation_error += error_message

                        except Error:
                            user_creation_error += error_message

                        else:
                            try:
                                reset_pass_form = ResetPasswordForm({
                                    'email':
                                    prepared_dict['email'],
                                    'name':
                                    'Asghar'
                                })
                                if reset_pass_form.is_valid():
                                    reset_pass_form.save(request)

                                semester_user_obj = UserSemester.objects.create(
                                    user=obj, semester=semester_obj)
                                sem_user_created.append(semester_user_obj)
                            except IntegrityError:
                                user_add_sem_error += error_message

                            except Error:
                                user_add_sem_error += error_message

                create_specific_messages(request, user_creation_error,
                                         user_add_sem_error, sem_user_created,
                                         already_existing_users,
                                         user_list_record, semester_obj,
                                         sem_user_added)
            else:
                messages.error(request, message)

            new_form = AddUsersToSemesterForm()
            semester = Semester.objects.get(pk=pk)
            return render(request, 'management/upload_users.html', {
                'form': new_form,
                'semester': semester,
                'users': sem_users
            })

    else:
        semester = Semester.objects.get(pk=pk)
        form = AddUsersToSemesterForm()
    return render(request, 'management/upload_users.html', {
        'form': form,
        'semester': semester,
        'users': sem_users
    })
Exemplo n.º 38
0
    def post(self, request):
        type = request.data.get('type')
        if type is None:
            return Response(
                {
                    "success": False,
                    "message":
                    "type param describing email or phone is missing."
                },
                status=400)
        if type == 'email':
            data = {
                "username": request.data.get("username"),
                "email": request.data.get("email"),
                "password": request.data.get("password")
            }
            user = SignupWithEmailSerializer(data=data)

        elif type == 'phone':
            data = {
                "username": request.data.get("username"),
                "phone_number": request.data.get("phone_number"),
                "password": request.data.get("password")
            }
            user = SignUpWithPhoneSerializer(data=data)
        else:
            return Response(
                {
                    "success": False,
                    "message": "Invalid type param provided."
                },
                status=400)
        if user.is_valid():
            if type == 'phone':
                instance = User(username=data.get('username'),
                                phone_number=data.get('phone_number'))
            elif type == 'email':
                instance = User(username=data.get('username'),
                                email=data.get('email'))
            instance.set_password(data.get('password'))
            instance.save()
            if type == 'email':
                emails = EmailAddress(user=instance,
                                      email=instance.email,
                                      primary=True)
                emails.save()
            token = TokenModel.objects.create(user_id=instance.id)
            code = VerificationCodeGenerator.random_with_N_digits(5)
            code_for_user = VerificationCode(user=instance, code=code)
            response = SendVerificationCode.send_code(code, type, instance)
            error = None
            if response.get('success'):
                message = "Verification Code Sent"
            else:
                message = "Unable to send verification Code"
                error = response.get('message')
            code_for_user.save()
            return Response({
                "success": True,
                "message": message,
                "error": error
            })
        return Response({"success": False, "message": user.errors}, status=400)
Exemplo n.º 39
0
 def save(self, commit=True):
     user = super().save(commit)
     user_email = EmailAddress(user=user, email=self.cleaned_data['email'])
     user_email.send_confirmation()
     user_email.save()
     return user
Exemplo n.º 40
0
import os
import sys

#SCRIPT TO CREATE PROFILES, AFTER CREATING USERS
#FOR CREATING USERS UNCOMMENT THE CODE COMMENTRD AND VICEVERSA

os.environ['DJANGO_SETTINGS_MODULE'] = 'pichrr.settings'

import django
from django.contrib.auth.models import User
from allauth.account.models import EmailAddress


if __name__ == '__main__':
    django.setup()

usernames = ['theHulk', 'tonyStark', 'capt_America', 'Thor', 'blackWidow', 'hawkEye', 'loki', 'deadPool']
passwords = ['theHulk', 'tonyStark', 'capt_America', 'Thor', 'blackWidow', 'hawkEye', 'loki', 'deadPool']

for i in range(len(usernames)):
    email = usernames[i]+'@gmail.com'
    user = User.objects.create_user(username = usernames[i], password = passwords[i], email = email)
    user.save()
    email_address = EmailAddress(user=user,email=email, verified=True, primary=True)
    email_address.save()
Exemplo n.º 41
0
with open('members.csv') as csvfile:
    member_csv = csv.reader(csvfile)
    for row in member_csv:
        if row[5] == "*****@*****.**":
            user = User.objects.get(email='*****@*****.**')
        else:
            user = User()
            user.email = row[5]
            user.save()

        email = EmailAddress()
        email.user = user
        email.email = row[5]
        email.verified = True
        email.save()

        address = Address()
        address.user = user
        address.street = row[8]
        address.unit = row[9]
        address.city = row[10]
        address.state = row[11]
        address.postal_code = row[12]
        address.phone_number = row[13]
        address.save()

        member = Member()
        member.user = user
        member.first_name = row[6]
        member.last_name = row[7]
Exemplo n.º 42
0
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from allauth.account.models import EmailAddress

site = Site.objects.get(id=1)
site.domain = os.getenv('SITE_DOMAIN')
site.name = os.getenv('SITE_NAME')
site.save()

uname = os.getenv("SITE_ADMIN_NAME")
if not User.objects.filter(username=uname).exists():
    email_addr = os.getenv("SITE_ADMIN_EMAIL")
    passwd = os.getenv("SITE_ADMIN_PASSWORD")
    user = User.objects.create_superuser(uname, email_addr, passwd)
    av = EmailAddress(user=user, email=email_addr, verified=True)
    av.save()
    print("Super user `{name}` created.".format(name=uname))

uname = os.getenv("PROJ_ADMIN_NAME")
if not User.objects.filter(username=uname).exists():
    email_addr = os.getenv("PROJ_ADMIN_EMAIL")
    passwd = os.getenv("PROJ_ADMIN_PASSWORD")
    projAdmin = User.objects.create_user(uname, email=email_addr, password=passwd)
    projAdmin.is_staff=True
    projAdmin.save()
    av = EmailAddress(user=projAdmin, email=email_addr, verified=True)
    av.save()
    print("projects upload user `{name}` created.".format(name=uname))

if not User.objects.filter(username='******').exists():
    User.objects.create_user('guest', password=str(random()))