Beispiel #1
0
def add_mice_node(mice):
    try:
        gdb = neo4j.GraphDatabaseService(settings.GRAPH_DB_URL)
        if gdb.get_indexed_node('node_auto_index', 'identifier',
                                mice.id_genealogy):
            return
        else:

            print "inizio aggiunta topo", mice.id_genealogy
            father_gen_id = Implant_details.objects.get_old(
                id_mouse=mice.id).aliquots_id.id_genealogy
            print father_gen_id
            g = GenealogyID(mice.id_genealogy)
            nodes = {}
            dateMouse = datetime.datetime.now()

            nodes[mice.id_genealogy] = {
                'type': 'Biomouse',
                'altype': None,
                'id': mice.id,
                'relationships': {},
                'nodeid': None,
                'date': str(dateMouse)
            }

            nodes[father_gen_id] = {
                'type': 'Aliquot',
                'nodeid': None,
                'wg': {},
                'relationships': {},
                'alType': None
            }
            nodes[father_gen_id]['nodeid'] = gdb.get_indexed_node(
                'node_auto_index', 'identifier', father_gen_id)

            query = "START n=node:node_auto_index(identifier='" + father_gen_id + "') match (w:WG)-[r]->n WHERE not has(r.endDate) RETURN id(r), type(r), w.identifier, id(w)"
            data, metadata = cypher.execute(gdb, query)
            print query, data
            if len(data) > 0:
                for d in data:
                    nodes[father_gen_id]['wg'][d[0]] = {
                        'nodeid':
                        gdb.get_indexed_node('node_auto_index', 'identifier',
                                             d[2]),
                        'rel_type':
                        d[1],
                        'name':
                        d[2]
                    }

            #relsWg = list(graph_db.match(end_node=nodes[father_gen_id]['nodeid']), rel_type="OwnsData") # e i paramteri associati? e i nodi attaccati?
            fatherNode = nodes[father_gen_id]
            print fatherNode

            nodes[g.getGenID()]['relationships'][father_gen_id] = {
                'type': 'generates',
                'app': 'implant'
            }

            buildSemanticNode(g.getGenID(), 'Biomouse', None, nodes, dateMouse)
            print 'after buildSemanticNode for ', g.getGenID()
            batch = neo4j.WriteBatch(gdb)
            batch.clear()

            rels = []

            for n, nInfo in nodes.items():
                print 'before ', n, nInfo
                if nInfo['nodeid'] is None:
                    nInfo['nodeid'] = batch.create(node(identifier=n))
                    labels = setLabels(nInfo['type'], nInfo['altype'])
                    #print labels
                    batch.add_labels(nInfo['nodeid'], *labels)
                    if nInfo['type'] in ['Biomouse', 'Aliquot', 'Collection']:
                        for wg, wgInfo in fatherNode['wg'].items():
                            batch.create(
                                rel(wgInfo['nodeid'], wgInfo['rel_type'],
                                    nInfo['nodeid'], {
                                        'startDate': nInfo['date'],
                                        'endDate': None
                                    }))
                print 'after ', n, nInfo

            for dest, destInfo in nodes.items():
                for source, relInfo in destInfo['relationships'].items():
                    print dest, destInfo, source, relInfo
                    if relInfo['app']:
                        batch.create(
                            rel(nodes[source]['nodeid'], relInfo['type'],
                                destInfo['nodeid'], {'app': relInfo['app']}))
                    else:
                        batch.create(
                            rel(nodes[source]['nodeid'], relInfo['type'],
                                destInfo['nodeid']))

            print '---------------------------------------------'
            print 'nodes', nodes
            print 'batch submit'
            results = batch.submit()
            batch.clear()
            print 'batch clear'

            for wg, wgInfo in fatherNode['wg'].items():
                if BioMice_WG.objects.filter(
                        biomice=mice,
                        WG=WG.objects.get(name=wgInfo['name'])).count() == 0:
                    m2m = BioMice_WG(biomice=mice,
                                     WG=WG.objects.get(name=wgInfo['name']))
                    m2m.save()

    except Exception, e:
        print e
        transaction.rollback()
        if BioMice_WG.objects.filter(
                biomice=mice, WG=WG.objects.get(name='admin')).count() == 0:
            m2m = BioMice_WG(biomice=mice, WG=WG.objects.get(name='admin'))
            m2m.save()
        subject = 'ERROR DURING SAVING XENO IN GRAPH DB'
        message = 'Error saving genid :', str(mice.id_genealogy)
        toList = list()
        email = EmailMessage(subject, message, '', toList, [], '', '', '', [])
Beispiel #2
0
def reset_password(request, field="email"):
    if not settings.RELATE_REGISTRATION_ENABLED:
        raise SuspiciousOperation(_("self-registration is not enabled"))

    # return form class by string of class name
    ResetPasswordForm = globals()["ResetPasswordFormBy" +
                                  field.title()]  # noqa
    if request.method == 'POST':
        form = ResetPasswordForm(request.POST)
        user = None
        if form.is_valid():
            exist_users_with_same_email = False
            if field == "instid":
                inst_id = form.cleaned_data["instid"]
                try:
                    user = get_user_model().objects.get(
                        institutional_id__iexact=inst_id)
                except ObjectDoesNotExist:
                    pass

            if field == "email":
                email = form.cleaned_data["email"]
                try:
                    user = get_user_model().objects.get(email__iexact=email)
                except ObjectDoesNotExist:
                    pass
                except MultipleObjectsReturned:
                    exist_users_with_same_email = True

            if exist_users_with_same_email:
                # This is for backward compatibility.
                messages.add_message(
                    request, messages.ERROR,
                    _("Failed to send an email: multiple users were "
                      "unexpectedly using that same "
                      "email address. Please "
                      "contact site staff."))
            else:
                if user is None:
                    FIELD_DICT = {  # noqa
                        "email": _("email address"),
                        "instid": _("institutional ID")
                    }
                    messages.add_message(
                        request, messages.ERROR,
                        _("That %(field)s doesn't have an "
                          "associated user account. Are you "
                          "sure you've registered?") %
                        {"field": FIELD_DICT[field]})
                else:
                    if not user.email:
                        messages.add_message(
                            request, messages.ERROR,
                            _("The account with that institution ID "
                              "doesn't have an associated email."))
                    else:
                        email = user.email
                        user.sign_in_key = make_sign_in_key(user)
                        user.save()

                        from relate.utils import render_email_template
                        message = render_email_template(
                            "course/sign-in-email.txt", {
                                "user":
                                user,
                                "sign_in_uri":
                                request.build_absolute_uri(
                                    reverse("relate-reset_password_stage2",
                                            args=(
                                                user.id,
                                                user.sign_in_key,
                                            ))),
                                "home_uri":
                                request.build_absolute_uri(
                                    reverse("relate-home"))
                            })
                        from django.core.mail import EmailMessage
                        msg = EmailMessage(
                            string_concat("[%s] " % _(get_site_name()),
                                          _("Password reset")), message,
                            getattr(settings, "NO_REPLY_EMAIL_FROM",
                                    settings.ROBOT_EMAIL_FROM), [email])

                        from relate.utils import get_outbound_mail_connection
                        msg.connection = (
                            get_outbound_mail_connection("no_reply")
                            if hasattr(settings, "NO_REPLY_EMAIL_FROM") else
                            get_outbound_mail_connection("robot"))
                        msg.send()

                        if field == "instid":
                            messages.add_message(
                                request, messages.INFO,
                                _("The email address associated with that "
                                  "account is %s.") % masked_email(email))

                        messages.add_message(
                            request, messages.INFO,
                            _("Email sent. Please check your email and "
                              "click the link."))

                        return redirect("relate-home")
    else:
        form = ResetPasswordForm()

    return render(
        request, "reset-passwd-form.html", {
            "field": field,
            "form_description": _("Password reset on %(site_name)s") % {
                "site_name": _(get_site_name())
            },
            "form": form
        })
Beispiel #3
0
 def do(self):
     file_path = Command().handle()
     mail = EmailMessage('Backup bazy iserwis.lechkom.pl z dnia %s' % datetime.now().strftime('%d-%m-%Y'), '', '*****@*****.**', ['*****@*****.**'])
     mail.attach_file(file_path)
     mail.send()
Beispiel #4
0
 def send_email(data):
     email = EmailMessage(subject=data['email_subject'],
                          body=data['email_body'],
                          to=[data['to_email']])
     EmailThread(email).start()
Beispiel #5
0
 def send_email(data):
   email = EmailMessage(subject=data['email_subject'], body=data['email_body'], to=[data['to_email']])
   email.content_subtype = "html"
   email.send()
Beispiel #6
0
def add_donatur(request):
    try:
        last_id = int(Donatur.objects.last().pk) + 1
    except:
        last_id = 1
    id_transaksi = '#' + ''.join(
        random.SystemRandom().choice(string.ascii_uppercase + string.digits)
        for _ in range(6))

    if (request.method == 'POST'):
        nominal = int(request.POST['nominal'])
        namadepan = request.POST['namadepan']
        namabelakang = request.POST['namabelakang']
        emailUser = request.POST['email']
        noHp = request.POST['nohandphone']
        kelamin = request.POST['kelamin']
        alamat = request.POST['alamat']
        birth = request.POST['birthdate']
        domisili = request.POST['domisili']
        nama = namadepan + ' ' + namabelakang
        id_transaksi = id_transaksi + '00' + str(last_id)
        kode_transfer = int(random.randint(1, 100))
        donatur = Donatur(nominal=nominal,
                          nama=namadepan + ' ' + namabelakang,
                          email=emailUser,
                          noHp=noHp,
                          kelamin=kelamin,
                          alamat=alamat,
                          birth=birth,
                          domisili=domisili,
                          id_transaksi=id_transaksi,
                          kode_transfer=kode_transfer,
                          jumlah_donasi=int(nominal + kode_transfer))
        donatur.save()
        print(Donatur.objects.all().count())
        pesan = "Assalamu'alaikum Warrahmatullahi Wabarakaatuh \n" \
                + 'Alhamdulillah, kami mengucapkan terima kasih kepada ' + kelamin + ' ' + nama + ' telah melakukan donasi kepada Yayasan Wakaf Produktif – Pengelola Aset Islami Indonesia.\n\n' \
                + 'Berikut adalah rincian donasi ' + kelamin + ' ' + nama + '\n\n' \
                + 'No Transaksi: ' + id_transaksi + '\n' \
                + 'Nama: ' + nama+ '\n' \
                + 'Tanggal Lahir: ' + birth +'\n' \
                + 'Alamat: ' + alamat + '\n' \
                + 'Domisili: ' + domisili + '\n' \
                + 'Jumlah Donasi: Rp ' + str(nominal) +'\n' \
                + 'Kode Unik: ' + str(kode_transfer) +'\n' \
                + 'Nominal Transfer: Rp ' + str(int(nominal+kode_transfer)) + '\n\n' \
                + 'Silahkan melanjutkan pembayaran donasi ke rekening kami:\n' \
                + 'Bank CIMB Niaga Syariah\n' \
                + 'No. Rekening: 761868208100\n' \
                + 'Atas Nama: YAYASAN WAKAF PRODUKTIF PENGELOLA ASET ISLAMI INDONESIA\n\n' \
                + 'Setelah anda melakukan pembayaran, silahkan lakukan konfirmasi di http://wakaf.paii.co.id/konfirmasi\n\n' \
                + 'Untuk informasi lebih lanjut, anda dapat menghubungi:\n' \
                + 'Call Center: 021-123456\n' \
                + 'SMS/WA: 0812-9060-9550\n' \
                + 'Email: [email protected]\n' \
                + 'Website: wakaf.paii.co.id\n\n'\
                + "“Jazakumullah khairan katsiran. Wa jazakumullah ahsanal jaza”\n" \
                + 'Yayasan Wakaf Produktif – Pengelola Aset Islami Indonesia'
        email = EmailMessage('Informasi dan Langkah Donasi',
                             pesan,
                             '*****@*****.**', [emailUser],
                             headers={'Message-ID': 'foo'})
        email.send(fail_silently=False)
        print("email kirim pertama")
        # TODO: Redirect ke page Thank you

        return thankyouDonasi(request, donatur)
    return HttpResponseRedirect(reverse('wakafapp:home'))
Beispiel #7
0
def callallocations(request):
    callallocateform = CallAllocateForm(None,request.POST or None,prefix='callallocateform')
    if request.method == 'POST':
        cudate = datetime.datetime.now().strftime('%Y%m%d')
        c=cudate+""+str(random.randint(0,10000))
        print(c)
        if callallocateform.is_valid():
            #name = callallocateform.cleaned_data['title']
            cid = callallocateform.cleaned_data['customer_id']
            pro = callallocateform.cleaned_data['product']
            prob = callallocateform.cleaned_data['description']
            cstatus = callallocateform.cleaned_data['call_status']
            ctype = callallocateform.cleaned_data['call_type']
            cend = callallocateform.cleaned_data['end']
            tat = callallocateform.cleaned_data['call_tat']
            cnote = callallocateform.cleaned_data['call_note']
            cpri = callallocateform.cleaned_data['call_priority']
            cname = callallocateform.cleaned_data['caller_name']
            enid = callallocateform.cleaned_data['engg_id']
            estat = callallocateform.cleaned_data['engg_status']
            #engg = callallocateform.cleaned_data['engg_name']

            #dte = callallocateform.cleaned_data['start']
            #tme = callallocateform.cleaned_data['call_alloc_time']

            qs = Customer.objects.values_list('customer_adrress',flat=True).get(id=cid.id)
            cn = Customer.objects.values_list('customer_name',flat=True).get(id=cid.id)
            ce = Customer.objects.values_list('customer_email',flat=True).get(id=cid.id)
            pn = Customer.objects.values_list('customer_contact_no',flat=True).get(id=cid.id)
            ct = Customer.objects.values_list('customer_city',flat=True).get(id=cid.id)

            eid = engg.objects.values_list('engg_id',flat=True).get(id=enid.id)
            en = engg.objects.values_list('engg_name',flat=True).get(id=enid.id)
            ec = engg.objects.values_list('engg_contact_number',flat=True).get(id=enid.id)


            csave = callallocate(
            customer_id_id = cid.id,
            title = cn,
            comp_address = qs,
            phone_number = pn,
            product = pro,
            description = prob,
            call_status = cstatus,
            complaint_no = c,
            call_type = ctype,
            cust_city = ct,
            end = cend,
            call_tat = tat,
            call_note = cnote,
            call_priority = cpri,
            caller_name = cname,
            engg_id_id = enid.id,
            engineer_id = eid,
            engg_status = estat,
            engg_name = en,
            engg_contact = ec,
            comp_email = ce,

            )
            csave.save()

            subject = 'Call Allocated'
            ctx = {
            'complid':str(c),
            'custname':cn,
            'addr':qs,
            'ename':en,
            'econt':ec,
            'prod':pro.product_name,
            'prob':prob,
            'note':cnote,
            'calnme':cname,
            'stat':cstatus,
            }
            message = get_template('loginapp/email.html').render(ctx)

            from_email = settings.EMAIL_HOST_USER
            to_list = [ce,settings.EMAIL_HOST_USER]
            msg = EmailMessage(subject,message,to=to_list,from_email=from_email)
            msg.content_subtype = 'html'
            msg.send()
            #send_mail(subject,message,from_email,to_list,fail_silently = True)

            return render(request,'loginapp/calendar1.html')

    return render(request,'loginapp/callallocate_form1.html',{'callallocateform':callallocateform,})
Beispiel #8
0
 def send_email(data):
     email = EmailMessage(data["email_subject"],
                          data["email_body"],
                          from_email="*****@*****.**",
                          to=[data["to"]])
     email.send()
Beispiel #9
0
 def delete_model(self, request, obj):
     EmailMessage('Greetings from a deleted object',
                  'I hereby inform you that some user deleted me',
                  '*****@*****.**', ['*****@*****.**']).send()
     return super(ArticleAdmin, self).delete_model(request, obj)
Beispiel #10
0
def send(request, eventid):

    #To find clubid for the eventid
    con = pymysql.connect(host='localhost',
                          user='******',
                          password='******',
                          db='evite')
    cur = con.cursor()
    cur.execute(
        "select clubId,title,date,time,location from event where eventId = %s",
        [eventid])
    result = cur.fetchone()
    clubid = result[0]
    eventname = result[1]
    date = result[2]
    time = result[3]
    location = result[4]

    #To find emails for the club id
    con1 = pymysql.connect(host='localhost',
                           user='******',
                           password='******',
                           db='evite')
    cur1 = con1.cursor()
    cur1.execute(
        "select email from auth_user where id in (select userId from member where clubId = %s)",
        [clubid])
    result1 = cur1.fetchall()

    #To insert all the invitation in invitation table
    con2 = pymysql.connect(host='localhost',
                           user='******',
                           password='******',
                           db='evite')
    cur2 = con2.cursor()
    add_event = ("INSERT INTO invitation (eventId, emailId, guid)"
                 "VALUES (%s, %s, %s)")
    add_review = ("INSERT INTO FEEDBACK (eventID,emailId,guid)"
                  "VALUES (%s, %s, %s)")
    for emailid in result1:
        guid = uuid.uuid4().hex[:32]
        pk_list = (eventid, emailid[0], guid)
        cur2.execute(add_event, pk_list)
        cur2.execute(add_review, pk_list)
        con2.commit()
        subject = "Event Invitation"
        to = [emailid[0]]
        from_email = '*****@*****.**'
        ctx = {
            'guid': guid,
            'eventname': eventname,
            'date': date,
            'time': time,
            'location': location,
        }
        message = get_template('event/email.html').render(ctx)
        msg = EmailMessage(subject, message, to=to, from_email=from_email)
        msg.content_subtype = 'html'
        msg.send()
    messages.success(request, 'Invitation emails sent successfully!')
    return HttpResponseRedirect('/event')
Beispiel #11
0
def checkout_handling(request):
    if request.method=='POST':
        email=request.POST.get('email')
        user = get_object_or_404(User, email=email)
        notification_type=request.POST.get('notification_type')
        operation_id=request.POST.get('operation_id')        
        amount=request.POST.get('amount')
        withdraw_amount=request.POST.get('withdraw_amount')
        currency=request.POST.get('currency')
        datetime=request.POST.get('datetime')
        sender=request.POST.get('sender')
        city = request.POST.get('city')
        street = request.POST.get('street')
        building = request.POST.get('building')
        suite = request.POST.get('suite')
        flat = request.POST.get('flat')
        zip = request.POST.get('zip')
        codepro=request.POST.get('codepro')
        notification_secret=settings.YANDEX_SECRET_KEY
        label=request.POST.get('label')
        sha1_hash=request.POST.get('sha1_hash')
        madesha1 = notification_type + '&' + operation_id + '&' + amount + '&' + currency + '&' + datetime + '&' + sender + '&' + codepro + '&' + notification_secret + '&' + label
        sha1_madehash = hashlib.sha1(madesha1.encode('utf-8')).hexdigest()
        if sha1_madehash == sha1_hash:
            cart = Cart.objects.all().filter(user=user).first()
            if city:
                user.delivery_address = city
                user.save()
                """address = Address()
                address.first_name = user.first_name
                address.last_name = user.last_name
                address.company_name = " "
                address.street_address_1 = " "
                address.street_address_2 = " "
                address.city = city
                address.city_area = " "
                address.postal_code = " "
                address.country = "Russian Federation"
                address.country_area = " "
                address.phone = user.phone
                address.save()
                
                
                user.default_billing_address = address
                user.addresses.add(address)
                user.save()
                cart.billing_address = user.addresses.first()
                cart.save()"""
                
            try:
                order = create_order(
                    cart=cart,
                    tracking_code=analytics.get_client_id(request),
                    discounts=request.discounts,
                    taxes=get_taxes_for_cart(cart, request.taxes))
            except InsufficientStock:
                return redirect('cart:index')
          # happens when a voucher is now invalid
            if not order:
                msg = pgettext('Checkout warning', 'Проверьте свою корзину(возможно истек срок действия купона).')
                messages.warning(request, msg)
                return redirect('cart:index')
            cart.delete()
            msg = pgettext_lazy('Order status history entry', 'Заказ размещен.')
            order.history.create(user=user, content=msg)

            lines = order.lines.all()
            for line in lines:
                suplierorder = SuplierOrder.objects.get_or_create(status=SuplierOrderStatus.CURRENT, 
                    suplier = line.variant.product.suplier)[0]
                line.suplierorder = suplierorder
                suplierorder.total_net += line.get_total()
                suplierorder.save()
                line.save()
            order.status = OrderStatus.PAID
            defaults = {
                'total': order.total.gross.amount,
                'tax': order.total.tax.amount,
                'currency': order.total.currency,
                'delivery': order.shipping_price.net.amount,
                'description': pgettext_lazy(
                    'Payment description', 'Order %(order)s') % {
                        'order': order},
                'captured_amount': order.total.gross.amount}
            Payment.objects.get_or_create(
                variant=CustomPaymentChoices.MANUAL,
                status=PaymentStatus.CONFIRMED, order=order,
                defaults=defaults)
            msg = pgettext_lazy(
                'Dashboard message',
                'Заказ был оплачен')
            order.history.create(content=msg, user=user)
            order.save()
            for line in lines:
                suplierorder = line.suplierorder
                if suplierorder.total_net.amount >= 10000:
                    suplierorder.status = SuplierOrderStatus.READY_TO_HANDLE
                    suplieroder.save()
            
            site = Site.objects.get_current()
            mail_subject = 'Заказ на BlitzShop'
            message = render_to_string('templated_email/compiled/confirm_order.html', {
                    'domain': site.domain,
                    'site_name': site.name,
                    'order': order
                })
            to_email = email
            
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.content_subtype = "html"
            email.send()
    return HttpResponse(status_code =200)
Beispiel #12
0
	def post(self, request):
		valid_form = False
		form_used = None
		stripe.api_key = settings.STRIPE_TEST_SECRET_KEY

#		print (request.form['text'])
		form_info_a = PricingFormA(request.POST)
		form_info_b = PricingFormB(request.POST)

		if form_info_b.is_valid():
			p_name = 'Basic'

			form_used = 'B'
			valid_form = True
			amount = 0000
			plan = stripe.Plan.retrieve("plan_DLIn5NDMMMdMHj")

			request.session['Troop_id'] = form_info_b.cleaned_data['Test_BTroop_id']
			request.session['Troop_abr'] = form_info_b.cleaned_data['Test_BTroop_abr']
			request.session['Troop_fd_date'] = form_info_b.cleaned_data['Test_BTroop_fd_date']
			contact_email = form_info_b.cleaned_data['Test_BTroop_email']

			print('Form B:')
			print (request.session.get('Troop_id', 'Nothing sorry'))

		elif form_info_a.is_valid():
			form_used = 'A'
			print ('form A')

			amount = 1600
			plan = stripe.Plan.retrieve("plan_DLIkKZNvTGqfCg")
			p_name = 'Premium'
			valid_form = True

			request.session['Troop_id'] = form_info_a.cleaned_data['Test_ATroop_id']
			request.session['Troop_abr'] = form_info_a.cleaned_data['Test_ATroop_abr']
			request.session['Troop_fd_date'] = form_info_a.cleaned_data['Test_ATroop_fd_date']
			print('Form A:')
			print (request.session.get('Troop_id', 'Nothing sorry'))			

#			to fix up later
			timestamp = (int(time.time()) + 120) 

			contact_email = request.POST['stripeEmail']

			customer = stripe.Customer.create(
				email=contact_email,
				source=request.POST['stripeToken'],
				api_key = settings.STRIPE_TEST_SECRET_KEY
				)
#			charge = stripe.Charge.create(
#				customer = customer.id,
#				amount=amount,
#				currency='aud',
#				)

			
			subscription = stripe.Subscription.create(
				customer=customer.id,
				items=[
					{
				    "plan": plan,
				    },
				  ],
				trial_period_days = 30,

				)
		if valid_form:

			r_amount = float((str(amount))[:-2] + "." + (str(amount)[-2:]))
			new_leader = None
			request.session['amount'] = r_amount 
			request.session['contact_email'] = contact_email
			request.session['signup'] = True	

			print (request.session['Troop_abr'])

			#Group Creation
			if not(GroupRecord.objects.filter(group=request.session['Troop_id']).exists()):
				new_group = GroupRecord.objects.create(group=request.session['Troop_id'], 
						abbreviation=request.session['Troop_abr'], subscription=p_name)
				new_group.save()

			_group = GroupRecord.objects.filter(group=request.session['Troop_id'])[0]
			#print ('group: {}'.format(_group))
			Master_username = '******' + str(request.session['Troop_abr'])
			request.session['username'] = Master_username
			created = User.objects.filter(username=Master_username).exists()
			print(created)
			Mast_pass = str(request.session['Troop_abr']) + str(request.session['Troop_fd_date'])
			if not(User.objects.filter(username=Master_username).exists()):
				#user creation
				new_leader = User.objects.create_user(username=Master_username, password=Mast_pass, is_staff = True)
				new_leader.save()

				#userprofile
#				UserProfile.objects.create(scout_username=new_leader, troop=new_group)
				new_leader.userprofile.scout_username = new_leader
				new_leader.userprofile.role = 'Leader'
				new_leader.userprofile.troop_details = _group
				new_leader.userprofile.save()
				new_leader.userprofile.refresh_from_db()


			#add staff status

			#send email with details
			to_list = []
			to_list.append(contact_email)
			reply_list = []
			reply_list.append('*****@*****.**')

			welcome_msg = 'Hey there! \nI am excited to have you as part of this! SORB aims to help reduce your stress when managing scout records and it provides a growing abundance of features to help you. To get started, here are your login details: \n'
			body_msg = 'Master username: {}\nMaster password: {}\n\n'.format(Master_username, Mast_pass)
			closing_msg = 'If you have any trouble working things out, or if you have any feedback, please reply directly to this email. \n\nWelcome, \nFelix Hall'
			msg = welcome_msg + body_msg + closing_msg
			email = EmailMessage (
				subject = 'Welcome to SORB!',
				body=msg,
				from_email='*****@*****.**',
				reply_to=reply_list,
				to=to_list,
				headers={'Content-Type': 'text/plain'})
			email.send()
			#send_mail(subject, msg, '*****@*****.**', [contact_email], fail_silently=False,) 

			return redirect ('home_page:home')

		elif (not (valid_form)) or existing_credentials:
			#error_packaging packages error to be [['field', ['error1, 'error2]]]
			#blank_field finds if all fields are blank, returns True if they are
			#form b errors

		

			Aerrors = form_info_a.errors
			Aerror_list = error_packaging(Aerrors)
			A_Blank_test = blank_field(Aerror_list)
			print (Aerror_list)

			#creates a dictionary where the key is a new key with a human readble name

			#form b errors
			Berrors = form_info_b.errors
			Berror_list = error_packaging(Berrors)
			B_Blank_test = blank_field(Berror_list)

			if form_used == "B" and existing_credentials:
				Berror_list.append(['Authenticating the user', ['Username provided has already been used. Try slighty changing your details']])
			elif form_used == 'A' and existing_credentials:
				Aerror_list.append(['Authenticating the user', ['Username provided has already been used. Try slighty changing your details']])


			args = {
			'key': settings.STRIPE_TEST_PUBLIC_KEY,
			'formA': PricingFormA(),
			'formB': PricingFormB(),
			}


			if B_Blank_test and A_Blank_test:
				args['blank_error'] = True
			elif B_Blank_test and not A_Blank_test:
				args['Aerror'] = Aerror_list
				args['blank_A'] = True
			elif A_Blank_test and not B_Blank_test:
				args['Berror'] = Berror_list
				args['blank_B'] = True
			print ('Error')

		return render(request, self.template_name, args)
Beispiel #13
0
 def test_build_w_reply_to_sg_email(self):
     # Test setting a Reply-To header.
     msg = EmailMessage()
     msg.extra_headers = {'Reply-To': '*****@*****.**'}
     with self.settings(SENDGRID_API_KEY='test_key'):
         mail = SendGridBackend()._build_sg_mail(msg)
         self.assertEqual(
             mail, {
                 'content': [{
                     'value': '',
                     'type': 'text/plain'
                 }],
                 'personalizations': [{}],
                 'reply_to': {
                     'email': '*****@*****.**'
                 },
                 'from': {
                     'email': 'webmaster@localhost'
                 },
                 'subject': ''
             })
     # Test using the reply_to attribute.
     msg = EmailMessage(reply_to=('*****@*****.**', ))
     with self.settings(SENDGRID_API_KEY='test_key'):
         mail = SendGridBackend()._build_sg_mail(msg)
         self.assertEqual(
             mail, {
                 'content': [{
                     'value': '',
                     'type': 'text/plain'
                 }],
                 'personalizations': [{}],
                 'reply_to': {
                     'email': '*****@*****.**'
                 },
                 'from': {
                     'email': 'webmaster@localhost'
                 },
                 'subject': ''
             })
     # Test using "name <email>" format.
     msg = EmailMessage(
         reply_to=('Andrii Soldatenko <*****@*****.**>', ))
     with self.settings(SENDGRID_API_KEY='test_key'):
         mail = SendGridBackend()._build_sg_mail(msg)
         self.assertEqual(
             mail, {
                 'content': [{
                     'value': '',
                     'type': 'text/plain'
                 }],
                 'personalizations': [{}],
                 'reply_to': {
                     'name': 'Andrii Soldatenko',
                     'email': '*****@*****.**'
                 },
                 'from': {
                     'email': 'webmaster@localhost'
                 },
                 'subject': ''
             })
Beispiel #14
0
def reset_password(request):
    if request.method == 'POST':
        is_send_mail = request.POST.get('is_send_mail')
        if is_send_mail == '1':
            email = request.POST.get('email')
            user = User().find_one({'email': email})

            if user is None:
                return JsonResponse({'code': 0, 'msg': 'Email not exists!'})

            account_activation_token = create_token(
                {'user_id': str(user['_id'])}, 60)
            mail_subject = 'Please reset your password.'
            current_site = get_current_site(request)
            message = render_to_string(
                'acc_active_email.html', {
                    'user_name': user['username'],
                    'domain': current_site.domain,
                    'token': account_activation_token,
                    'reset_password': 1
                })
            email = EmailMessage(mail_subject, message, to=[email])
            email.send()
            return JsonResponse({
                'code': 1,
                'msg': 'The email send successfully!'
            })

        else:
            password = request.POST.get('password')
            token = request.POST.get('token')
            if not all([password, token]):
                return JsonResponse({
                    'code': 0,
                    'msg': 'password or token is None!'
                })
            acc, payload = authenticate_token(token)
            if acc == 0:
                return HttpResponse(payload)
            else:
                user = User().find_one({
                    '_id': ObjectId(payload['user_id']),
                    'is_active': 1
                })
                if user is None:
                    return JsonResponse({
                        'code':
                        0,
                        'msg':
                        'User not exist or Email not activated!'
                    })
                User().collection.update_one(
                    {'_id': ObjectId(payload['user_id'])},
                    {"$set": {
                        'password': get_password(password)
                    }})
            return JsonResponse({
                'code':
                1,
                "msg":
                "Reset password Successfully, Please Login!"
            })
Beispiel #15
0
    def save(self, request, commit=True):
        instance = super(VendorUserForm, self).save(commit=False)
        vendor = None
        company = None

        if 'company_id' in request.session:
            try:
                vendor_user = CompanyVendor.objects.filter(
                    company_id=request.user['company_id']).last()
            except:
                vendor_user = None
        else:
            try:
                vendor_user = CompanyVendor.objects.filter(
                    user=request.user).last()
            except:
                vendor_user = None

        if vendor_user:
            # if vendor user has a detail
            vendor = vendor_user.vendor
            company = vendor_user.company

        first_name = self.cleaned_data.get('first_name')
        last_name = self.cleaned_data.get('last_name')
        email = self.cleaned_data.get('email')
        mobile_number = self.cleaned_data.get('mobile_number')
        status = self.cleaned_data.get('status')
        user_type = int(self.cleaned_data.get('user_type'))

        if status == 'True':
            status = True
        else:
            status = False

        if not self.instance.pk:
            # create
            if commit:
                password = User.objects.make_random_password()
                user = User.objects.create(first_name=first_name,
                                           last_name=last_name,
                                           email=email,
                                           password=make_password(password),
                                           user_type=user_type,
                                           mobile_number=mobile_number,
                                           is_active=status)
                instance.user = user
                instance.owner = request.user
                instance.vendor = vendor
                instance.company = company
                instance.user.save()
                instance.save()

                html_message = "Dear " + first_name + ", <br><br>Welcome to Plat X. We are delighted to have you onboard !<br><br>Please find your first time login credentials :<br>" + "Your email: " + email + "<br>Password: "******" <br>After your first login please change your password.<br><br>If you have any questions we are here to help – please drop in an email to [email protected]<br><br>Cheers,<br>Team XYZ<br>"
                email_message = EmailMessage('Password Information',
                                             html_message,
                                             settings.EMAIL_HOST_USER, [],
                                             [email])
                email_message.content_subtype = "html"
                email_message.send()
        else:
            # update
            if commit:
                instance.user.first_name = first_name
                instance.user.last_name = last_name
                instance.user.email = email
                instance.user.mobile_number = mobile_number
                instance.user.user_type = user_type
                instance.user.is_active = status
                instance.user.save()
                instance.save()

        return instance
Beispiel #16
0
 def save_model(self, request, obj, form, change=True):
     EmailMessage('Greetings from a created object',
                  'I hereby inform you that some user created me',
                  '*****@*****.**', ['*****@*****.**']).send()
     return super(ArticleAdmin, self).save_model(request, obj, form, change)
def smart_home_manager():
    """The function polls the remote smart home server, processes the received data,
    takes managerial decisions and makes changes to the system."""
    controller_data = requests.get(url, headers=headers).json().get("data")
    controller_data = {x["name"]: x for x in controller_data}
    payload = {"controllers": []}
    if controller_data["leak_detector"]["value"]:
        # if the sensor shows a leak - we shut off hot and cold water
        if controller_data["cold_water"]["value"]:
            payload["controllers"].append({
                "name": "cold_water",
                "value": False
            })

        if controller_data["hot_water"]["value"]:
            payload["controllers"].append({
                "name": "hot_water",
                "value": False
            })
        email = EmailMessage(
            'leak detector',
            'text',
            settings.EMAIL_HOST,
            [settings.EMAIL_RECEPIENT],
        )
        email.send(fail_silently=False)

    # if there is no cold water - turn off the boiler and the washing machine
    if (controller_data["leak_detector"]["value"]
            or not controller_data["cold_water"]["value"]):
        if controller_data["boiler"]["value"]:
            payload["controllers"].append({"name": "boiler", "value": False})
        if controller_data["washing_machine"]["value"] in ("on", "broken"):
            payload["controllers"].append({
                "name": "washing_machine",
                "value": "off"
            })

    boiler_temperature = controller_data["boiler_temperature"]["value"]
    hot_water_target_temperature = Setting.objects.get(
        controller_name="hot_water_target_temperature").value

    bedroom_temperature = controller_data["bedroom_temperature"]["value"]
    bedroom_target_temperature = Setting.objects.get(
        controller_name="bedroom_target_temperature").value

    if controller_data["smoke_detector"]["value"]:
        # If the smoke sensor has worked, turn off the air conditioner, boiler and light
        if controller_data["air_conditioner"]["value"]:
            payload["controllers"].append({
                "name": "air_conditioner",
                "value": False
            })
        if controller_data["bathroom_light"]["value"]:
            payload["controllers"].append({
                "name": "bathroom_light",
                "value": False
            })
        if controller_data["bedroom_light"]["value"]:
            payload["controllers"].append({
                "name": "bedroom_light",
                "value": False
            })
        if controller_data["boiler"]["value"]:
            payload["controllers"].append({"name": "boiler", "value": False})
        if controller_data["washing_machine"]["value"] in ("on", "broken"):
            payload["controllers"].append({
                "name": "washing_machine",
                "value": "off"
            })

    can_turn_on = {
        "boiler":
        controller_data["cold_water"]["value"]
        and not controller_data["leak_detector"]["value"]
        and not controller_data["smoke_detector"]["value"]
        and not controller_data["boiler"],
        "air_conditioner":
        not controller_data["smoke_detector"]["value"],
    }

    if (boiler_temperature <
            hot_water_target_temperature * 0.9) and can_turn_on["boiler"]:
        payload["controllers"].append({"name": "boiler", "value": True})

    if boiler_temperature > hot_water_target_temperature * 1.1:
        payload["controllers"].append({"name": "boiler", "value": False})

    if (bedroom_temperature < bedroom_target_temperature *
            0.9) and can_turn_on["air_conditioner"]:
        payload["controllers"].append({
            "name": "air_conditioner",
            "value": False
        })

    if bedroom_temperature > bedroom_target_temperature * 1.1:
        payload["controllers"].append({
            "name": "air_conditioner",
            "value": True
        })

    outdoor_light = controller_data["outdoor_light"]["value"]
    bedroom_light = controller_data["bedroom_light"]["value"]

    # open and close the curtains depending on the light sensor
    if controller_data["curtains"]["value"] == "slightly_open":
        pass
    else:
        if outdoor_light < 50 and not bedroom_light:
            if controller_data["curtains"]["value"] == 'close':
                payload["controllers"].append({
                    "name": "curtains",
                    "value": "open"
                })
        elif outdoor_light > 50 or bedroom_light:
            if controller_data["curtains"]["value"] == 'open':
                payload["controllers"].append({
                    "name": "curtains",
                    "value": "close"
                })

    if payload["controllers"]:
        unique = []
        for item in payload["controllers"]:
            if item not in unique:
                unique.append(item)
        payload["controllers"] = unique
        requests.post(url, headers=headers, json=payload)
Beispiel #18
0
 def mail_admin(self, request, selected):
     EmailMessage('Greetings from a ModelAdmin action',
                  'This is the test email from an admin action',
                  '*****@*****.**', ['*****@*****.**']).send()
Beispiel #19
0
    my_password = '******'
    my_use_tls = True
    fail_silently = False
    connection = get_connection(host=my_host,
                                port=my_port,
                                username=my_username,
                                password=my_password,
                                use_tls=my_use_tls)

    send_mail(subject,
              message,
              'mpod@%s' % domain, [user.email],
              connection=connection)
    # or
    EmailMessage(subject,
                 message,
                 'mpod@%s' % domain, [user.email],
                 connection=connection).send(fail_silently=False)

    backend = EmailBackend(host=my_host,
                           port=my_port,
                           username=my_username,
                           password=my_password,
                           use_tls=my_use_tls,
                           fail_silently=fail_silently)

    email = EmailMessage(subject,
                         message,
                         'mpod@%s' % domain, [user.email],
                         connection=backend)
    email.send()
Beispiel #20
0
def external_mail(modeladmin, request, selected):
    EmailMessage('Greetings from a function action',
                 'This is the test email from a function action',
                 '*****@*****.**', ['*****@*****.**']).send()
Beispiel #21
0
        if '.csv' in ff and 'summary' in ff: # the creation time judgement need to coordinate with the frequency of running this script
            now = timezone.make_naive(timezone.localtime())
            delta_time = (now - datetime.datetime.fromtimestamp(os.path.getctime(ff)))
            if delta_time.total_seconds() <= 15*60:
                ff_id = getid(ff)
                if OptTask.objects.filter(pk = ff_id).exists():
                    task = OptTask.objects.get(pk = ff_id)
                    task.task_status = 'Completed'
                    task.save()
                    ff_user = task.user
                    toemail = ff_user.email
                    content = 'Your Task %s is Completed!' %task.task_name
                    message = EmailMessage(
                        'No Reply - Notification',
                        content,
                        '*****@*****.**',
                        [toemail])
                    message.send(fail_silently = False)   # send email to notify user
                    old_result = OptTaskResults.objects.filter(task = task)
                    for i in range(len(old_result)):
                        old_result[i].delete()
                    new_result = OptTaskResults(task = task)
                    summary = ''
                with open(ff, newline='') as csvfile:
                    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
                    for row in spamreader:
                        summary += ': '.join(row)
                        summary += '\n'
                new_result.summary = summary            # obtain the summary information
                new_result.save()
Beispiel #22
0
    def form_valid(self, form):
        # username = form.cleaned_data['username']
        prenom = form.cleaned_data['prenom']
        nom = form.cleaned_data['nom']
        email = form.cleaned_data['email']
        password1 = form.cleaned_data['password1']
        password2 = form.cleaned_data['password2']
        if password1 != password2:
            form.add_error('password2', _('Passwords do not match'))
            return super(RegisterView, self).form_invalid(form)

        # hack pour faire un fake username
        username = email.replace('@', '_at_')
        # Si username déjà utilisé, erreur :
        if len(User.objects.filter(username__exact=username)):
            err = _('A user has already the same firstname and lastname')
            form.add_error('prenom', err)
            form.add_error('nom', err)
            return super(RegisterView, self).form_invalid(form)
        # Si email déjà utilisé, erreur :
        if len(User.objects.filter(email__exact=email)):
            form.add_error('email', _('This email is already used'))
            return super(RegisterView, self).form_invalid(form)

        # Création de l'utilisateur :
        try:
            user = User.objects.create_user(username=username,
                                            email=email,
                                            password=password1,
                                            first_name=prenom,
                                            last_name=nom)
        except IntegrityError:
            form.add_error('username', _('This username is already used'))
            return super(RegisterView, self).form_invalid(form)

        user.is_active = False
        user.save()
        rand_str = str(uuid.uuid4())
        p = Personne(
            user=user,
            confirmation_code=rand_str,
            champs_supplementaires='',
            # Si on s'enregistre ici = beta testeur
            is_beta_tester=True)
        p.save()

        site_web = "{}://{}".format(self.request.scheme,
                                    self.request.META['HTTP_HOST'])
        if 'development' not in self.request.META['HTTP_HOST']:
            EmailMessage(
                subject=_('Thanks again for signing up.'),
                body=_('We sincerely hope that you will appreciate this new '
                       'and innovative international social network, '
                       'for which the operative word is “sharing”\n'
                       "To validate your registration, "
                       "click on the following link:\n{}{}").format(
                           site_web,
                           reverse('register_validate',
                                   kwargs={'rand_str': rand_str})),
                from_email='*****@*****.**',
                to=[form.cleaned_data['email']],
                bcc=['*****@*****.**']).send()

        self.request.session['message'] = [
            _('Thanks for signing up!'),
            _('An email confirmation has been sent to you.'),
            _('Please check your mailbox in order to activate your account, '
              'via the link provided, and start the adventure!'),
            _('Click here to hide this message')
        ]
        return super(RegisterView, self).form_valid(form)
Beispiel #23
0
def NA_EmailData(request):
    if request.method == "POST":
        subject = request.POST.get('subject', '')
        message = request.POST.get('message', '')
        getUser = request.user.username
        to = request.POST.get('to', '')
        type_report = request.POST['type_report']
        if subject and message and to:
            try:
                email = EmailMessage(
                    subject=subject,
                    body="<"+str(getUser)+">" + message,
                    from_email=getUser,
                    to=[to]
                    )
                import glob
                for name in glob.glob(settings.STATIC_ROOT + '/app/Upload/email_data/'+getUser+'/*'): #get all file in his/her directory
                    email.attach_file(name)
                try:
                    email.send()
                except SMTPException as e:
                    return HttpResponse(e, status=403)
                else:
                    result_all = {}
                    if type_report == 'tabular_data':
                        data_report_tabular = request.POST['data_report_tabular']
                        if 'Employee' in data_report_tabular.split(','):
                            total_empl = Employee.objects.count()
                            result_all['tabular_data_employee'] = str(total_empl) + ' Employees' if total_empl > 1 else str(total_empl) + ' Employee'
                        if 'Supplier' in data_report_tabular.split(','):
                            total_supl = NASupplier.objects.count()
                            result_all['tabular_data_supplier'] = str(total_supl) + ' Suppliers' if total_supl > 1 else str(total_supl) + ' Supplier'
                    elif type_report == 'biodata':
                        data_report_empl = request.POST['data_report_empl']
                        data_report_supl = request.POST['data_report_supl']
                        len_report_empl = int(len(data_report_empl.split(',')))
                        len_report_supl = int(len(data_report_supl.split(',')))
                        if data_report_empl != 'none':
                            result_empl = []
                            if len_report_empl > 1:
                                bio_empl = Employee.objects.filter(idapp__in=(data_report_empl.split(',')))\
                                    .values('idapp', 'nik', 'employee_name', 'typeapp', 'jobtype', 'gender', 'status', 'telphp', 'territory', 'descriptions','inactive')
                            elif len_report_empl == 1:
                                bio_empl = Employee.objects.retriveData(data_report_empl)\
                                    .values('idapp', 'nik', 'employee_name', 'typeapp', 'jobtype', 'gender', 'status', 'telphp', 'territory', 'descriptions','inactive')
                            for i in bio_empl:
                                result_empl.append(i)
                            result_all['bio_employee'] = result_empl
                        if data_report_supl != 'none':
                            result_supl = []
                            if len_report_supl > 1:
                                bio_supl = NASupplier.objects.filter(suppliercode__in=(data_report_supl.split(',')))\
                                    .values('suppliercode', 'suppliername', 'address', 'telp', 'hp', 'contactperson','inactive')
                            elif len_supl_empl == 1:
                                bio_supl = NASupplier.objects.retriveData(data_report_supl)\
                                    .values('suppliercode', 'suppliername', 'address', 'telp', 'hp', 'contactperson','inactive')
                            for i in bio_supl:
                                result_supl.append(i)
                            result_all['bio_supplier'] = result_supl

                    LogEvent.objects.create(nameapp='Send Email', typeapp='P', descriptionsapp={
                            'emailData':[
                                to,
                                getUser,
                                subject,
                                message,
                                'Tabular Data' if type_report == 'tabular_data' else 'Biodata',
                                result_all
                                ]
                            }, createdby=str(request.user.username))

                import os
                for name in glob.glob(settings.STATIC_ROOT + '/app/Upload/email_data/'+getUser+'/*.pdf'):
                    os.remove(name)
            except BadHeaderError: #Preventing header injection from hacker(commonly called HAKEL) SHIT .. .
                return HttpResponse('Invalid header found.')
        return HttpResponse('Success !!!')
    return render(request, 'app/MasterData/NA_F_EmailData.html')
Beispiel #24
0
def send_email_user_mentions(comment_id,
                             called_from,
                             domain="demo.django-crm.io",
                             protocol="http"):
    """ Send Mail To Mentioned Users In The Comment """
    comment = Comment.objects.filter(id=comment_id).first()
    if comment:
        comment_text = comment.comment
        comment_text_list = comment_text.split()
        recipients = []
        for comment_text in comment_text_list:
            if comment_text.startswith("@"):
                if comment_text.strip("@").strip(",") not in recipients:
                    if User.objects.filter(
                            username=comment_text.strip("@").strip(","),
                            is_active=True).exists():
                        email = (User.objects.filter(
                            username=comment_text.strip("@").strip(
                                ",")).first().email)
                        recipients.append(email)

        context = {}
        context["commented_by"] = comment.commented_by
        context["comment_description"] = comment.comment
        if called_from == "accounts":
            context["url"] = (
                protocol + "://" + domain +
                reverse("accounts:view_account", args=(comment.account.id, )))
            subject = "New comment on Account. "
        elif called_from == "contacts":
            context["url"] = (
                protocol + "://" + domain +
                reverse("contacts:view_contact", args=(comment.contact.id, )))
            subject = "New comment on Contact. "
        elif called_from == "leads":
            context["url"] = (
                protocol + "://" + domain +
                reverse("leads:view_lead", args=(comment.lead.id, )))
            subject = "New comment on Lead. "
        elif called_from == "opportunity":
            context["url"] = (protocol + "://" + domain + reverse(
                "opportunity:opp_view", args=(comment.opportunity.id, )))
            subject = "New comment on Opportunity. "
        elif called_from == "cases":
            context["url"] = (
                protocol + "://" + domain +
                reverse("cases:view_case", args=(comment.case.id, )))
            subject = "New comment on Case. "
        elif called_from == "tasks":
            context["url"] = (
                protocol + "://" + domain +
                reverse("tasks:task_detail", args=(comment.task.id, )))
            subject = "New comment on Task. "
        elif called_from == "invoices":
            context["url"] = (protocol + "://" + domain + reverse(
                "invoices:invoice_details", args=(comment.invoice.id, )))
            subject = "New comment on Invoice. "
        elif called_from == "events":
            context["url"] = (
                protocol + "://" + domain +
                reverse("events:detail_view", args=(comment.event.id, )))
            subject = "New comment on Event. "
        else:
            context["url"] = ""
        # subject = 'Django CRM : comment '
        blocked_domains = BlockedDomain.objects.values_list("domain",
                                                            flat=True)
        blocked_emails = BlockedEmail.objects.values_list("email", flat=True)
        if recipients:
            for recipient in recipients:
                if (recipient
                        not in blocked_emails) and (recipient.split("@")[-1]
                                                    not in blocked_domains):
                    recipients_list = [
                        recipient,
                    ]
                    context["mentioned_user"] = recipient
                    html_content = render_to_string("comment_email.html",
                                                    context=context)
                    msg = EmailMessage(
                        subject,
                        html_content,
                        from_email=comment.commented_by.email,
                        to=recipients_list,
                    )
                    msg.content_subtype = "html"
                    msg.send()
Beispiel #25
0
def sign_up(request):
    if not settings.RELATE_REGISTRATION_ENABLED:
        raise SuspiciousOperation(_("self-registration is not enabled"))

    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            if get_user_model().objects.filter(
                    username=form.cleaned_data["username"]).count():
                messages.add_message(
                    request, messages.ERROR,
                    _("A user with that username already exists."))

            else:
                email = form.cleaned_data["email"]
                user = get_user_model()(email=email,
                                        username=form.cleaned_data["username"])

                user.set_unusable_password()
                user.status = user_status.unconfirmed
                user.sign_in_key = make_sign_in_key(user)
                user.save()

                from relate.utils import render_email_template
                message = render_email_template(
                    "course/sign-in-email.txt", {
                        "user":
                        user,
                        "sign_in_uri":
                        request.build_absolute_uri(
                            reverse("relate-reset_password_stage2",
                                    args=(
                                        user.id,
                                        user.sign_in_key,
                                    )) + "?to_profile=1"),
                        "home_uri":
                        request.build_absolute_uri(reverse("relate-home"))
                    })

                from django.core.mail import EmailMessage
                msg = EmailMessage(
                    string_concat("[%s] " % _(get_site_name()),
                                  _("Verify your email")), message,
                    getattr(settings, "NO_REPLY_EMAIL_FROM",
                            settings.ROBOT_EMAIL_FROM), [email])

                from relate.utils import get_outbound_mail_connection
                msg.connection = (get_outbound_mail_connection("no_reply")
                                  if hasattr(settings, "NO_REPLY_EMAIL_FROM")
                                  else get_outbound_mail_connection("robot"))
                msg.send()

                messages.add_message(
                    request, messages.INFO,
                    _("Email sent. Please check your email and click "
                      "the link."))

                return redirect("relate-home")
        else:
            if ("email" in form.errors
                    and "That email address is already in use."
                    in form.errors["email"]):
                messages.add_message(
                    request, messages.ERROR,
                    _("That email address is already in use. "
                      "Would you like to "
                      "<a href='%s'>reset your password</a> instead?") %
                    reverse("relate-reset_password"))

    else:
        form = SignUpForm()

    return render(request, "generic-form.html", {
        "form_description": _("Sign up"),
        "form": form
    })
Beispiel #26
0
 def send_email(data):
     email=EmailMessage(
         subject=data['email_subject'], to=[data['to_email']], body=data['email_body']
     ,)
     email.send()
Beispiel #27
0
def sign_in_by_email(request):
    if not settings.RELATE_SIGN_IN_BY_EMAIL_ENABLED:
        messages.add_message(request, messages.ERROR,
                             _("Email-based sign-in is not being used"))
        return redirect("relate-sign_in_choice")

    if request.method == 'POST':
        form = SignInByEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            user, created = get_user_model().objects.get_or_create(
                email__iexact=email,
                defaults=dict(username=email, email=email))

            if created:
                user.set_unusable_password()
                user.status = user_status.unconfirmed

            user.sign_in_key = make_sign_in_key(user)
            user.save()

            from relate.utils import render_email_template
            message = render_email_template(
                "course/sign-in-email.txt", {
                    "user":
                    user,
                    "sign_in_uri":
                    request.build_absolute_uri(
                        reverse("relate-sign_in_stage2_with_token",
                                args=(
                                    user.id,
                                    user.sign_in_key,
                                ))),
                    "home_uri":
                    request.build_absolute_uri(reverse("relate-home"))
                })
            from django.core.mail import EmailMessage
            msg = EmailMessage(
                _("Your %(relate_site_name)s sign-in link") %
                {"relate_site_name": _(get_site_name())}, message,
                getattr(settings, "NO_REPLY_EMAIL_FROM",
                        settings.ROBOT_EMAIL_FROM), [user.email])

            from relate.utils import get_outbound_mail_connection
            msg.connection = (get_outbound_mail_connection("no_reply")
                              if hasattr(settings, "NO_REPLY_EMAIL_FROM") else
                              get_outbound_mail_connection("robot"))
            msg.send()

            messages.add_message(
                request, messages.INFO,
                _("Email sent. Please check your email and click the link."))

            return redirect("relate-home")
    else:
        form = SignInByEmailForm()

    return render(request, "course/login-by-email.html", {
        "form_description": "",
        "form": form
    })
Beispiel #28
0
def render_settings(request):
    user = User.objects.get(pk=request.user.id)
    delete_account_request = False
    try:
        delete_request = DeleteAccountRequest.objects.filter(user=user).first()
        if delete_request:
            delete_account_request = True
    except ObjectDoesNotExist:
        delete_account_request = False
    try:
        settings = UserProfile.objects.get(user=user)
        user_groups = user.groups.all()
        group_list = []
        for g in user_groups:
            group_list.append({
                'id':
                g.id,
                'name':
                g.name,
                'receive_updates':
                settings.get_group_notification_preference(g.id)
            })
    except UserProfile.DoesNotExist:
        settings = None
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        if settings:
            settings_form = SettingsForm(request.POST, instance=settings)
        else:
            settings_form = SettingsForm(request.POST)
        if user_form.is_valid() and settings_form.is_valid():
            user = user_form.save()
            settings = settings_form.save(commit=False)
            settings.user_id = request.user.id
            settings.save()
            settings_form.save_m2m()
            # update the interface language
            if settings.interface_lang:
                translation.activate(settings.interface_lang)
                request.LANGUAGE_CODE = translation.get_language()

            # get group update settings
            for g in group_list:
                gets_notif = True if request.POST.get(
                    'group_notif_' + str(g.get('id'))) else False
                settings.set_group_notification_preference(
                    g.get('id'), gets_notif)
                g['receive_updates'] = gets_notif

            # check for delete account requests
            if request.POST.get('delete_account_option') == 'delete':
                DeleteAccountRequest.objects.create(user=user)
                delete_account_request = True
                settings.set_active(False)
                ctx = {
                    "user": user,
                }
                html = render_to_string('emails/delete_account_request.html',
                                        ctx)
                email = EmailMessage('Delete user account request', html,
                                     constance.config.NO_REPLY_EMAIL,
                                     [config.ACTIVATE_USER_EMAIL])
                email.content_subtype = "html"
                email.send()
            else:
                if delete_account_request:
                    DeleteAccountRequest.objects.filter(user=user).delete()
                    delete_account_request = False
                    settings.set_active(True)
            messages.add_message(request, messages.SUCCESS,
                                 'Profile Update Successful.')
    else:
        user_form = UserForm(instance=request.user)
        settings_form = SettingsForm(instance=settings)

    errors = dict(user_form.errors)
    errors.update(settings_form.errors)

    interest_types = {
        'languages': [(lang.id, lang.name) for lang in Language.objects.all()],
        'interests':
        [(interest.id, interest.name) for interest in Interest.objects.all()],
        'regions':
        [(region.id, region.name) for region in Region.objects.all()]
    }

    return render_to_response('users/user_settings_v2.html', {
        'settings_form': settings_form,
        'user_form': user_form,
        'group_list': group_list,
        'interest_types': interest_types,
        'has_password': user.has_usable_password(),
        'errors': errors,
        'delete_account_request': delete_account_request,
    },
                              context_instance=RequestContext(request))
def _send_user_digest(namespace_info, from_timestamp, to_timestamp, user_id,
                      email, first_name, last_name, subject, from_email, unread_only=True):
    """
    This will send a digest of unread notifications to a given user. Note, it is assumed here
    that the user's preference has already been checked. namespace_info will contain
    a 'display_name' entry which will be a human readable string that can be put
    in the digest email
    """

    # query all unread notifications for this user since the timestamp
    notifications = get_notifications_for_user(
        user_id,
        filters={
            'read': not unread_only,
            'unread': True,
            'start_date': from_timestamp,
            'end_timestamp': to_timestamp,
            'namespace': namespace_info['namespace'],
        },
        options={
            'select_related': True,  # make sure we do JOINs on the initial query
        }
    )

    notification_groups = render_notifications_by_type(notifications)

    # As an option, don't send an email at all if there are no
    # unread notifications
    if not notification_groups and const.NOTIFICATION_DONT_SEND_EMPTY_DIGEST:
        log.debug('Digest email for {email} is empty. Not sending...'.format(email=email))
        return 0

    context = {
        'namespace_display_name': namespace_info['display_name'],
        'grouped_user_notifications': notification_groups
    }

    # render the notifications html template
    notifications_html = render_to_string("django/digests/unread_notifications_inner.html", context)

    # create the image dictionary to store the
    # img_path, unique id and title for the image.
    branded_logo = dict(title='Logo', path=const.NOTIFICATION_BRANDED_DEFAULT_LOGO, cid=str(uuid.uuid4()))

    context = {
        'branded_logo': branded_logo['cid'],
        'user_first_name': first_name,
        'user_last_name': last_name,
        'namespace': namespace_info['display_name'],
        'count': len(notifications),
        'rendered_notifications': notifications_html
    }
    # render the mail digest template.
    email_body = with_inline_css(
        render_to_string("django/digests/branded_notifications_outer.html", context)
    )

    html_part = MIMEMultipart(_subtype='related')
    html_part.attach(MIMEText(email_body, _subtype='html'))
    logo_image = attach_image(branded_logo, 'Header Logo')
    if logo_image:
        html_part.attach(logo_image)

    log.info('Sending Notification Digest email to {email}'.format(email=email))

    # do a formatting pass on the email subject in case we need
    # to also present the namespace display_name
    subject = subject.format(display_name=namespace_info['display_name'])

    msg = EmailMessage(subject, None, from_email, [email])
    msg.attach(html_part)
    msg.send()

    return 1
Beispiel #30
0
def add_aliquot_node(aliquot):
    try:
        father_gen_id = aliquot.id_explant.id_mouse.id_genealogy
        groupsToSend = list()
        gdb = neo4j.GraphDatabaseService(settings.GRAPH_DB_URL)
        if gdb.get_indexed_node('node_auto_index', 'identifier',
                                aliquot.id_genealogy):
            return
        else:
            batch = neo4j.WriteBatch(gdb)

            nodes = {}
            print aliquot.id_genealogy
            g = GenealogyID(aliquot.id_genealogy)
            altype = 'c' + g.get2Derivation() if g.is2Derivation(
            ) else g.getArchivedMaterial()
            print altype
            dateAl = datetime.datetime.now()
            nodes[g.getGenID()] = {
                'type': 'Aliquot',
                'altype': altype,
                'id': aliquot.id,
                'relationships': {},
                'nodeid': None,
                'date': str(dateAl)
            }

            nodes[father_gen_id] = {
                'type': 'Biomouse',
                'nodeid': None,
                'wg': {},
                'relationships': {}
            }
            nodes[father_gen_id]['nodeid'] = gdb.get_indexed_node(
                'node_auto_index', 'identifier', father_gen_id)

            query = "START n=node:node_auto_index(identifier='" + father_gen_id + "') match (w:WG)-[r]->n WHERE not has(r.endDate) RETURN id(r), type(r), w.identifier, id(w)"
            data, metadata = cypher.execute(gdb, query)
            if len(data) > 0:
                for d in data:
                    nodes[father_gen_id]['wg'][d[0]] = {
                        'nodeid':
                        gdb.get_indexed_node('node_auto_index', 'identifier',
                                             d[2]),
                        'rel_type':
                        d[1],
                        'name':
                        d[2]
                    }

            #relsWg = list(graph_db.match(end_node=nodes[father_gen_id]['nodeid']), rel_type="OwnsData") # e i paramteri associati? e i nodi attaccati?
            fatherNode = nodes[father_gen_id]

            nodes[g.getGenID()]['relationships'][father_gen_id] = {
                'type': 'generates',
                'app': 'explant'
            }

            buildSemanticNode(g.getGenID(), 'Aliquot', None, nodes, dateAl)

            batch = neo4j.WriteBatch(gdb)

            for n, nInfo in nodes.items():
                flagInsert = True
                print n, nInfo
                if nInfo['nodeid'] is None:
                    nInfo['nodeid'] = batch.create(node(identifier=n))
                    labels = setLabels(nInfo['type'], nInfo['altype'])
                    batch.add_labels(nInfo['nodeid'], *labels)
                    if nInfo['type'] in ['Biomouse', 'Aliquot', 'Collection']:
                        for wg, wgInfo in fatherNode['wg'].items():
                            batch.create(
                                rel(wgInfo['nodeid'], wgInfo['rel_type'],
                                    nInfo['nodeid'], {
                                        'startDate': nInfo['date'],
                                        'endDate': None
                                    }))

            for dest, destInfo in nodes.items():
                for source, relInfo in destInfo['relationships'].items():
                    if relInfo['app']:
                        batch.create(
                            rel(nodes[source]['nodeid'], relInfo['type'],
                                destInfo['nodeid'], {'app': relInfo['app']}))
                    else:
                        batch.create(
                            rel(nodes[source]['nodeid'], relInfo['type'],
                                destInfo['nodeid']))

            results = batch.submit()
            batch.clear()

    except Exception, e:
        print 'Error graph', e
        subject = 'ERROR DURING SAVING ALIQUOT EXPLANTED IN GRAPH DB'
        message = 'Error saving genid: ', str(aliquot.id_genealogy)
        toList = list()
        email = EmailMessage(subject, message, '', toList, [], '', '', '', [])
        email.send(fail_silently=False)