Esempio n. 1
0
def send_activation_email(user_id, customer_id):

    from customers.models import Customer
    tenant = Customer.objects.get(id=customer_id)
    user = User.objects.get(id=user_id)

    html_template = get_template('activation/activate_email.html')
    text_template = get_template('activation/activate_email.txt')
    uid = urlsafe_base64_encode(force_bytes(user.pk))
    token = default_token_generator.make_token(user)
    activation_link = "https://%s%s" % (tenant.domain_url,
                                        reverse('account_activate',
                                                kwargs={
                                                    'uidb64': uid,
                                                    'token': token
                                                }))
    context = Context({
        'first_name': user.employee.first_name,
        'activation_link': activation_link,
        'message': tenant.activation_email,
    })
    from_email = 'Scoutmap<*****@*****.**>'
    subject = 'Welcome to Scoutmap'
    text_content = text_template.render(context)
    html_content = html_template.render(context)
    text_content = string.replace(text_content, '[ACTIVATION LINK]',
                                  activation_link)
    text_content = strip_tags(text_content)
    html_content = string.replace(html_content, '[ACTIVATION LINK]',
                                  activation_link)
    msg = EmailMultiAlternatives(subject, text_content, from_email,
                                 [user.email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
Esempio n. 2
0
def reset_password(request):
    form = PasswordResetForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            context = {}
            try:
                user = get_user_model().objects.get(
                    email=form.cleaned_data['email'])
                context['token'] = account_token_generator.make_token(user)
                context['domain'] = get_current_site(request).domain
                context['user'] = user
                context['uid'] = urlsafe_base64_encode(force_bytes(user.pk))

                subject = 'Novo password para Servigraf Sistemas'
                message = render_to_string('password_reset_email.html',
                                           context,
                                           request=request)
                send_mail(subject=subject,
                          message=message,
                          from_email=settings.EMAIL_HOST_USER,
                          recipient_list=[user.email])

            except ObjectDoesNotExist:
                pass

            return render(request, 'password_reset_done.html')

    return render(request, 'password_reset_form.html', {'form': form})
Esempio n. 3
0
    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.image = self.cleaned_data.get('image')
        user.email = self.cleaned_data.get("email")

        if commit:
            user.is_active = False
            user.save()

            subject = u'[%s] : Subscription' % settings.SITE_NAME
            mail = render_to_string(
                'registration/account_activation_email.html', {
                    'title': subject,
                    'username': user.username,
                    'site': settings.SITE_NAME,
                    'user_id': urlsafe_base64_encode(force_bytes(
                        user.pk)).decode(),
                    'token': account_activation_token.make_token(user)
                })

            msg = EmailMessage(
                subject, mail, '%(site)s <%(email)s>' % {
                    'site': settings.SITE_NAME,
                    'email': settings.DEFAULT_FROM_EMAIL
                }, [user.email])

            msg.content_subtype = "html"
            msg.send()

        return user
Esempio n. 4
0
    def post(self, request, *args, **kwargs):
        password_reset_form = PasswordResetForm(request.POST)
        if password_reset_form.is_valid():
            cleaned_data = password_reset_form.clean()
            id_type, identifier = cleaned_data["identifier"]
            url_gid = urlsafe_base64_encode(
                force_bytes(request.session.session_key))

            if id_type == "email":
                email = identifier
                user = get_user_model().objects.get(
                    accounts__email__iexact=email, accounts__is_active=True)
                host_name = settings.HOST_NAME
                token_generator = PasswordResetTokenGenerator()
                use_https = request.is_secure()
                context = {
                    'email': email,
                    'host_name': host_name,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': token_generator.make_token(user),
                    'protocol': 'https' if use_https else 'http',
                }
                reset_password_link = "{protocol}://{host_name}/password/reset/confirm/" \
                                      "{uid}/{token}".format(**context)
                context_data = {"reset_password_link": reset_password_link}
                email_string = render_to_string(
                    "password/password_reset_email.html",
                    context_instance=RequestContext(request, context_data))
                request.session["reset_password_email"] = email
                send_auth_email(email_type="password_reset",
                                email=email,
                                html_msg=email_string)
            else:
                cell_phone = identifier
                request.session["password_reset_phone"] = cell_phone
                return HttpResponseRedirect("/password/reset/phone/%s" %
                                            url_gid)
        else:
            error = get_form_error(password_reset_form.errors)
            logger.error(error)
            return HttpResponseRedirect("")

        redirect_link = "/password/reset/done/%s" % url_gid
        return HttpResponseRedirect(redirect_link)
Esempio n. 5
0
    def post(self, request, key, *args, **kwargs):
        try:
            key = force_text(urlsafe_base64_decode(key))
            if key != request.session.session_key:
                raise TypeError
        except (TypeError, ValueError, OverflowError):
            messages.error(request, u"会话已过期或无效链接")
            return HttpResponseRedirect("/login")
        if not is_time_up(
                request.session.get("password_reset_email_next_send_datetime",
                                    0)):
            remain_seconds = get_remain_seconds(
                request.session.get("password_reset_email_next_send_datetime",
                                    0))
            messages.error(request, u"发送太频繁,请稍等%s秒再试" % remain_seconds)
            return HttpResponseRedirect("")
        email = request.session.get("reset_password_email", "")
        user = get_user_model().objects.get(accounts__email__iexact=email,
                                            accounts__is_active=True)
        host_name = settings.HOST_NAME
        token_generator = PasswordResetTokenGenerator()
        use_https = request.is_secure()
        context = {
            'email': email,
            'host_name': host_name,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user),
            'protocol': 'https' if use_https else 'http',
        }
        reset_password_link = "{protocol}://{host_name}/password/reset/confirm/" \
                              "{uid}/{token}".format(**context)
        context_data = {"reset_password_link": reset_password_link}
        email_string = render_to_string("password/password_reset_email.html",
                                        context_instance=RequestContext(
                                            request, context_data))
        request.session["reset_password_email"] = email

        send_auth_email(email_type="password_reset",
                        email=email,
                        html_msg=email_string)

        request.session[
            "password_reset_email_next_send_datetime"] = get_expire_timestamp(
                settings.EMAIL_SEND_INTERVAL)

        return HttpResponseRedirect("")
Esempio n. 6
0
	def send_recovery_email(self, request, user, token):

		# Get mailing information and next step data
		site = get_current_site(request)
		domain = site.domain
		protocol = ('https' if request.is_secure() else 'http')
		user_id = base64_encode(force_bytes(user.id))

		# Create the actual email
		body = render_to_string('accounts/email_recover.html', context = RequestContext(request, locals()))
		ActionLog.objects.log_account('Sending recovery email to user', user = user, status = 201)

		mail = EmailMultiAlternatives(
			subject = _('Recuperacion de contraseña - Sistema NWL'),
			body = body,
			to = [ user.email_address ]
		)
		mail.attach_alternative(body, 'text/html')
		mail.send(True)
Esempio n. 7
0
 def post(self, request, *args, **kwargs):
     reset_form = CellPhoneResetPasswordForm(data=request.POST,
                                             request=request,
                                             redis_conn=account_redis_api)
     gid = request.POST.get("gid")
     if reset_form.is_valid():
         cell_phone = reset_form.cleaned_data["cell_phone"]
         user = get_user_model().objects.get(
             accounts__cell_phone__exact=cell_phone,
             accounts__is_active=True)
         token_generator = PasswordResetTokenGenerator()
         context = {
             'uid': urlsafe_base64_encode(force_bytes(user.pk)),
             'token': token_generator.make_token(user),
         }
         reset_password_link = "/password/reset/confirm/{uid}/{token}".format(
             **context)
         return HttpResponseRedirect(reset_password_link)
     return HttpResponseRedirect("")
Esempio n. 8
0
    def _account_activate_link(self):
        _host_name = settings.HOST_NAME
        _email = self._account.email
        _gid = uuid.uuid4().hex
        use_https = self._request.is_secure()
        context = {
            'host_name': _host_name,
            'gid': _gid,
            'emailb64': urlsafe_base64_encode(force_bytes(_email)),
            'protocol': 'https' if use_https else 'http'
        }
        activate_link = "{protocol}://{host_name}/register/complete/{emailb64}/{gid}".format(
            **context)
        email_string = render_to_string("activate/activate_account_email.html",
                                        context_instance=RequestContext(
                                            self._request,
                                            {"activate_link": activate_link}))

        self.init_data(mail_content=email_string, recipients=_email)
        self._set_gid_to_db(_gid, _email)
Esempio n. 9
0
 def email_token(self, user):
     """Generate activation email and to user else write to file."""
     token = default_token_generator.make_token(user)
     uid = urlsafe_base64_encode(force_bytes(user.pk))
     subject = 'Account Activation - Enstitute'
     text_content = 'You have registered for an account with Enstitute.'
     activation_link = 'http://{0}/accounts/user/validate/{1}/{2}'.format(
         self.host, force_text(uid), token)
     html_content = '<p>Click --><a href="%s" rel="nofollow">here</a><-- to activate your account.</p>' % activation_link
     from_email = getattr(settings, 'EMAIL_HOST_USER', None)
     to_email = user.email
     message = EmailMultiAlternatives(
         subject, text_content, from_email, [to_email])
     message.attach_alternative(html_content, 'text/html')
     try:
         message.send()
     except socket.error as socket_err:
         filename = user.username + '_activation_fail'
         with open(os.path.join(os.getcwd(), filename), 'w+') as fn:
             fn.write('email: \t\t\t\t' + str(user.email) + '\nactivation link: \t' +
                      str(activation_link) + '\nerror: \t\t\t\t' + str(socket_err))
             fn.close()
Esempio n. 10
0
    def post(self, request, *args, **kwargs):
        form = RegisterForm(data=request.POST,
                            request=request,
                            redis_conn=account_redis_api)
        if not form.is_valid():
            return redirect_login()
        account, error = form.register()
        if error:
            return redirect_login()

        send_activate_email = SendActivateEmail(
            request=request,
            account=account,
            redis_conn=account_redis_api,
            expire_time=settings.REGISTER_ID_EXPIRE)

        result, error = send_activate_email.send_email()

        request.session["register_email"] = account.email
        url_gid = urlsafe_base64_encode(
            force_bytes(request.session.session_key))
        redirect_link = "/register/done/%s" % url_gid

        return HttpResponseRedirect(redirect_link)
Esempio n. 11
0
def path_avatar(instance, filename):
    path = 'avatar/'
    ext = filename.split('.')[-1]
    file_name = '%s.%s' % (urlsafe_base64_encode(force_bytes(
        instance.user.pk)), ext)
    return os.path.join(path, file_name)