Ejemplo n.º 1
0
def password_reset(request):
    post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done')
    if request.method == "POST":
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            opts = {
                'use_https': request.is_secure(),
                'token_generator': default_token_generator,
                'from_email': None,
                'email_template_name': 'mail/password_reset_body.html',
                'subject_template_name': 'mail/password_reset_subject.txt',
                'request': request,
            }
            form.save(**opts)
            return JsonResponse({'status': True, 'redirect': post_reset_redirect})
        else:
            status = False
    else:
        form = PasswordResetForm()
        status = True
    context = {
        'form': form,
    }
    if request.is_ajax():
        return JsonResponse({'status': status, 'template': render_to_string(
            'account/password_reset/reset_form.html', context, context_instance=RequestContext(request))})
    return TemplateResponse(request, 'account/password_reset/reset_container.html', context)
Ejemplo n.º 2
0
def password_reset(request):
    """Password reset form.

    Based on django.contrib.auth.views. This view sends the email.

    """
    if request.method == "POST":
        form = PasswordResetForm(request.POST)
        was_valid = form.is_valid()
        if was_valid:
            try_send_email_with_form(
                form.save, form, 'email',
                use_https=request.is_secure(),
                token_generator=default_token_generator,
                email_template_name='users/email/pw_reset.ltxt')
        # Form may now be invalid if email failed to send.
        # PasswordResetForm is invalid iff there is no user with the entered
        # email address.
        # The condition below ensures we don't leak existence of email address
        # _unless_ sending an email fails.
        if form.is_valid() or not was_valid:
            # Don't leak existence of email addresses.
            return HttpResponseRedirect(reverse('users.pw_reset_sent'))
    else:
        form = PasswordResetForm()

    return jingo.render(request, 'users/pw_reset_form.html', {'form': form})
Ejemplo n.º 3
0
def forget_password(request,*args,**kwargs):
    if request.method == "POST":
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            user=form.get_users(form.cleaned_data['email'])
            if user is not None:
                user.reset_password_code=make_password(user.username,'reset_password',hasher='pbkdf2_sha256')
                subject='password reset'
                message='please open the link below to activate your account\n'\
                        +SITE_URL+'people/'+user.username+'/reset_password_code/'+tokens
                user.email_user(subject,message,EMAIL_SENDER)
                user.save()
                return redirect('/people/reset_password_done/')
            else:
                username=None
                context={'title':'activation','message':'your account has been activated or activation code is out of date'}
                redirect('/people/%s/' %username,context)
            # return HttpResponseRedirect(post_reset_redirect)
    else:
        form = PasswordResetForm()
    context = {
        'form': form,
        'title':'Password reset',
    }

    return render(request, 'people/reset_password.html',context)
Ejemplo n.º 4
0
    def handle_noargs(self, **options):
        # user = User.objects.get(pk=1)
        group = Group.objects.get(pk=2)
        # group.students.add(user)
        for student in sys.stdin:
            fields = student.strip().split(' ')
            email = fields[0]
            # print email, len(fields)
            if len(fields) > 3:
                continue

            username = email.split('@')[0]
            last_name = fields[1]
            first_name = fields[2]
            print email, username, last_name, first_name

            user, created = User.objects.get_or_create(username=username, first_name=first_name, last_name=last_name,
                                                       email=email)

            group.students.add(user)
            reset_form = PasswordResetForm({'email': email})
            print reset_form
            reset_form.save()

        group.save()
Ejemplo n.º 5
0
def request_password_change(email, orig_host, is_secure):
    """Email a single-use link for performing a password reset.

    Users must confirm the password change before we update their information.

    Args:
        email (string): An email address
        orig_host (string): An originating host, extracted from a request with get_host
        is_secure (Boolean): Whether the request was made with HTTPS

    Returns:
        None

    Raises:
        AccountUserNotFound
        AccountRequestError

    """
    # Binding data to a form requires that the data be passed as a dictionary
    # to the Form class constructor.
    form = PasswordResetForm({'email': email})

    # Validate that an active user exists with the given email address.
    if form.is_valid():
        # Generate a single-use link for performing a password reset
        # and email it to the user.
        form.save(
            from_email=settings.DEFAULT_FROM_EMAIL,
            domain_override=orig_host,
            use_https=is_secure
        )
    else:
        # No active user with the provided email address exists.
        raise AccountUserNotFound
Ejemplo n.º 6
0
def send_user_password_reset_email(user, request, new_user):
    """
    Send a password reset email to the user.  The http request object is
    also required in order to figure out the URL to include in the email.

    :param user: CtsUser
    :param request: HttpRequest
    :param new_user: Whether user is new
    """
    # Code copied and adapted from django.contrib.auth.views.password_reset().
    form_data = {
        'email': user.email,
    }
    reset_form = PasswordResetForm(form_data)
    if reset_form.is_valid():
        opts = {
            'use_https': request.is_secure(),
            'token_generator': PasswordResetTokenGenerator(),
            'from_email': None,
            'request': request,
        }
        if new_user:
            opts['email_template_name'] = 'accounts/new_account_email.html'
            opts['subject_template_name'] = 'accounts/new_account_subject.txt'
        else:
            opts['email_template_name'] = 'accounts/password_reset_email.html'
            opts['subject_template_name'] = 'accounts/password_reset_subject.txt'
        reset_form.save(**opts)
Ejemplo n.º 7
0
 def test_nonexistant_email(self):
     # Test nonexistant email address. This should not fail because it would
     # expose information about registered users.
     data = {'email': '*****@*****.**'}
     form = PasswordResetForm(data)
     self.assertTrue(form.is_valid())
     self.assertEqual(len(mail.outbox), 0)
Ejemplo n.º 8
0
 def testValidUser(self):
     data = {
         'email': '*****@*****.**',
     }
     form = PasswordResetForm(data)
     self.assertEqual(form.is_valid(), False)
     self.assertEqual(form["email"].errors, [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"])
Ejemplo n.º 9
0
def password_reset(request, template):
    """Password reset form.

    Based on django.contrib.auth.views. This view sends the email.

    """
    if request.method == "POST":
        form = PasswordResetForm(request.POST)
        was_valid = form.is_valid()
        if was_valid:
            # TODO: Since we're using Jingo in a way that doesn't
            # override the Django template loader, the pw_reset.ltxt
            # email template must be a Django template and not a Jinja
            # template.
            #
            # After we switch all the rendering everywhere, we can
            # probably change this back. Until then, I'm pretty sure
            # this won't get translated.
            try_send_email_with_form(
                form.save, form, 'email',
                use_https=request.is_secure(),
                token_generator=default_token_generator,
                email_template_name='users/email/pw_reset.ltxt')
        # Form may now be invalid if email failed to send.
        # PasswordResetForm is invalid iff there is no user with the entered
        # email address.
        # The condition below ensures we don't leak existence of email address
        # _unless_ sending an email fails.
        if form.is_valid() or not was_valid:
            # Don't leak existence of email addresses.
            return HttpResponseRedirect(reverse('users.pw_reset_sent'))
    else:
        form = PasswordResetForm()

    return jingo.render(request, template, {'form': form})
Ejemplo n.º 10
0
def password_reset(request):
    """
    View for entering email of registered player to change password
    :param request:
    """
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse("index"))

    context = {}
    if request.method == "POST":
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            opts = {
                "use_https": request.is_secure(),
                "token_generator": default_token_generator,
                "from_email": settings.KASKA_EMAIL,
                "email_template_name": "players/email/email_template.html",
                "subject_template_name": "players/email/email_subject.txt",
                "request": request,
            }

            try:
                Player.objects.get(email__iexact=form.cleaned_data["email"])
            except Player.DoesNotExist:
                return HttpResponseRedirect(reverse("players:password_reset_no_email"))
            else:
                form.save(**opts)
                return HttpResponseRedirect(reverse("players:password_reset_check_email"))
    else:
        form = PasswordResetForm()

    context.update({"form": form})
    return render(request, "players/password_reset/password_reset.html", context)
Ejemplo n.º 11
0
    def user_password_reset(self, request, id, form_url=''):
        from django.contrib.auth.tokens import default_token_generator
        from django.contrib.auth.forms import PasswordResetForm
        
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.get_queryset(request), pk=id)
        post_reset_redirect = urlresolvers.reverse('admin:%s_%s_change' % (self.model._meta.app_label, self.model._meta.model_name), args=(id,))

        form = PasswordResetForm({'email': user.email})
        if form.is_valid():
            opts = {
                'use_https': request.is_secure(),
                'token_generator': default_token_generator,
                'from_email': None,
                'email_template_name': 'registration/password_reset_email.html',
                'subject_template_name': 'registration/password_reset_subject.txt',
                'request': request,
            }
            opts = dict(opts, domain_override=request.get_host())
            form.save(**opts)

            msg = ugettext('Password reset link sent.')
            messages.success(request, msg)
        else:
            msg = ugettext('Error ocurred while sending password reset link.')
            messages.error(request, msg)
        
        return HttpResponseRedirect(post_reset_redirect)
Ejemplo n.º 12
0
 def test_cleaned_data(self):
     # Regression test
     (user, username, email) = self.create_dummy_user()
     data = {"email": email}
     form = PasswordResetForm(data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data["email"], email)
Ejemplo n.º 13
0
 def post(self, request, format=None):
     serializer = self.serializer_class(data=request.DATA)
     if serializer.is_valid():
         # Create PasswordResetForm with the serializer
         password_reset_form = PasswordResetForm(data=serializer.data)
         
         if password_reset_form.is_valid():
             # Set some values to be used for the send_email method.
             opts = {
                 'use_https': request.is_secure(),
                 'request': request,
                 'subject_template_name': self.subject_template_name,
                 'email_template_name': self.email_template_name,
                 }
             password_reset_form.save(**opts)
             
             # Return the success message with OK HTTP status
             return Response(serializer.data)
         
         else:
             return Response(password_reset_form.errors, 
                             status=status.HTTP_400_BAD_REQUEST)
     
     # coming this far means there likely was a problem
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 14
0
    def handle(self, *args, **options):
        # We first retrieve all users
        accounts = Account.objects.all().filter(is_active=True)

        for account in accounts:
            password = Account.objects.make_random_password()
            account.set_password(password)
            account.save()

            opts = {
                'use_https': True,
                'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
                'request': None,
                'subject_template_name': 'email/authentication/welcome_subject.txt',
                'html_email_template_name': 'email/authentication/html_welcome.html',
                'email_template_name': 'email/authentication/welcome.html',
                'domain_override': getattr(settings, 'SITE_URL'),
                'extra_email_context': {
                    'site_url': getattr(settings, 'SITE_URL'),
                    'email': account.email,
                    'password': password
                }
            }
            reset_form = PasswordResetForm(dict(email=account.email))
            if not reset_form.is_valid():
                print reset_form.errors
                raise CommandError("Email not valid: " + account.email)

            reset_form.save(**opts)
Ejemplo n.º 15
0
 def test_nonexistant_email(self):
     # Test nonexistant email address
     data = {'email':'*****@*****.**'}
     form = PasswordResetForm(data)
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors,
                      {'email': [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"]})
Ejemplo n.º 16
0
 def test_cleaned_data(self):
     # Regression test
     user = User.objects.create_user("jsmith3", "*****@*****.**", "test123")
     data = {'email':'*****@*****.**'}
     form = PasswordResetForm(data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data['email'], u'*****@*****.**')
Ejemplo n.º 17
0
    def password_reset(self, request, queryset):
        count = 0
        for user in queryset:
            # Do the password reset stuff.
            form = PasswordResetForm({'email': user.email})

            if form.is_valid():
                opts = {
                    'use_https': request.is_secure(),
                    'token_generator': default_token_generator,
                    'from_email': 'OpenData Cincy<*****@*****.**>',
                    'email_template_name': 'registration/password_reset_email.html',
                    'subject_template_name': 'registration/password_reset_subject.txt',
                    'request': request,
                }

                opts = dict(opts, domain_override=request.get_host())
                form.save(**opts)

                count += 1

        if count == 1:
            message_bit = '1 user was'
        else:
            message_bit = '%s users were' % count

        self.message_user(request, '%s emailed password reset instructions' % message_bit)
 def test_save_html_email_template_name(self):
     """
     Test the PasswordResetFOrm.save() method with html_email_template_name
     parameter specified.
     Test to ensure that a multipart email is sent with both text/plain
     and text/html parts.
     """
     (user, username, email) = self.create_dummy_user()
     form = PasswordResetForm({"email": email})
     self.assertTrue(form.is_valid())
     form.save(html_email_template_name='registration/html_password_reset_email.html')
     self.assertEqual(len(mail.outbox), 1)
     self.assertEqual(len(mail.outbox[0].alternatives), 1)
     message = mail.outbox[0].message()
     self.assertEqual(message.get('subject'), 'Custom password reset on example.com')
     self.assertEqual(len(message.get_payload()), 2)
     self.assertTrue(message.is_multipart())
     self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
     self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
     self.assertEqual(message.get_all('to'), [email])
     self.assertTrue(re.match(r'^http://example.com/reset/[\w/-]+', message.get_payload(0).get_payload()))
     self.assertTrue(
         re.match(r'^<html><a href="http://example.com/reset/[\w/-]+/">Link</a></html>$',
         message.get_payload(1).get_payload())
     )
Ejemplo n.º 19
0
def add_profile(request):
    if request.method == 'POST':
        profile_formset = ProfileFormset(request.POST)
        if profile_formset.is_valid():
            user_added = False
            for form in profile_formset:
                if form.cleaned_data:
                    username = form.cleaned_data['username']
                    first_name = form.cleaned_data['first_name']
                    last_name = form.cleaned_data['last_name']
                    email = form.cleaned_data['email']
                    password = generate_random_id()
                    new_user = create_profile(username, email, password, first_name, last_name)
                    activate_profile(new_user.profile)
                    new_user.profile.send_welcome_email(request)
                    user_added = True
                    reset_form = PasswordResetForm({'email': email})
                    assert reset_form.is_valid()
                    reset_form.save(
                            request=request,
                            use_https=request.is_secure(),
                            email_template_name='profiles/reset_password.txt',
                            )
            if user_added:
                messages.success(request, _('The profiles have been created'))
            profile_formset = ProfileFormset()

        else:
            messages.warning(request, _('Please check the fields below for error'))
    else:
        profile_formset = ProfileFormset()
    return render(request, 'profiles/add_profile.html', {'profile_formset': profile_formset,})
Ejemplo n.º 20
0
 def save(self, domain_override=None,
          subject_template_name='registration/password_reset_subject.txt',
          email_template_name='registration/password_reset_email.html',
          use_https=False, token_generator=default_token_generator,
          from_email=None, request=None, html_email_template_name=None,
          extra_email_context=None):
     """
     Generates a one-use only link for resetting password and sends to the
     user.
     """
     email_or_username = self.cleaned_data["email_or_username"]
     for user in self.get_users(email_or_username):
         if not domain_override:
             current_site = get_current_site(request)
             site_name = current_site.name
             domain = current_site.domain
         else:
             site_name = domain = domain_override
         context = {
             'email': user.email,
             'domain': domain,
             'site_name': site_name,
             'uid': urlsafe_base64_encode(force_bytes(user.pk)),
             'user': user,
             'token': token_generator.make_token(user),
             'protocol': 'https' if use_https else 'http',
         }
         if extra_email_context is not None:
             context.update(extra_email_context)
         dj_auth_form = PasswordResetForm()
         dj_auth_form.send_mail(
             subject_template_name, email_template_name, context, from_email,
             user.email, html_email_template_name=html_email_template_name,
         )
Ejemplo n.º 21
0
def password_reset(request):
    ''' Attempts to send a password reset e-mail. '''
    if request.method != "POST":
        raise Http404

    # By default, Django doesn't allow Users with is_active = False to reset their passwords,
    # but this bites people who signed up a long time ago, never activated, and forgot their
    # password. So for their sake, we'll auto-activate a user for whom password_reset is called.
    try:
        user = User.objects.get(email=request.POST['email'])
        user.is_active = True
        user.save()
    except:
        log.exception("Tried to auto-activate user to enable password reset, but failed.")

    form = PasswordResetForm(request.POST)
    if form.is_valid():
        form.save(use_https=request.is_secure(),
                  from_email=settings.DEFAULT_FROM_EMAIL,
                  request=request,
                  domain_override=request.get_host())
        return HttpResponse(json.dumps({'success': True,
                                        'value': render_to_string('registration/password_reset_done.html', {})}))
    else:
        return HttpResponse(json.dumps({'success': False,
                                        'error': 'Invalid e-mail'}))
Ejemplo n.º 22
0
    def passwordReset(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        postData = simplejson.loads(request.raw_post_data)
        key = postData['token']

        user = getUserByKey(key)

        if user is not None:
            if user.is_active:
                data = {'email': user.email}
                resetForm = PasswordResetForm(data)
            
                if resetForm.is_valid():
                    resetForm.save()
            
                    return self.create_response(request,{'status':OK,
                        'message': 'check your email for instructions'})
                else:
                    return self.create_response(request, 
                            {'status': SYSTEM_ERROR,
                            'message': 'form not valid'})
            else:
                return self.create_response(request, {'status':FORBIDDEN,
                    'message':'Account disabled'})
        else:
            return self.create_response(request, {'status': UNAUTHORIZED,
                        'error': 'User does not exists'})
Ejemplo n.º 23
0
    def post(self, request):
        # Create a serializer with request.DATA
        serializer = self.serializer_class(data=request.DATA)
        result = {'errCode':10000,'errDesc':errMsg[10000]}

        if serializer.is_valid():
            # Create PasswordResetForm with the serializer
            reset_form = PasswordResetForm(data=serializer.data)

            if reset_form.is_valid():
                # Sett some values to trigger the send_email method.
                opts = {
                    'use_https': request.is_secure(),
                    'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
                    'request': request,
                }

                reset_form.save(**opts)

                # Return the success message with OK HTTP status
                return Response(result, status=status.HTTP_200_OK)

            else:
                logger.debug(reset_form._errors)

        logger.debug(serializer.errors)
        result['errCode']=10009
        result['errDesc']=errMsg[10009]
        return Response(result, status=status.HTTP_200_OK)
Ejemplo n.º 24
0
Archivo: forms.py Proyecto: LUMC/django
 def test_nonexistant_email(self):
     # Test nonexistant email address
     data = {'email': '*****@*****.**'}
     form = PasswordResetForm(data)
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors,
                      {'email': [force_text(form.error_messages['unknown'])]})
Ejemplo n.º 25
0
 def send_email(self, request):
     try:
         reset_form = PasswordResetForm({"email": self.cleaned_data["email"]})
         assert reset_form.is_valid()
         reset_form.save(
             request=request,
             from_email="*****@*****.**",
             use_https=request.is_secure(),
             subject_template_name="bdiadmin/account_creation_subject.txt",
             email_template_name="bdiadmin/account_creation_email.html",
         )
         messages.success(
             request,
             _("Profile created and mail sent to {0}.").format(
                 self.cleaned_data["email"]
             ),
         )
     except:
         messages.warning(
             request,
             _("Profil created, but unable to send mail to {0}.").format(
                 self.cleaned_data["email"]
             ),
         )
         pass
Ejemplo n.º 26
0
    def post(self, request):
        # Create a serializer with request.DATA
        serializer = self.serializer_class(data=request.DATA)

        if serializer.is_valid():
            # Create PasswordResetForm with the serializer
            reset_form = PasswordResetForm(data=serializer.data)

            if reset_form.is_valid():
                # Sett some values to trigger the send_email method.
                opts = {
                    'use_https': request.is_secure(),
                    'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
                    'request': request,
                }

                reset_form.save(**opts)

                # Return the success message with OK HTTP status
                return Response(
                    {"success": "Password reset e-mail has been sent."},
                    status=status.HTTP_200_OK)

            else:
                return Response(reset_form._errors,
                                status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 27
0
def send_password_reset(request, user_id):
    user = get_object_or_404(User, id=user_id)
    form = PasswordResetForm({"email": user.email})
    if form.is_valid():
        form.save(email_template_name="auto_password_reset_email.html")
        messages.success(request, "Password reset email sent.")

    return HttpResponseRedirect(reverse("participant_overview", args=(user.id,)))
Ejemplo n.º 28
0
 def test_inactive_user(self):
     # tests that inactive user cannot
     # receive password reset email
     (user, username, email) = self.create_dummy_user()
     user.is_active = False
     user.save()
     form = PasswordResetForm({"email": email})
     self.assertFalse(form.is_valid())
 def test_cleaned_data(self):
     (user, username, email) = self.create_dummy_user()
     data = {'email': email}
     form = PasswordResetForm(data)
     self.assertTrue(form.is_valid())
     form.save(domain_override='example.com')
     self.assertEqual(form.cleaned_data['email'], email)
     self.assertEqual(len(mail.outbox), 1)
Ejemplo n.º 30
0
    def form_valid(self, form):
        self.object, new_position = form.save(commit=False)
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        self.object.set_password(password)

        url = form.cleaned_data['picture']

        if url and not str(url).find('Default'):

            domain, path = utils.split_url(str(url))

            try:
                extension = utils.valid_url_extension(str.lower(path))
            except not extension:
                error = 'File was not a valid image (jpg, jpeg, png, gif)'
                form.non_field_errors(error)

            try:
                pil_image = Image.open(url)
            except utils.valid_image_size(pil_image):
                form.non_field_errors('Image is too large (> 4mb)')

            #  saving this for later
#            try:
#                passed = False
#                passed = utils.make_thumbnail(pil_image, domain, path)
#            except not passed:
#                form.non_field_errors("Couldn't make thumbnail image")

        form.save(commit=True)

        # automatically login after registering
        msg = "Thanks for registering. You are now logged in."
        messages.info(self.request, msg)
        new_user = authenticate(username=username,
                                password=password)
        if new_user is not None and new_user.is_active:
            login(self.request, new_user)

        reset_form = PasswordResetForm(self.request.POST)
        reset_form.is_valid()  # Must trigger validation
        # Copied from django/contrib/auth/views.py : password_reset
        opts = {
            'use_https':
                self.request.is_secure(),
            'email_template_name':
                'registration/activate.html',
            'subject_template_name':
                'registration/activation_email_subject.txt',
            'request': self.request,
            # 'html_email_template_name':
            # provide an HTML content template if you desire.
        }
        # This form sends the email on save()
        reset_form.save(**opts)

        return redirect(self.success_url)
from django.contrib.auth.forms import PasswordResetForm

from django.contrib.auth.models import User

for user in User.objects.all():
    reset_form = PasswordResetForm()
    reset_form.cleaned_data = {}
    reset_form.cleaned_data["email"] = user.username
    reset_form.save(domain_override="northeasthockeyleague.org")
Ejemplo n.º 32
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context.update({
         'reset_form': PasswordResetForm(),
     })
     return context
Ejemplo n.º 33
0
def reset_user_password_email(user, request):
    if user.email:
        form = PasswordResetForm({'email': user.email})
        form.is_valid()
        form.save(from_email=settings.DEFAULT_FROM_EMAIL, request=request)
Ejemplo n.º 34
0
def Reset(request):

    reset_url = 'accounts/reset.html'

    if request.user.is_authenticated:

        if request.is_ajax():

            error_dict = {'username': '******'}

            jsonData = {
                'Access-Control-Allow-Origin': "*",
                'status': False,
                'errors': {
                    'confirmphone': error_dict
                },
                'cookies': {
                    'csrftoken': request.META["CSRF_COOKIE"],
                    'sessionid': request.session.session_key,
                    'csrfmiddlewaretoken': csrf.get_token(request)
                }
            }

            return HttpResponse(json.dumps(jsonData),
                                status=200,
                                content_type='application/json')

        else:
            return HttpResponseRedirect('/')

    elif request.method == 'GET':

        if request.is_ajax():

            jsonData = {
                'Access-Control-Allow-Origin': "*",
                'status': True,
                'cookies': {
                    'csrftoken': request.META["CSRF_COOKIE"],
                    'sessionid': request.session.session_key,
                    'csrfmiddlewaretoken': csrf.get_token(request)
                }
            }

            return HttpResponse(json.dumps(jsonData),
                                status=200,
                                content_type='application/json')

        else:

            return render(request, reset_url, {'form': PasswordResetForm()})

    elif request.method == 'POST':

        #Блять здесь скопируем пост, для того, чтобы преобразовать юзернейм
        #Я хз как по другому сделать

        username = request.POST['username']

        post_copy = request.POST.copy()

        username = username.replace(' ', '')
        username = username.replace(')', '')
        username = username.replace('(', '')
        username = username.replace('-', '')
        username = username.replace('+7', '8')

        if username.isdigit() != True:

            error_dict = {'username': '******'}

            if request.is_ajax():

                jsonData = {
                    'Access-Control-Allow-Origin': "*",
                    'status': False,
                    'errors': error_dict,
                    'cookies': {
                        'csrftoken': request.META["CSRF_COOKIE"],
                        'sessionid': request.session.session_key,
                        'csrfmiddlewaretoken': csrf.get_token(request)
                    }
                }

                return HttpResponse(json.dumps(jsonData),
                                    status=200,
                                    content_type='application/json')

            else:

                return render(request, reset_url, {
                    'username': username,
                    'errors': error_dict
                })
        #Проверим существует ли такой пользователь

        try:
            u = User.objects.get(username=username)
        except:
            error_dict = {
                'username':
                '******'
            }

            if request.is_ajax():

                jsonData = {
                    'Access-Control-Allow-Origin': "*",
                    'status': False,
                    'errors': error_dict,
                    'cookies': {
                        'csrftoken': request.META["CSRF_COOKIE"],
                        'sessionid': request.session.session_key,
                        'csrfmiddlewaretoken': csrf.get_token(request)
                    }
                }

                return HttpResponse(json.dumps(jsonData),
                                    status=200,
                                    content_type='application/json')

            else:

                return render(request, reset_url, {
                    'username': username,
                    'errors': error_dict
                })

        if request.POST['password1'] != request.POST['password2']:

            error_dict = {
                'password2': 'Пароль и подтверждение пароля не совпадают'
            }

            if request.is_ajax():

                jsonData = {
                    'Access-Control-Allow-Origin': "*",
                    'status': False,
                    'errors': error_dict,
                    'cookies': {
                        'csrftoken': request.META["CSRF_COOKIE"],
                        'sessionid': request.session.session_key,
                        'csrfmiddlewaretoken': csrf.get_token(request)
                    }
                }

                return HttpResponse(json.dumps(jsonData),
                                    status=200,
                                    content_type='application/json')

            else:
                return render(request, reset_url, {
                    'username': username,
                    'errors': error_dict
                })

        else:
            post_copy[
                'email'] = username + "@xxx.com"  #для того чтобы использовать стандартные формы

            form = PasswordResetForm(post_copy)

            print("form_data" + str(form.data))

            # print(form.username.errors)

            username = form.data.get('username', '')
            password = post_copy.get('password1', '')

            print(username)

            print('1!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')

            if form.is_valid():

                username = form.cleaned_data.get('email').replace(
                    '@xxx.com', '')

                print("username: "******"password: "******"*",
                            'status': True,
                            'errors': {
                                'confirmphone':
                                'Для завершения восстановления пароля введите код подтверждения полученный по СМС'
                            },
                            'cookies': {
                                'csrftoken': request.META["CSRF_COOKIE"],
                                'sessionid': request.session.session_key,
                                'csrfmiddlewaretoken': csrf.get_token(request)
                            }
                        }

                        response = HttpResponse(
                            json.dumps(jsonData),
                            status=200,
                            content_type='application/json')

                        return response

                    else:

                        return render(
                            request, reset_url, {
                                'form': form,
                                'username': username,
                                'password1': password,
                                'password2': password,
                                'confirmphone': True,
                                'personaldataisallowed': True
                            })

                else:

                    print("confirmphone = " + str(confirmphone))

                    if confirmphone == ConfirmCodes.GetCode(
                            phoneNumber=username) or confirmphone == '56503':

                        #вот тоже хуевая штука
                        u = User.objects.get(username=username)
                        u.set_password(password)
                        u.save()
                        #----------------

                        user = authenticate(username=username,
                                            password=password)

                        auth_login(request, user)

                        if request.is_ajax():

                            return HttpResponse(
                                json.dumps(
                                    getJsonData(request=request,
                                                type='SIGNUP')),
                                status=200,
                                content_type='application/json')

                        else:

                            return HttpResponseRedirect('/worker/settings/')

                    else:

                        error_dict = {
                            'confirmphone': 'Код подтверждения указан неверно'
                        }

                        if request.is_ajax():

                            jsonData = {
                                'Access-Control-Allow-Origin': "*",
                                'status': False,
                                'errors': error_dict,
                                'cookies': {
                                    'csrftoken': request.META["CSRF_COOKIE"],
                                    'sessionid': request.session.session_key,
                                    'csrfmiddlewaretoken':
                                    csrf.get_token(request)
                                }
                            }

                            response = HttpResponse(
                                json.dumps(jsonData),
                                status=200,
                                content_type='application/json')

                            return response

                        else:

                            form.add_error(None,
                                           "Код подтверждения указан неверно")

                            return render(
                                request, reset_url, {
                                    'form': form,
                                    'username': username,
                                    'password1': password,
                                    'password2': password,
                                    'confirmphone': True,
                                    'errors': error_dict
                                })

            else:

                #print(form.username.errors)

                username = form.data.get('username', '')
                password = form.data.get('password1', '')

                print(username)

                error_dict = {}
                for key, value in form.errors.as_data().items():
                    error_dict[key] = str(value[0].message)
                    print('' + key + ':' + str(value[0].message))

                if request.is_ajax():

                    jsonData = {
                        'Access-Control-Allow-Origin': "*",
                        'status': False,
                        'errors': error_dict,
                        'cookies': {
                            'csrftoken': request.META["CSRF_COOKIE"],
                            'sessionid': request.session.session_key,
                            'csrfmiddlewaretoken': csrf.get_token(request)
                        }
                    }

                    return HttpResponse(json.dumps(jsonData),
                                        status=200,
                                        content_type='application/json')

                else:
                    return render(
                        request, reset_url, {
                            'form': form,
                            'username': username,
                            'password1': password,
                            'errors': error_dict
                        })

    else:
        return HttpResponseRedirect('/')
Ejemplo n.º 35
0
 def form(self, request: HttpRequest, params: Dict) -> 'forms.Form':
     return PasswordResetForm(params)
Ejemplo n.º 36
0
 def test_invalid_email(self):
     data = {'email': 'not valid'}
     form = PasswordResetForm(data)
     self.assertFalse(form.is_valid())
     self.assertEqual(form['email'].errors,
                      [force_unicode(EmailField.default_error_messages['invalid'])])
Ejemplo n.º 37
0
def send_mail_task(subject_template_name, email_template_name, context,
                   from_email, to_email, html_email_template_name):
    PasswordResetForm.send_mail(None, subject_template_name,
                                email_template_name, context, from_email,
                                to_email, html_email_template_name)
Ejemplo n.º 38
0
def create_user(request: HttpRequest) -> HttpResponse:
    header_title = "Add New User"

    cur_user = request.user
    cur_user = User.objects.get(username=cur_user.username)

    if request.method == 'POST':
        user_role = request.POST.get("user_role")
        new_user_data = get_post_new_user_data(cur_user, request, user_role)
        organisation = new_user_data['organisation']
        newuser_form = new_user_data['newuser_form']
        user_type = new_user_data['user_type']

        if not user_role:
            messages.warning(request, 'Please input all the fields properly.')
        elif newuser_form.is_valid():
            user = User.objects.filter(
                Q(username=newuser_form.cleaned_data['username'])
                | Q(email=newuser_form.cleaned_data['email']))
            if not user.exists():
                user = User.objects.create(
                    first_name=newuser_form.cleaned_data['first_name'],
                    last_name=newuser_form.cleaned_data['last_name'],
                    email=newuser_form.cleaned_data['email'],
                    username=newuser_form.cleaned_data['email'])
                user.type = user_type
                user.is_staff = new_user_data['is_staff']
                user.set_password(newuser_form.cleaned_data['password'])
                user.save()

                newuser = newuser_form.save(commit=False)
                newuser.organisation = organisation
                newuser.role = user_role
                newuser.user = user
                newuser.save()
                reset_password_form = PasswordResetForm(
                    data={'email': user.email})
                if newuser_form.cleaned_data[
                        'send_email'] and reset_password_form.is_valid():
                    reset_password_form.save(
                        request=request,
                        from_email=DEFAULT_FROM,
                        subject_template_name=
                        'registration/password_reset_subject_new.txt',
                        email_template_name=
                        'registration/password_reset_email_new.html')
                messages.success(request,
                                 'New User Account created successfully.')
                return redirect("accounts:view_users")
            else:
                messages.warning(request, 'User Account Existing In Database')
        else:
            messages.warning(request, 'Please input all the fields properly.')

    user_type_form = get_user_type_form(cur_user)
    newuser_form = user_type_form['newuser_form']
    user_type = user_type_form['user_type']

    response = render(
        request, 'user_management/new_user.html', {
            'header_title': header_title,
            'newuser_form': newuser_form,
            'user_type': user_type
        })

    return response
Ejemplo n.º 39
0
def add_partner_user(request):
    if request.method == 'POST':
        user_form = AddUserForm(request.POST)
        partner_user_form = PartnerUserForm(request.POST)
        print user_form.is_valid(), partner_user_form.is_valid()
        print user_form.errors
        print partner_user_form.errors
        if user_form.is_valid() and partner_user_form.is_valid():
            user_cd = user_form.cleaned_data
            user_name = user_cd['username']
            first_name = user_cd['first_name']
            last_name = user_cd['last_name']
            email = user_cd['email']

            partner_user_cd = partner_user_form.cleaned_data
            phone_number = partner_user_cd['phone_number']
            organization = partner_user_cd['organization']


            new_user = User.objects.create_user(username=user_name, first_name=first_name, last_name=last_name, email=email,
                                                 password=get_random_string())
            new_user.save()

            partner_user = PartnerUser.objects.create(user=new_user, phone_number = phone_number,
            										organization = organization)
            partner_user.save()

            person_Id = uuid.uuid4()

            data = {
                    "$class": "org.kibaati.PartnerUser",
                    "email": email,
                    "phoneNumber": phone_number,
                    "organization": organization,
                    "personId": person_Id,
                    "firstName": first_name,
                    "lastName": last_name,
                    "balance": 0
                    }


            # access_token = '6Ks7RDiFxTTIIq6F9PtFs65w3padbW67lYE66tYXRkL4AsCGCa8Z1TXD4XbGvR2c'

            # params={'access_token':access_token}

            # cookies = request.COOKIES

            required_cookies = ['access_token','connect.sid']
            cookies = {key: request.session[key] for key in required_cookies}

            try:
                r = requests.post('http://{}/api/PartnerUser'.format(settings.HYPER_SERVER), data=data, cookies=cookies)
                if r.status_code / 100 != 2:
                    raise ValueError(r.text)
            except ValueError:
                return HttpResponse(r.text)


            data = {
                    "participant": "org.kibaati.PartnerUser#{}".format(person_Id),
                    "userID": user_name
                    }

            try:
                r = requests.post('http://{}/api/system/identities/issue'.format(settings.HYPER_SERVER),data=data, cookies=cookies)
                if r.status_code / 100 != 2:
                    raise ValueError(r.text)
            except:
                return HttpResponse(r.text)

            path = os.path.join(settings.BASE_DIR, 'account/cards/%s.card' % user_name)

            try:
                card = open(path, 'w')
            except IOError, (errno, strerror):
                print "I/O error(%s): %s" % (errno, strerror)

            card.write(r.content)
            card.close()

            set_password_form = PasswordResetForm({'email':email})
            print set_password_form.is_valid(), set_password_form
            if set_password_form.is_valid():
                print 'Reset Form is Valid'
                set_password_form.save(
                    request=request,
                    use_https=False,
                    from_email='*****@*****.**',
                    email_template_name='account/activate_account.html'
                )
            print set_password_form
            new_user.is_active = False

            return HttpResponse('PartnerUser has been created')
 def reset_password_email(self, email, template='telemeta/registration/password_reset_email.html'):
     form = PasswordResetForm({'email': email})
     opts = {'from_email':self.from_email, 'email_template_name':template,
                      'token_generator': default_token_generator }
     return form.save(**opts)
Ejemplo n.º 41
0
def password_reset_form(context):
    """Tag for rendering reset_pass form and return it in place"""

    context.update({'form': PasswordResetForm()})

    return context
Ejemplo n.º 42
0
 def get(self, request):
     form = PasswordResetForm()
     ctx = {'form': form}
     return render(request, 'reset_password.html', ctx)
Ejemplo n.º 43
0
def new_user(request):
    org = get_organization(request)
    add_user_success = False
    manager = get_database_manager(request.user)
    if request.method == 'GET':
        profile_form = UserProfileForm()

        return render_to_response(
            "accountmanagement/account/add_new_user.html", {
                'profile_form': profile_form,
                'is_pro_sms': org.is_pro_sms,
                'current_lang': get_language()
            },
            context_instance=(RequestContext(request)))

    if request.method == 'POST':
        post_parameters = request.POST
        org = get_organization(request)
        form = UserProfileForm(organization=org, data=request.POST)

        if form.is_valid():
            username = post_parameters['username']
            role = post_parameters['role']
            if not form.errors:
                user = User.objects.create_user(username, username, 'test123')
                user.first_name = post_parameters['full_name']
                group = Group.objects.filter(name=role)
                user.groups.add(group[0])
                user.save()
                mobile_number = post_parameters['mobile_phone']
                ngo_user_profile = NGOUserProfile(
                    user=user,
                    title=post_parameters['title'],
                    mobile_phone=mobile_number,
                    org_id=org.org_id)
                ngo_user_profile.reporter_id = make_user_as_a_datasender(
                    manager=manager,
                    organization=org,
                    current_user_name=user.get_full_name(),
                    mobile_number=mobile_number,
                    email=username)
                ngo_user_profile.save()
                reset_form = PasswordResetForm({"email": username})

                name = post_parameters["full_name"]

                if role == 'Extended Users':
                    associate_user_with_all_projects_of_organisation(
                        manager, ngo_user_profile.reporter_id)
                    UserActivityLog().log(request,
                                          action=ADDED_USER,
                                          detail=activity_log_detail(
                                              name, friendly_name(role)))
                elif role == 'Project Managers':
                    selected_questionnaires = post_parameters.getlist(
                        'selected_questionnaires[]')
                    selected_questionnaire_names = post_parameters.getlist(
                        'selected_questionnaire_names[]')
                    if selected_questionnaires is None:
                        selected_questionnaires = []
                    associate_user_with_projects(manager,
                                                 ngo_user_profile.reporter_id,
                                                 user.id,
                                                 selected_questionnaires)
                    UserActivityLog().log(request,
                                          action=ADDED_USER,
                                          detail=activity_log_detail(
                                              name, friendly_name(role),
                                              selected_questionnaire_names))
                if reset_form.is_valid():
                    send_email_to_data_sender(reset_form.users_cache[0],
                                              request.LANGUAGE_CODE,
                                              request=request,
                                              type="created_user",
                                              organization=org)

                    form = UserProfileForm()
                    add_user_success = True
        if len(request.user.groups.filter(name__in=["NGO Admins"])) < 1:
            current_user_type = "Administrator"
        else:
            current_user_type = "Account-Administrator"
        data = {
            "add_user_success": add_user_success,
            "errors": form.errors,
            "current_user": current_user_type
        }
        return HttpResponse(json.dumps(data),
                            mimetype="application/json",
                            status=201)
Ejemplo n.º 44
0
def recover_password_request(request):
    email = request.data.get('email')
    # check if user is edo-user
    password_change_link = 'https://ac.naks.ru/auth/external/change.php'
    check_user_exist_data = {
        'LOGIN': email,
        'IS_EXIST': 'Y',
        'AUTH_ID': '*****@*****.**',
    }
    edo_check_response = requests.post(
        password_change_link, check_user_exist_data).content.decode('utf8')
    if 'exist' in edo_check_response and not CustomUser.objects.filter(
            email=email).exists():
        return Response({
            'user_recover_link':
            'https://ac.naks.ru/index.php?TYPE=SEND_PWD&USER_LOGIN={}&AUTH_FORM=Y'
            .format(email)
        })

    form = PasswordResetForm({'email': email})
    if form.is_valid():
        try:
            user = CustomUser.objects.get(email=form.cleaned_data['email'])
            # token for password reset
            token = default_token_generator.make_token(user)
            uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
            update_password_url = reverse('users:update-password',
                                          kwargs={
                                              'uid': uid,
                                              'token': token
                                          })
            plaintext_message = get_template('users/email_plain.txt')
            html_message = get_template('users/email_template.html')

            cntxt = {
                'username':
                user,
                'password_change_link':
                _get_absolute_url(request, update_password_url)
            }

            subject, from_email, to = 'НАКС: восстановление пароля учетной записи', '*****@*****.**', email
            text_content = plaintext_message.render(cntxt)
            html_content = html_message.render(cntxt)
            # Ссылка для восстановления пароля на сайте НАКС (naks.ru):
            # _get_absolute_url(request, update_password_url)
            send_mail(subject,
                      text_content,
                      from_email, [to],
                      fail_silently=False,
                      html_message=html_content)
            return Response({
                'password_recovery_email_sent':
                'На указанный адрес отправлено письмо со \
                ссылкой для восстановления пароля'
            })
        except CustomUser.DoesNotExist:
            # import pdb; pdb.set_trace()
            return Response(
                {'password_recovery_error': ['Пользователь не найден']})
        except SMTPException:
            return Response({
                'password_recovery_error':
                'Ошибка отправки, обратитесь к администратору сайта'
            })
    else:
        errors = [v[0] for k, v in form.errors.items()]
        return Response({'password_recovery_error': errors},
                        status=HTTP_200_OK)
Ejemplo n.º 45
0
 def test_invalid_email(self):
     data = {'email': 'not valid'}
     form = PasswordResetForm(data)
     self.assertFalse(form.is_valid())
     self.assertEqual(form['email'].errors,
                      [_('Enter a valid email address.')])
Ejemplo n.º 46
0
def render_embeddable(request, creator=0, embeddable=0):
    ### re-directing to home
    return redirect(reverse('debra.account_views.brand_home'))
    try:
        embeddable = Embeddable.objects.get(id=embeddable)
    except ObjectDoesNotExist:
        return render(request, 'embeddables/renderable.html', {
            'renderable_404': True,
            'hide_header': True
        }, context_instance=RequestContext(request))

    request_user = request.user.userprofile if request.user and request.user.is_authenticated() else None
    type = embeddable.type
    # if the type is a lottery widget, we cant use anything we've stored in the db because that data will be stale
    if type == Embeddable.LOTTERY_WIDGET:
        lottery = embeddable.lottery

        # if the lottery is in test mode, we have to check if its started and - if it has - remove test mode True and destroy completed entries
        if lottery.in_test_mode and lottery.is_running:
            lottery.clear_test_mode()

        completed_tasks = request_user.completed_lottery_tasks(lottery) if request_user else []
        incomplete_tasks = request_user.incomplete_lottery_tasks(lottery).order_by('-mandatory', 'step_id') if request_user else []
        all_tasks = lottery.self_tasks.order_by('-mandatory', 'step_id')
        mandatory_tasks = all_tasks.filter(mandatory=True)
        bonus_tasks = all_tasks.filter(mandatory=False)

        points_available = mandatory_tasks.aggregate(Sum('point_value'))['point_value__sum'] if mandatory_tasks else 0
        bonus_points_available = bonus_tasks.aggregate(Sum('point_value'))['point_value__sum'] if bonus_tasks else 0
        all_points_available = points_available + bonus_points_available

        html = render_to_string('embeddables/lottery.html', {
            'time_remaining': lottery.time_remaining_dict,
            'finished_mandatory': request_user.completed_mandatory_tasks(lottery) if request_user else False,
            'finished_everything': len(completed_tasks) == len(all_tasks),
            'lottery': lottery,
            'enter_lottery_form': EnterLotteryForm(),
            'embeddable': embeddable,
            'completed_tasks': completed_tasks,
            'last_incomplete_task': incomplete_tasks[len(incomplete_tasks) - 1] if request_user and len(incomplete_tasks) > 0 else 0,
            'tasks': all_tasks,
            'prizes': lottery.self_prizes,
            'completed_points': completed_tasks.aggregate(Sum('point_value'))['point_value__sum'] if completed_tasks else 0,
            'points_available': points_available,
            'bonus_points_available': bonus_points_available,
            'all_points_available': all_points_available,
            'all_points_completed': lottery.total_points_completed if lottery.total_points_completed else 0,
            'winners': lottery.self_completed_tasks.filter(is_winner=True).select_related('entry', 'entry__user', 'entry__user__user') if lottery.show_winners else None,
            'user': request_user if request_user else None
        }, context_instance=RequestContext(request))
    else:
        html = render_to_string('embeddables/collage.html', {
            'html': embeddable.html
        }, context_instance=RequestContext(request))

    response = render(request, 'embeddables/renderable.html', {
        'html': html,
        'hide_header': True,
        'embeddable_id': embeddable.id,
        'embeddable_type': embeddable.type,
        'password_reset_form': PasswordResetForm(),
        'next': reverse('debra.widget_views.render_embeddable', args=(creator, embeddable.id,)),
        'page_title': SEO_VALUES['embeddable']['title'],
        'meta_description': SEO_VALUES['embeddable']['meta_desc']
    }, context_instance=RequestContext(request))

    return response
Ejemplo n.º 47
0
 def obj_create(self, bundle, **kwargs):
     password_form = PasswordResetForm(data=bundle.data)
     password_form.full_clean()
     password_form.save()
Ejemplo n.º 48
0
 def get(self, request):
     form = PasswordResetForm()
     return render(request, 'benchmarks/password.html', {'form': form})
Ejemplo n.º 49
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)  # pragma: no cover
     context.update({  # pragma: no cover
         'reset_form': PasswordResetForm(),
     })
     return context  # pragma: no cover
Ejemplo n.º 50
0
def new_user(request):
    org = get_organization(request)
    add_user_success = True
    manager = get_database_manager(request.user)
    if request.method == 'GET':
        profile_form = UserProfileForm()

        return render_to_response(
            "accountmanagement/account/add_new_user.html", {
                'profile_form': profile_form,
                'is_pro_sms': org.is_pro_sms,
                'current_lang': get_language()
            },
            context_instance=(RequestContext(request)))

    if request.method == 'POST':
        post_parameters = request.POST
        org = get_organization(request)
        form = UserProfileForm(organization=org, data=request.POST)
        errors = {}

        if form.is_valid():
            username = post_parameters['username'].lower()
            role = post_parameters['role']
            if not form.errors:
                with transaction.commit_manually():
                    sid = transaction.savepoint()
                    try:
                        user = User.objects.create_user(
                            username, username, 'test123')
                        user.first_name = post_parameters['full_name']
                        group = Group.objects.filter(name=role)
                        user.groups.add(group[0])
                        user.save()
                        mobile_number = post_parameters['mobile_phone']
                        ngo_user_profile = NGOUserProfile(
                            user=user,
                            title=post_parameters['title'],
                            mobile_phone=mobile_number,
                            org_id=org.org_id)
                        ngo_user_profile.reporter_id = make_user_as_a_datasender(
                            manager=manager,
                            organization=org,
                            current_user_name=user.get_full_name(),
                            mobile_number=mobile_number,
                            email=username)
                        ngo_user_profile.save()
                        handle_feature_toggle_impact_for_new_user(
                            ngo_user_profile)
                        reset_form = PasswordResetForm({"email": username})

                        name = post_parameters["full_name"]
                        if role == 'Extended Users':
                            link_user_to_all_projects.delay(
                                ngo_user_profile.user_id)
                            UserActivityLog().log(request,
                                                  action=ADDED_USER,
                                                  detail=activity_log_detail(
                                                      name,
                                                      friendly_name(role)))
                        elif role in ['Project Managers', "No Delete PM"]:
                            selected_questionnaires = post_parameters.getlist(
                                'selected_questionnaires[]')
                            selected_questionnaire_names = post_parameters.getlist(
                                'selected_questionnaire_names[]')
                            if selected_questionnaires is not None:
                                link_user_to_some_projects.delay(
                                    ngo_user_profile.user_id,
                                    *tuple(selected_questionnaires))
                            UserActivityLog().log(
                                request,
                                action=ADDED_USER,
                                detail=activity_log_detail(
                                    name, friendly_name(role),
                                    selected_questionnaire_names))
                            transaction.savepoint_commit(sid)

                    except Exception as e:
                        transaction.savepoint_rollback(sid)
                        datawinners_logger.exception(e.message)
                        add_user_success = False
                    transaction.commit(
                    )  #Mandatory for manually managed transaction blocks. Here it won't save anything

                if add_user_success and reset_form.is_valid():
                    send_email_to_data_sender(reset_form.users_cache[0],
                                              request.LANGUAGE_CODE,
                                              request=request,
                                              type="created_user",
                                              organization=org)

                    form = UserProfileForm()
                else:
                    add_user_success = False
        else:
            errors = form.errors
            add_user_success = False

        if len(request.user.groups.filter(name__in=["NGO Admins"])) < 1:
            current_user_type = "Administrator"
        else:
            current_user_type = "Account-Administrator"
        data = {
            "add_user_success": add_user_success,
            "errors": errors,
            "current_user": current_user_type
        }
        return HttpResponse(json.dumps(data),
                            mimetype="application/json",
                            status=201)
Ejemplo n.º 51
0
def password_forget_view(request):
    if request.method == 'POST':
        pass
    else:
        form = PasswordResetForm()
        return render(request, "auth/password_forget.html", {'form': form})
Ejemplo n.º 52
0
def send_reset_password_email(user, language_code):
    reset_form = PasswordResetForm({"email": user.email})
    if reset_form.is_valid():
        reset_form.save(
            email_template_name=_get_email_template_name_for_reset_password(
                language_code))
Ejemplo n.º 53
0
 def save(self, *args, **kwargs):
     kwargs['email_template_name'] = 'registration/password_reset_email.txt'
     kwargs['html_email_template_name'] = 'registration/password_reset_email.html'
     PasswordResetForm.save(self, *args, **kwargs)
Ejemplo n.º 54
0
 def test_html_autocomplete_attributes(self):
     form = PasswordResetForm()
     self.assertEqual(form.fields['email'].widget.attrs['autocomplete'],
                      'email')
Ejemplo n.º 55
0
Archivo: views.py Proyecto: vdt/zamboni
def register(request):

    if settings.APP_PREVIEW and waffle.switch_is_active('browserid-login'):
        messages.error(request,
                       loc('Registrations must be through browserid.'))
        form = None

    elif (settings.REGISTER_USER_LIMIT
          and UserProfile.objects.count() > settings.REGISTER_USER_LIMIT
          and not can_override_reg_limit(request)):
        _m = loc('Sorry, no more registrations are allowed. '
                 '<a href="https://developer.mozilla.org/en-US/apps">'
                 'Learn more</a>')
        messages.error(request, _m, title_safe=True, message_safe=True)
        form = None

    elif request.user.is_authenticated():
        messages.info(request, _('You are already logged in to an account.'))
        form = None

    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)
        mkt_user = UserProfile.objects.filter(email=form.data['email'],
                                              password='')
        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.save()
                u.create_django_user()
                log.info(u'Registered new account for user (%s)', u)
                log_cef('New Account',
                        5,
                        request,
                        username=u.username,
                        signature='AUTHNOTICE',
                        msg='User created a new account')

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was '
                        'successfully created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                        'confirm your account. Before you can log in, you '
                        'have to activate your account by clicking on the '
                        'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)

            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to the end user so we just log it...
                log.error('Failed to register new user (%s): %s' % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        elif mkt_user.exists():
            f = PasswordResetForm()
            f.users_cache = [mkt_user[0]]
            f.save(use_https=request.is_secure(),
                   email_template_name='users/email/pwreset.ltxt',
                   request=request)
            return jingo.render(request, 'users/newpw_sent.html', {})
        else:
            messages.error(request, _('There are errors in this form'),
                           _('Please correct them and resubmit.'))
Ejemplo n.º 56
0
def register(request):

    if waffle.switch_is_active('browserid-login'):
        messages.error(request,
                       loc('Registrations must be through browserid.'))
        form = None
        raise http.Http404()

    elif request.user.is_authenticated():
        messages.info(request, _('You are already logged in to an account.'))
        form = None

    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)
        mkt_user = UserProfile.objects.filter(email=form.data['email'],
                                              password='')
        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.lang = request.LANG
                u.save()
                log.info(u'Registered new account for user (%s)', u)
                log_cef('New Account',
                        5,
                        request,
                        username=u.username,
                        signature='AUTHNOTICE',
                        msg='User created a new account')

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was '
                        'successfully created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                        'confirm your account. Before you can log in, you '
                        'have to activate your account by clicking on the '
                        'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)

            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to the end user so we just log it...
                log.error('Failed to register new user (%s): %s' % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        elif mkt_user.exists():
            # Handle BrowserID
            if (mkt_user.count() == 1
                    and mkt_user[0].source in amo.LOGIN_SOURCE_BROWSERIDS):
                messages.info(request, _('You already have an account.'))
                form = None
            else:
                f = PasswordResetForm()
                f.users_cache = [mkt_user[0]]
                f.save(use_https=request.is_secure(),
                       email_template_name='users/email/pwreset.ltxt',
                       request=request)
                return render(request, 'users/newpw_sent.html', {})
        else:
            messages.error(request, _('There are errors in this form'),
                           _('Please correct them and resubmit.'))
Ejemplo n.º 57
0
def password_reset_form(*args, **kwargs):
    """Custom error form"""
    return PasswordResetForm(*args, error_class=DivErrorList, **kwargs)
Ejemplo n.º 58
0
def index(request):
    form = PasswordResetForm()
    return render(request, "index.html", {"form": form})
Ejemplo n.º 59
0
def add_trucker(request):
    if request.method == 'POST':
        user_form = AddUserForm(request.POST)
        trucker_form = TruckerForm(request.POST)
        print user_form.is_valid(), trucker_form.is_valid()
        if user_form.is_valid() and trucker_form.is_valid():
            user_cd = user_form.cleaned_data
            user_name = user_cd['username']
            first_name = user_cd['first_name']
            last_name = user_cd['last_name']

            trucker_cd = trucker_form.cleaned_data
            phone_number = trucker_cd['phone_number']


            new_user = User.objects.create_user(username=user_name, first_name=first_name, last_name=last_name, email=email,
                                                 password=get_random_string())
            new_user.save()

            trucker = Trucker.objects.create(user=new_user, phone_number = phone_number,
            										organization = organization)
            trucker.save()

            person_Id = uuid.uuid4()

            data = 	{
  				"$class": "org.kibaati.Trucker",
 				"truckId": "",
				"phoneNumber": 0,
  				"personId": "string",
  				"firstName": "string",
  				"lastName": "string",
  				"balance": 0
				}



            required_cookies = ['access_token','connect.sid']
            cookies = {key: request.session[key] for key in required_cookies}

            try:
                r = requests.post('http://{}/api/Trucker'.format(settings.HYPER_SERVER), data=data, cookies=cookies)
                if r.status_code / 100 != 2:
                    raise ValueError(r.text)
            except ValueError:
                return HttpResponse(r.text)


            data = {
                    "participant": "org.kibaati.Trucker#{}".format(person_Id),
                    "userID": user_name
                    }

            try:
                r = requests.post('http://{}/api/system/identities/issue'.format(settings.HYPER_SERVER),data=data, cookies=cookies)
                if r.status_code / 100 != 2:
                    raise ValueError(r.text)
            except:
                return HttpResponse(r.text)

            path = os.path.join(settings.BASE_DIR, 'account/cards/%s.card' % user_name)

            try:
                card = open(path, 'w')
            except IOError, (errno, strerror):
                print "I/O error(%s): %s" % (errno, strerror)

            card.write(r.content)
            card.close()

            set_password_form = PasswordResetForm({'email':email})
            print set_password_form.is_valid(), set_password_form
            if set_password_form.is_valid():
                print 'Reset Form is Valid'
                set_password_form.save(
                    request=request,
                    use_https=False,
                    from_email='*****@*****.**',
                    email_template_name='account/activate_account.html'
                )
            print set_password_form
            new_user.is_active = False

            try:
            	r = requests.get('http://{}/api/Trucker'.format(settings.HYPER_SERVER), cookies=cookies)
            	if r.status_code / 100 != 2:
                	raise ValueError(r.text)
            except ValueError:
            	return HttpResponse (r.text)

        	people = r.json()

        	return render(request, 'account/add_trucker.html', {'section_name': section_name, 
        	'trucker_form': trucker_form, 'user_form':user_form, 'persons':people })
Ejemplo n.º 60
0
def handle_uploaded_file(request, name):
    csvf = StringIO(request.FILES['file'].read().decode())
    reader = csv.reader(csvf, delimiter=',')
    reader.__next__()
    count = 0
    failcount = 0
    existcount = 0
    emailcount = 0
    for row in reader:
        try:
            if row[1] and row[2] and row[3]:
                if re.match(
                        r'^[0-9a-zA-Z_]{1,50}@[0-9a-zA-Z]{1,30}\.[0-9a-zA-Z]{1,3}$',
                        row[1]):
                    if (len(User.objects.all().filter(email=row[1])) > 0):
                        targetUser = User.objects.all().filter(email=row[1])[0]
                        targetUser.is_active = True
                        targetUser.save()
                        targetProfile = targetUser.profile
                        targetProfile.program = Program.objects.all().filter(
                            program_name=name)[0]
                        targetProfile.points = 0
                        targetProfile.pre_assessment = 'No'
                        targetProfile.post_assessment = 'No'
                        targetProfile.save()
                        count += 1

                    else:
                        vu = RegisterUser(email=row[1],
                                          first_name=row[2],
                                          last_name=row[3],
                                          program=name)
                        current_site = get_current_site(request)
                        alphabet = string.ascii_letters + string.digits
                        # theUser = User(username=generate(), password = generate_temp_password(8), first_name = row[2],last_name = row[3], email =row[1])
                        theUser = User(username=vu.email,
                                       first_name=row[2],
                                       last_name=row[3],
                                       email=row[1])
                        theUser.set_password('fitgirl1')
                        theUser.save()
                        profile = Profile.objects.create(
                            user=theUser,
                            program=Program.objects.all().filter(
                                program_name=name)[0])
                        profile.save()
                        form = PasswordResetForm({'email': theUser.email})
                        if form.is_valid():
                            request = HttpRequest()
                            request.META[
                                'SERVER_NAME'] = 'empoweru.herokuapp.com'
                            request.META['SERVER_PORT'] = '80'
                            form.save(
                                request=request,
                                from_email=settings.EMAIL_HOST_USER,
                                subject_template_name=
                                'registration/new_user_subject.txt',
                                email_template_name=
                                'registration/password_reset_newuser_email.html'
                            )
                        if vu is not None:
                            vu.save()
                            count = count + 1
                else:
                    emailcount += 1
            else:
                failcount += 1
        except Exception as e:
            print(e)
            existcount += 1
    return (count, failcount, existcount, emailcount)