Пример #1
0
def forgot(request, template=None):
    """Sends a password reset link to a user's validated email address. If
    the email address isn't validated, do nothing (?)
    """
    # This doesn't make sense if the user is logged in
    if not request.user.is_anonymous():
        return HttpResponseRedirect('/')

    if request.method == 'POST':
        User = get_user_model()

        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']

            try:
                user = User.objects.get(email=email)
                if getattr(user, 'social_auth', None) and user.social_auth.exists():
                    send_social_auth_provider_login_email(request, user)
                else:
                    try:
                        send_password_reset_email(request, user)
                    except User.userdata.RelatedObjectDoesNotExist:
                        from accounts.models import UserData
                        UserData.objects.get_or_create(user=user)
                        send_password_reset_email(request, user)


            except User.DoesNotExist:
                pass

            if not template:
                try:
                    template = settings.ACCOUNTS_TEMPLATES['wait_for_email']
                except Exception as e:
                    print('ERROR: NO SETTING FOR ACCOUNTS_TEMPLATES["wait_for_email"]')
                    pass
            if not template:
                template = 'accounts/forgot/wait_for_email.html'

            return render(request, template)
    else:
        form = ForgotPasswordForm()

    c = {
        'form': form,
    }

    if not template:
        try:
            template = settings.ACCOUNTS_TEMPLATES['forgot']
        except Exception as e:
            print('ERROR: NO SETTING FOR ACCOUNTS_TEMPLATES["forgot"]')
            pass
    if not template:
        template = 'accounts/forgot/forgot.html'

    return render(request, template, c)
Пример #2
0
def forgot_password_view(request):
    form = ForgotPasswordForm(request.POST or None)
    if form.is_valid():
        email = form.cleaned_data['email']
        user = User.objects.filter(email=email)
        if user:
            print('works!')
        else:
            messages.warning(request, 'Δεν υπάρχει χρήστης με αυτό το email')
Пример #3
0
def forgot_password_view(request):
    form = ForgotPasswordForm(request.POST or None)
    if form.is_valid():
        email = form.cleaned_data['email']
        user = User.objects.filter(email=email)
        if user:
            print('works!')
        else:
            messages.warning(request, 'There is no user with this email')
def forgot_password(request):
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request,
                u'Verifique o link que foi enviado para o seu e-mail.'
            )
            return redirect('accounts_forgot_password')
    else:
        form = ForgotPasswordForm()
    return render(request, 'accounts/forgot_password.html', {'form': form})
Пример #5
0
def forgot_password(request):
    """
    Allows user to send an email with a link to reset their password.
    """
    template = 'accounts/forgot.html'
    template_context = {}
    success = False
    
    if request.user.is_authenticated():
        # User is already logged in. Should we let them reset it?
        return redirect('/index')
    
    if request.POST:
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            # Email exists, send email to user
            success = True
            # Build activation key
            user = form.get_user()
            username = user.username
            salt = hashlib.sha224(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt+username).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)
            
            # Create and save user and profile
            new_profile = user.get_profile()
            new_profile.activation_key = activation_key
            new_profile.key_expires = key_expires
            new_profile.save()
    
            # Send an email with the confirmation link
            email = user.email                                                                                                                    
            email_subject = 'Resetting your EventHub account password'
            email_template = get_template('accounts/email/reset.txt')
            context = Context({
                'email'    : email,
                'web_root' : settings.WEB_ROOT,
                'key'      : activation_key
            })
            email_body = email_template.render(context)
            send_mail(email_subject,
                      email_body,
                      '*****@*****.**',
                      [email])
            
        template_context = {
            'form' : form,
            'success' : success
        }
            
    request_context = RequestContext(request, template_context)
    return render_to_response(template, request_context)
Пример #6
0
def forgot_password(request):
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(
                request,
                u'Verifique o link que foi enviado para o seu e-mail.')
            return redirect('accounts_forgot_password')
    else:
        form = ForgotPasswordForm()
    return render(request, 'accounts/forgot_password.html', {'form': form})
Пример #7
0
def forgot_password_check_view(request):
    if request.user.is_authenticated():   # only if the user didn't login
        return HttpResponseRedirect(reverse('accounts:dashboard'))

    verification_code, username = request.GET.get('verification_code'), request.GET.get('username')
    if verification_code is None or username is None:
        return render(request, "accounts/invalid_forgot_password_reset.html", {})
    else:
        try:
            result = ForgotPasswordVerification.objects.get(user__username=username,
                                                            verification_code=verification_code)
            if not result.is_not_expired_forgot_password:
                raise Exception
        except Exception:
            return render(request, "accounts/invalid_forgot_password_reset.html", {})

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

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ForgotPasswordForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            password = form.cleaned_data['password']
            change_password(user, password)
            result.delete()
            return render(request, "accounts/forgot_password_reset_done.html",{})

    # if a GET (or any other method) we'll create a blank form
    else:
        form = ForgotPasswordForm()

    return render(request, 'accounts/forgot_password_reset.html',
                  {'form': form, 'verification_code': verification_code, 'username': username})
Пример #8
0
def forgot_password(request):
    if request.method == "POST":
        form = ForgotPasswordForm(request.POST)
        print(form.errors)
        if form.is_valid():
            try:
                user = User.objects.get(email=form.cleaned_data.get("email"))

                current_site = get_current_site(request)
                subject = 'Password Request Link'
                message = render_to_string(
                    'site/accounts/password_reset.html', {
                        'user': user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': account_activation_token.make_token(user),
                    })
                send_mail(
                    subject,
                    message,
                    'info@' + split_domain_ports(request.get_host()),
                    [user.email],
                    fail_silently=False,
                )
                print("sent email")
                return render(request, 'site/accounts/reset-email-sent.html')
            except:
                print("user does not exist")
                messages.error(request, 'such an account does not exist')
                return redirect("accounts:forgot")

        else:
            print("did not send email due to invalid form")
            form = ForgotPasswordForm()
            return render(request, 'site/accounts/forgot.html', {'form': form})

    else:
        print("did not send email..just loaded the page")
        form = ForgotPasswordForm()
        return render(request, 'site/accounts/forgot.html', {'form': form})
Пример #9
0
def resend_key(request):
    """
    Allows user to generate and send a new activation key.
    """
    template = 'accounts/resend.html'
    template_context = {}
    success = False
    
    if request.user.is_authenticated():
        # User is already logged in. Shouldn't be here
        return redirect('/index')
    
    if request.POST:
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            # Email exists, send email to user
            success = True
            
            user = form.get_user()
            
            # Check if user is already active
            if user.is_active:
                error_msg = "That user is already active! You should be able to \
                    sign in to this site."
                messages.add_message(request, messages.ERROR, error_msg)
            
            else:
                # Build activation key
                username = user.username
                salt = hashlib.sha224(str(random.random())).hexdigest()[:5]
                activation_key = hashlib.sha1(salt+username).hexdigest()
                key_expires = datetime.datetime.today() + datetime.timedelta(2)
                
                # Modify and save user profile
                profile = user.get_profile()
                profile.activation_key = activation_key
                profile.key_expires = key_expires
                profile.save()
                
                email = user.email                                                                                                                    
                email_subject = 'Your EventHub activation link'
                email_template = get_template('accounts/email/register.txt')
                context = Context({
                    'email'          : email,
                    'web_root'       : settings.WEB_ROOT,
                    'activation_key' : activation_key
                })
                email_body = email_template.render(context)
                send_mail(email_subject,
                          email_body,
                          '*****@*****.**',
                          [email])
                
                success_msg = "A new activation link has been sent to your email."
                messages.add_message(request, messages.SUCCESS, success_msg)
            
        template_context = {
            'form' : form,
            'success' : success
        }
            
    request_context = RequestContext(request, template_context)
    return render_to_response(template, request_context)
Пример #10
0
def forgot_pass(request):
    resend_email = request.GET.get('resend')
    if resend_email:
        user = get_object_or_404(User, email=resend_email)
        send_email_change_pass(request, user, resend_email)
        context = {
            'email': resend_email,
            'resend': True
        }
        return render(request, 'accounts/complete_change_pass.html', context)
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            if not username and not email:
                form.add_error(None, 'Email or username must be filled')
                return render(request, 'accounts/forgot_password_form.html', {'form': form})
            if username and email:
                user = User.objects.get(username=username)
                if user.email != email:
                    form.add_error(None, 'Email and username doesnt match')
                    return render(request, 'accounts/forgot_password_form.html', {'form': form})
            if username:
                try:
                    user = User.objects.get(username=username)
                except User.DoesNotExist:
                    form.add_error('username', 'This user isnt exist')
                    return render(request, 'accounts/forgot_password_form.html', {'form': form})
                send_email_change_pass(request, user, user.email)
                return render(request, 'accounts/complete_change_pass.html', {'email': user.email})
            if email:
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    form.add_error('email', 'This email doensnt match with any user')
                    return render(request, 'accounts/forgot_password_form.html', {'form': form})
                send_email_change_pass(request, user, user.email)
                return render(request, 'accounts/complete_change_pass.html', {'email': user.email})
    else:
        form = ForgotPasswordForm()
        return render(request, 'accounts/forgot_password_form.html', {'form': form})
Пример #11
0
def ForgotPasswordView(request):
    api = KavenegarAPI(settings.KAVENEGAR_API_KEY)
    try:
        last_retry_str = request.session['last_retry']
        last_retry = datetime.datetime.strptime(last_retry_str,"%Y-%m-%d %H:%M:%S")
    except:
        last_retry = datetime.datetime.now()
    now = datetime.datetime.now()
    if now >= last_retry:
        if request.method == 'POST':
            data = request.POST.copy()
            form = ForgotPasswordForm(data=request.POST)

            phone_number_exists = False
            if form.is_valid():
                phone_number = form.cleaned_data.get('phone_number')

                try :
                    commonuser = get_object_or_404(CommonUserModel,phone_number = phone_number)
                    if commonuser:
                        print(commonuser)
                        user = commonuser.user
                        var = 'abcdefghijklmnpqrstuvwxyzABCDEFIJKLMNPQRSTUVWXYZ123456789'
                        new_password=''
                        for i in range(0,random.randrange(10,13,1)):
                            c = random.choice(var)
                            new_password += c


                        params = {
                        'sender': settings.KAVENEGAR_PHONE_NUMBER,
                        'receptor': phone_number,
                        'message' : 'سامانه ورزش کن\n' + str(user.username) + ' :'+'نام کاربری شما'+'\n'+ new_password +' :'+ 'رمز عبور جدید شما '
                        }
                        response = api.sms_send(params)
                        phone_number_exists = True
                        user.set_password(new_password)
                        print(user.password)
                        user.save()
                        now = datetime.datetime.now() + datetime.timedelta(minutes=3)
                        str_now = str(now.year)+'-'+str(now.month)+'-'+str(now.day)+' '+str(now.hour)+':'+str(now.minute)+':'+str(now.second)
                        request.session['last_retry'] = str_now
                        return HttpResponseRedirect(reverse('login'))
                except:
                    pass
                try :
                    sportclub = get_object_or_404(SportClubModel,phone_number = phone_number)
                    if sportclub:
                        user = sportclub.user
                        var = 'abcdefghijklmnpqrstuvwxyzABCDEFIJKLMNPQRSTUVWXYZ123456789'
                        new_password=''
                        for i in range(0,random.randrange(10,13,1)):
                            c = random.choice(var)
                            new_password += c


                        params = {
                        'sender': settings.KAVENEGAR_PHONE_NUMBER,
                        'receptor': phone_number,
                        'message' : 'سامانه ورزش کن\n' + str(user.username) + ' :'+'نام کاربری شما'+'\n'+ new_password +' :'+ 'رمز عبور جدید شما '
                        }

                        response = api.sms_send(params)
                        phone_number_exists = True
                        user.set_password(new_password)
                        print(user.password)
                        user.save()
                        now = datetime.datetime.now() + datetime.timedelta(minutes=3)
                        str_now = str(now.year)+'-'+str(now.month)+'-'+str(now.day)+' '+str(now.hour)+':'+str(now.minute)+':'+str(now.second)
                        request.session['last_retry'] = str_now
                        return HttpResponseRedirect(reverse('login'))
                except:
                    pass
                try :
                    masteruser = get_object_or_404(MasterUserModel,phone_number = phone_number)
                    if masteruser:
                        user = masteruser.user
                        var = 'abcdefghijklmnpqrstuvwxyzABCDEFIJKLMNPQRSTUVWXYZ123456789'
                        new_password=''
                        for i in range(0,random.randrange(10,13,1)):
                            c = random.choice(var)
                            new_password += c


                        params = {
                        'sender': settings.KAVENEGAR_PHONE_NUMBER,
                        'receptor': phone_number,
                        'message' : 'سامانه ورزش کن\n' + str(user.username) + ' :'+'نام کاربری شما'+'\n'+ new_password +' :'+ 'رمز عبور جدید شما '
                        }
                        print(user.password)
                        response = api.sms_send(params)
                        phone_number_exists = True
                        user.set_password(new_password)
                        user.save()
                        now = datetime.datetime.now() + datetime.timedelta(minutes=3)
                        str_now = str(now.year)+'-'+str(now.month)+'-'+str(now.day)+' '+str(now.hour)+':'+str(now.minute)+':'+str(now.second)
                        request.session['last_retry'] = str_now
                        return HttpResponseRedirect(reverse('login'))
                except:
                    pass

            else:
                print(form.errors)
            if not phone_number_exists:
                return HttpResponseRedirect(reverse('accounts:wrongphonenumber'))


        else:
            form = ForgotPasswordForm()

        return render(request,'accounts/forgotpassword.html',{'form':form})
    else:
        return HttpResponseRedirect(reverse('commonuser:twominwait'))