def send_confirmation(self, user): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + user.email).hexdigest() path = reverse("auth_confirm_email", args=[confirmation_key]) protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'http') port = getattr(settings, 'MY_SITE_PORT', '') activate_url = u"%s://%s%s%s" % (protocol, settings.SITE_DOMAIN, port and ':' + port or '', path) context = { "user": user, "activate_url": activate_url, "site_name": settings.SITE_NAME, "confirmation_key": confirmation_key, } subject = render_to_string("auth/email_confirmation_subject.txt", context) subject = "".join( subject.splitlines()) # remove superfluous line breaks message = render_to_string("auth/email_confirmation_message.txt", context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]) profile = user.get_profile() profile.email_verified = False profile.save() return self.create(user=user, sent=datetime.now(), confirmation_key=confirmation_key)
def create_invitation(self, email, invited_by): salt = sha_constructor(str(random.random())).hexdigest()[:5] if isinstance(email, unicode): email = email.encode('utf-8') invitation_key = sha_constructor(salt + email).hexdigest() return self.create(email=email, invitation_key=invitation_key, invited_by=invited_by)
def reset_activation_key(self): ''' 重新生成 activation_key ''' salt = sha_constructor(str(random.random())).hexdigest()[:5] if isinstance(self.email, unicode): email = self.email.encode('utf-8') self.activation_key = sha_constructor(salt + self.email).hexdigest()
def send_invitation(self, from_user, to_email, message): contact, created = Contact.objects.get_or_create(email=to_email, user=from_user) salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + to_email).hexdigest() accept_url = u"http://%s%s" % ( unicode(Site.objects.get_current()), reverse("friends_accept_join", args=(confirmation_key, )), ) ctx = { "SITE_NAME": settings.SITE_NAME, "CONTACT_EMAIL": settings.CONTACT_EMAIL, "user": from_user, "message": message, "accept_url": accept_url, } subject = render_to_string("friends/join_invite_subject.txt", ctx) email_message = render_to_string("friends/join_invite_message.txt", ctx) send_mail(subject, email_message, settings.DEFAULT_FROM_EMAIL, [to_email]) return self.create(from_user=from_user, contact=contact, message=message, status="2", confirmation_key=confirmation_key)
def create_inactive_user(self, username, email, password, site, send_email=True): """ Create a new, inactive ``User``, set the activation key and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. The activation key will be a SHA1 hash, generated from a combination of the username and a random salt. """ new_user = self.create_user(username, email, password) new_user.is_active = False salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt+new_user.username).hexdigest() new_user.activation_key = activation_key new_user.save() if send_email: new_user.send_activation_email(site) return new_user
def reset_activation_key (self): ''' 重新生成 activation_key ''' salt = sha_constructor(str(random.random())).hexdigest()[:5] if isinstance(self.email, unicode): email = self.email.encode('utf-8') self.activation_key = sha_constructor(salt+self.email).hexdigest()
def send_confirmation(self, email_address): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + email_address.email).hexdigest() current_site = Site.objects.get_current() # check for the url with the dotted view path try: path = reverse("emailconfirmation.views.confirm_email", args=[confirmation_key]) except NoReverseMatch: # or get path with named urlconf instead path = reverse("emailconfirmation_confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": email_address.user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } send_templated_email([email_address.user], "emails/emailconfirmation", context) return self.create(email_address=email_address, sent=now(), confirmation_key=confirmation_key)
def send_invitation(self, from_user, contact, to_email, message=None): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + to_email).hexdigest() accept_url = u"http://%s%s" % ( settings.WWW_HOST, reverse("acct_signup_key", args=(confirmation_key, )), ) ctx = { "SITE_NAME": unicode(Site.objects.get_current()), "CONTACT_EMAIL": settings.DEFAULT_FROM_EMAIL, "contact": contact, "email": to_email, "user": from_user, "actor": from_user.get_profile(), "message": message, "accept_url": accept_url, } # subject = render_to_string("friends/join_invite_subject.txt", ctx) # subject = subject.rstrip() # email_message = render_to_string("friends/join_invite_message.txt", ctx) send_email(to_email, 'join_invitation', ctx=ctx, skip_footer=True) # send_html_mail(subject, 'text message', email_message, settings.DEFAULT_FROM_EMAIL, [to_email]) # send_mail(subject, email_message, settings.DEFAULT_FROM_EMAIL, [to_email]) return self.create(from_user=from_user, contact=contact, message=message, status="2", confirmation_key=confirmation_key)
def send_confirmation(self, user): assert user.email from messages.models import Message self.filter(user=user).delete() salt = sha_constructor(str(random()) + settings.SECRET_KEY).hexdigest()[:5] confirmation_key = sha_constructor( salt + user.email.encode('utf-8')).hexdigest() try: current_site = Site.objects.get_current() except Site.DoesNotExist: return path = reverse("auth:confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = u'Please confirm your email address for %s' % current_site.name Meter('templated-emails-sent-by-type.email-address-confirmation').inc() send_templated_email_async(user, subject, "messages/email/email-confirmation.html", context) return self.create(user=user, sent=datetime.now(), confirmation_key=confirmation_key)
def init_activation(self, user): # The activation key is a SHA1 hash, generated from a combination of the username and a random salt salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt+user.username).hexdigest() registration_profile = self.create(user=user, activation_key=activation_key) return registration_profile.send_activation_email()
def send_confirmation(self, email_address): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + email_address.email).hexdigest() current_site = Site.objects.get_current() # check for the url with the dotted view path try: path = reverse("emailconfirmation.views.confirm_email", args=[confirmation_key]) except NoReverseMatch: # or get path with named urlconf instead path = reverse( "emailconfirmation_confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": email_address.user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } send_templated_email([email_address.user], "emails/emailconfirmation", context) return self.create( email_address=email_address, sent=now(), confirmation_key=confirmation_key)
def send_confirmation(self, user): assert user.email self.filter(user=user).delete() salt = sha_constructor(str(random())+settings.SECRET_KEY).hexdigest()[:5] confirmation_key = sha_constructor(salt + user.email).hexdigest() try: current_site = Site.objects.get_current() except Site.DoesNotExist: return path = reverse("auth:confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = u'Please confirm your email address for %s' % current_site.name message = render_to_string( "auth/email_confirmation_message.txt", context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]) return self.create( user=user, sent=datetime.now(), confirmation_key=confirmation_key)
def signup(request): if request.method == "POST": form = BetaSignupForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] salt = sha_constructor(str(random.random())).hexdigest()[:5] if isinstance(email, unicode): email = email.encode("utf-8") activation_key = sha_constructor(salt + email).hexdigest() subsribe_email = form.save(commit=False) subsribe_email.key = activation_key subsribe_email.save() preview_send_mail = getattr(settings, "PREVIEW_SEND_MAIL", True) if preview_send_mail: if Site._meta.installed: site = Site.objects.get_current() else: site = request.get_host() subject = render_to_string("preview/email_subject.txt", {"site": site}) message = render_to_string( "preview/email.txt", {"url": reverse("preview_unsignup", args=[activation_key]), "site": site} ) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [email], fail_silently=True) return redirect(reverse("preview_confirm")) else: form = BetaSignupForm() return render_to_response("preview/signup.html", {"form": form}, context_instance=RequestContext(request))
def send_confirmation(self, email_address): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + email_address.email).hexdigest() current_site = Site.objects.get_current() # check for the url with the dotted view path try: path = reverse("emailconfirmation.views.confirm_email", args=[confirmation_key]) except NoReverseMatch: # or get path with named urlconf instead path = reverse("emailconfirmation_confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": email_address.user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = render_to_string( "emailconfirmation/email_confirmation_subject.txt", context) # remove superfluous line breaks subject = "".join(subject.splitlines()) message = render_to_string( "emailconfirmation/email_confirmation_message.txt", context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [email_address.email], priority="high") return self.create(email_address=email_address, sent=datetime.now(), confirmation_key=confirmation_key)
def test_large_upload(self): tdir = tempfile.gettempdir() file1 = tempfile.NamedTemporaryFile(suffix=".file1", dir=tdir) file1.write('a' * (2 ** 21)) file1.seek(0) file2 = tempfile.NamedTemporaryFile(suffix=".file2", dir=tdir) file2.write('a' * (10 * 2 ** 20)) file2.seek(0) post_data = { 'name': 'Ringo', 'file_field1': file1, 'file_field2': file2, } for key in post_data.keys(): try: post_data[key + '_hash'] = sha_constructor(post_data[key].read()).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + '_hash'] = sha_constructor(post_data[key]).hexdigest() response = self.client.post('/file_uploads/verify/', post_data) self.assertEqual(response.status_code, 200)
def test_large_upload(self): tdir = tempfile.gettempdir() file1 = tempfile.NamedTemporaryFile(suffix=".file1", dir=tdir) file1.write('a' * (2**21)) file1.seek(0) file2 = tempfile.NamedTemporaryFile(suffix=".file2", dir=tdir) file2.write('a' * (10 * 2**20)) file2.seek(0) post_data = { 'name': 'Ringo', 'file_field1': file1, 'file_field2': file2, } for key in post_data.keys(): try: post_data[key + '_hash'] = sha_constructor( post_data[key].read()).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + '_hash'] = sha_constructor( post_data[key]).hexdigest() response = self.client.post('/file_uploads/verify/', post_data) self.assertEqual(response.status_code, 200)
def create_profile(self, user): salt = sha_constructor(str(random.random())).hexdigest()[:5] username = user.username if isinstance(username, unicode): username = username.encode('utf-8') activation_key = sha_constructor(salt+username).hexdigest() return self.create(user=user, activation_key=activation_key)
def send_confirmation(self, email_address): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + email_address.email).hexdigest() current_site = Site.objects.get_current() # check for the url with the dotted view path try: path = reverse("emailconfirmation.views.confirm_email", args=[confirmation_key]) except NoReverseMatch: # or get path with named urlconf instead path = reverse( "emailconfirmation_confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": email_address.user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = render_to_string( "emailconfirmation/email_confirmation_subject.txt", context) # remove superfluous line breaks subject = "".join(subject.splitlines()) message = render_to_string( "emailconfirmation/email_confirmation_message.txt", context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [email_address.email], priority="high") return self.create( email_address=email_address, sent=datetime.now(), confirmation_key=confirmation_key)
def get_value_for_datastore(self, model_instance): """ Extract the value from a model instance and convert it to a encrypted password that goes in the datastore. """ raw = super(self.__class__, self).get_value_for_datastore(model_instance) if raw is None: raise ValueError(_("Password can't be empty")) try: if len(raw) > 12: alg, seed, passw = raw.split('$') return raw# the password is encrypted except Exception: pass if len(raw) < 5: raise ValueError(_("Invalid password")) if re.search(r'[^a-zA-Z0-9]', raw): raise ValueError(_("Invalid password")) from random import random alg = "sha1" seed = sha_constructor(str(random()) + str(random())).hexdigest()[:5] passw = sha_constructor(seed + raw).hexdigest() return '%s$%s$%s' % (alg, seed, passw)
def send_confirmation(self, user): assert user.email self.filter(user=user).delete() salt = sha_constructor(str(random.random()) + settings.SECRET_KEY).hexdigest()[:5] confirmation_key = sha_constructor(salt + user.email.encode('utf8')).hexdigest() try: current_site = Site.objects.get_current() except Site.DoesNotExist: return path = reverse("accounts:confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = _(u'Please confirm your email address for %(site)s') % {'site': current_site.name} send_templated_email(user.email, subject, 'accounts/email_confirmation_message.html', context, fail_silently=settings.DEBUG) return self.create( user=user, sent=timezone.now(), confirmation_key=confirmation_key)
def send_invitation(self, from_user, contact, to_email, message=None): salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + to_email).hexdigest() accept_url = u"http://%s%s" % ( settings.WWW_HOST, reverse("acct_signup_key", args=(confirmation_key,)), ) ctx = { "SITE_NAME": unicode(Site.objects.get_current()), "CONTACT_EMAIL": settings.DEFAULT_FROM_EMAIL, "contact": contact, "email": to_email, "user": from_user, "actor": from_user.get_profile(), "message": message, "accept_url": accept_url, } # subject = render_to_string("friends/join_invite_subject.txt", ctx) # subject = subject.rstrip() # email_message = render_to_string("friends/join_invite_message.txt", ctx) send_email(to_email, 'join_invitation', ctx = ctx, skip_footer = True) # send_html_mail(subject, 'text message', email_message, settings.DEFAULT_FROM_EMAIL, [to_email]) # send_mail(subject, email_message, settings.DEFAULT_FROM_EMAIL, [to_email]) return self.create(from_user=from_user, contact=contact, message=message, status="2", confirmation_key=confirmation_key)
def send_confirmation(self, user): assert user.email self.filter(user=user).delete() salt = sha_constructor(str(random.random()) + settings.SECRET_KEY).hexdigest()[:5] confirmation_key = sha_constructor(salt + user.email).hexdigest() try: current_site = Site.objects.get_current() except Site.DoesNotExist: return path = reverse("accounts:confirm_email", args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = _(u'Please confirm your email address for %(site)s') % {'site': current_site.name} send_templated_email(user.email, subject, 'accounts/email_confirmation_message.html', context, fail_silently=settings.DEBUG) return self.create( user=user, sent=timezone.now(), confirmation_key=confirmation_key)
def save_form_data(self, instance, data): if data and self.width and self.height and isinstance(data, UploadedFile): content = self.resize_image(data.read(), width=self.width, height=self.height) salt = sha_constructor(str(random.random())).hexdigest()[:5] fname = sha_constructor(salt + settings.SECRET_KEY).hexdigest() + '.png' data = SimpleUploadedFile(fname, content, data.content_type) super(FramedImageField, self).save_form_data(instance, data)
def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy() form_data.update(request.FILES) for key, value in form_data.items(): if key.endswith('_hash'): continue if key + '_hash' not in form_data: continue submitted_hash = form_data[key + '_hash'] if isinstance(value, UploadedFile): new_hash = sha_constructor(value.read()).hexdigest() else: new_hash = sha_constructor(value).hexdigest() if new_hash != submitted_hash: return HttpResponseServerError() # Adding large file to the database should succeed largefile = request.FILES['file_field2'] obj = FileModel() obj.testfile.save(largefile.name, largefile) return HttpResponse('')
def nuevo_usuario(request): try: sendEmailTest() except: print "Error sending email" if request.method == "POST": formulario = RegisterForm(request.POST) if formulario.is_valid(): email_list = [] email_user = formulario.cleaned_data['email'] name_newuser = formulario.cleaned_data['username'] salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt+email_user).hexdigest() new_user = formulario.save() new_user.is_active = False new_user.save() from models import activation_keys activation_keys(id_user=new_user, email=email_user, activation_key= activation_key).save() email_list.append(str(email_user) + ",") try: title = "Bienvenido a DiaryCodes" contenido = "<strong>"+str(name_newuser)+"</strong> <br ><br> Te damos la bienvenida a DiaryCodes, solo falta un paso para activar tu cuenta. <br > Ingresa al siguiente link para activar tu cuenta: <a href='http://www.diarycodes.daiech.com/usuarios/activate/"+activation_key+"' >http://diarycodes.daiech.com/usuarios/activate/"+activation_key+"</a>" # print contenido sendEmail(email_list, title, contenido) except Exception, e: print "Exception mail: %s" % e return HttpResponseRedirect('/usuarios/ingresar',{},context_instance=RequestContext(request))
def create_profile(self, contact): salt = sha_constructor(str(random.random())).hexdigest()[:5] username = contact.user.username if isinstance(username, unicode): username = username.encode('utf-8') activation_key = sha_constructor(salt + username).hexdigest() return self.create(contact=contact, activation_key=activation_key)
def send_invitation(self, from_user, to_email, message=None): contact, _ = Contact.objects.get_or_create(email=to_email, owner=from_user) contact.type = "I" contact.save() salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + to_email).hexdigest() accept_url = u"http://%s%s" % ( unicode(Site.objects.get_current()), reverse("friends_accept_join", args=(confirmation_key,)), ) ctx = { "SITE_NAME": unicode(Site.objects.get_current()), "CONTACT_EMAIL": settings.CONTACT_EMAIL, "contact": contact, "user": from_user, "message": message, "accept_url": accept_url, } subject = render_to_string("friends/join_invite_subject.txt", ctx) email_message = render_to_string("friends/join_invite_message.txt", ctx) send_mail(subject, email_message, settings.DEFAULT_FROM_EMAIL, [to_email]) return self.create( from_user=from_user, contact=contact, message=message, status="2", confirmation_key=confirmation_key )
def create_invitation(self, to_user, from_user = None): """ Create an ``Invitation`` and returns it. The code for the ``Invitation`` will be a SHA1 hash, generated from a combination of the ``User``'s username and a random salt. """ kwargs = {'to_user': to_user} # Register from user if from_user: kwargs.update({'from_user': from_user}) date_invited = datetime.datetime.now() kwargs['date_invited'] = date_invited kwargs['expiration_date'] = date_invited + datetime.timedelta(getattr(settings, 'ACCOUNT_INVITATION_DAYS', 30)) salt = sha_constructor(str(random.random())).hexdigest()[:5] kwargs['code'] = sha_constructor("%s%s%s" % (datetime.datetime.now(), salt, to_user.username)).hexdigest() return self.create(**kwargs)
def save(self, user): contacts = list(self.cleaned_data.get("contacts", [])) if self.cleaned_data.get("email"): contact, created = Contact.objects.get_or_create(email=self.cleaned_data["email"], user=user) if contact not in contacts: contacts.append(contact) muaccount = MUAccount.objects.get(id=self.cleaned_data["muaccount"]) message = self.cleaned_data["message"] context = { "SITE_NAME": muaccount.name, "CONTACT_EMAIL": user.email or settings.CONTACT_EMAIL, "user": user, "message": message, } for contact in contacts: # BASED ON django-friends JoinInvitationManager's method 'send_invitation' contact, created = Contact.objects.get_or_create(email=contact.email, user=user) salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + contact.email).hexdigest() context["accept_url"] = muaccount.get_absolute_url("friends_accept_join", args=(confirmation_key,)) subject = render_to_string("friends/join_invite_subject.txt", context) email_message = render_to_string("friends/join_invite_message.txt", context) send_mail(subject, email_message, settings.DEFAULT_FROM_EMAIL, [contact.email]) join_request = JoinInvitation.objects.get_or_create( from_user=user, contact=contact, message=message, status="2", confirmation_key=confirmation_key ) user.message_set.create(message=_("Invitation to join sent to %(email)s") % {"email": contact.email})
def profile(request): """ Form for modifying and adding profile values """ if request.method == 'POST': form = ProfileForm(request.POST, instance = request.user) email = request.POST.get('email', '') if not email == '' and not email == request.user.email: #confirm the email salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + email).hexdigest() current_site = Site.objects.get_current() path = reverse('confirm_email', args=[confirmation_key]) activate_url = u"http://%s%s" % (unicode(current_site.domain), path) context = { "user": request.user, "activate_url": activate_url, "current_site": current_site, "confirmation_key": confirmation_key, } subject = render_to_string( "email_confirmation_subject.txt", context) # remove superfluous line breaks subject = "".join(subject.splitlines()) message = render_to_string( "email_confirmation_message.txt", context) print email send_mail(subject, message, getattr(settings, 'DEFAULT_FROM_EMAIL', 'do-not-reply@%s' % current_site), [email]) Email.objects.create( owner = request.user, email = email, email_is_verified = False, sent = datetime.now(), confirmation_key = confirmation_key) form.save() return HttpResponseRedirect(request.POST.get('next', '/')) else: form = ProfileForm(instance = request.user) next = request.GET.get('next', '/') return render_to_response('profile.html', {'form': form, 'next': next}, context_instance = RequestContext(request))
def register(request, template_name="account/register.html"): ''' This allows the anonymous user to become a registered user. This is the form used to register a new user and sends email with the action link with a time out. ''' if request.user.is_authenticated(): # They already have an account; don't let them register again return HttpResponseRedirect(reverse('YAAS.views.my_account')) if request.method == 'POST': postdata = request.POST.copy() page_title='Registration form' form = RegistrationForm(postdata) if form.is_valid(): # Build the activation key for their account human = True un = postdata.get('user_name','') pw = postdata.get('pass_word','') em = postdata.get('email','') fn = postdata.get('first_name','') ln = postdata.get('last_name','') pn = postdata.get('phone_number','') sx = postdata.get('sex','') salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt+un).hexdigest() key_expires = datetime.datetime.today() + datetime.timedelta(2) # Create and save their profile hashpw = extra.hashPassword(pw) new_profile = CustomUser.objects.create_user(username=un, email=em, password=hashpw) new_profile.is_active = False new_profile.first_name = fn new_profile.last_name = ln new_profile.activation_key = activation_key new_profile.keyexpiry_date = key_expires new_profile.phone_number = pn new_profile.sex = sx new_profile.save() t = loader.get_template('registration/email.txt') c = Context({ 'firstname': new_profile.first_name, 'lastname': new_profile.last_name, 'site_name': 'YAAS Auction Site', 'username': new_profile.username, 'activationkey': new_profile.activation_key, 'admin': 'Kenneth Odoh', }) email_subject = 'Your new YAAS account' send_mail(email_subject, t.render(c), '*****@*****.**', [new_profile.email], fail_silently=False) return HttpResponseRedirect(reverse('my_account')) else: #errors form = RegistrationForm() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy() form_data.update(request.FILES) # Check to see if unicode names worked out. if not request.FILES['file_unicode'].name.endswith( u'test_\u4e2d\u6587_Orl\xe9ans.jpg'): return HttpResponseServerError() for key, value in form_data.items(): if key.endswith('_hash'): continue if key + '_hash' not in form_data: continue submitted_hash = form_data[key + '_hash'] if isinstance(value, UploadedFile): new_hash = sha_constructor(value.read()).hexdigest() else: new_hash = sha_constructor(value).hexdigest() if new_hash != submitted_hash: return HttpResponseServerError() # Adding large file to the database should succeed largefile = request.FILES['file_field2'] obj = FileModel() obj.testfile.save(largefile.name, largefile) return HttpResponse('')
def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy() form_data.update(request.FILES) # Check to see if unicode names worked out. if not request.FILES['file_unicode'].name.endswith(u'test_\u4e2d\u6587_Orl\xe9ans.jpg'): return HttpResponseServerError() for key, value in form_data.items(): if key.endswith('_hash'): continue if key + '_hash' not in form_data: continue submitted_hash = form_data[key + '_hash'] if isinstance(value, UploadedFile): new_hash = sha_constructor(value.read()).hexdigest() else: new_hash = sha_constructor(value).hexdigest() if new_hash != submitted_hash: return HttpResponseServerError() return HttpResponse('')
def create_profile(self, email): """ 创建一个 Email - Key 对 """ salt = sha_constructor(str(random.random())).hexdigest()[:5] if isinstance(email, unicode): email = email.encode('utf-8') activation_key = sha_constructor(salt + email).hexdigest() return self.create(email=email, activation_key=activation_key)
def activate(self): self.is_active = True salt = sha_constructor(str(random.random())).hexdigest()[:5] username = self.user.username if isinstance(username, unicode): username = username.encode('utf-8') self.activation_key = sha_constructor(salt + username).hexdigest() self.save()
def activate(self): self.is_active = True salt = sha_constructor(str(random.random())).hexdigest()[:5] username = self.user.username if isinstance(username, unicode): username = username.encode('utf-8') self.activation_key = sha_constructor(salt+username).hexdigest() self.save()
def password_reset(request): if request.method == "POST": form = RequestPasswordResetForm(request.POST) if form.is_valid(): user = form.get_user() if not user.is_active: messages.warning(request, _("Your account is still inactive! You won't be able to log in until you reactivate with the link sent by e-mail.")) expire = datetime.now() + timedelta(days=1) variable_part = expire.strftime("%Y-%m-%d %H:%i:%s") + str(int(random.random() * 10)) h = sha_constructor(settings.SECRET_KEY + variable_part).hexdigest()[:24] # make sure the hash is unique enough reset = PasswordReset(user=user, expire=expire, h=h) try: reset.save() except IntegrityError: extrapart = int(random.random() * 10) h = sha_constructor(settings.SECRET_KEY + variable_part + extrapart).hexdigest()[:24] reset = PasswordReset(user=user, expire=expire, h=h) reset.save() #send email nickname = user.get_profile().forum_nickname email = user.email if not email: email = '*****@*****.**' domain = Site.objects.get_current().domain url = "http://%s%s?h=%s" % ( domain, reverse(do_password_reset), h ) text_content = _("""Hello %(nickname)s, \n You or someone else has requested a password reset for your Modelbrouwers.nl account. This request will expire after 24 hours.\n Go to %(url)s to complete your password reset.\n Sincerely,\n The Modelbrouwers.nl staff""" % { 'nickname': nickname, 'url': url } ) html_content = _(TEMPLATE_RESET_PW_HTML % { 'nickname': nickname, 'url': url } ) subject, from_email = _("Modelbrouwers.nl password reset"), '*****@*****.**' msg = EmailMultiAlternatives(subject, text_content, from_email, [email]) msg.attach_alternative(html_content, "text/html") msg.send() messages.success(request, _("An e-mail was sent to '%(email)s' with a link to reset your pasword.") % {'email': email}) return HttpResponseRedirect(reverse(custom_login)) else: form = RequestPasswordResetForm() return render(request, 'general/password_reset.html', {'form': form})
def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha_constructor(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha_constructor(combined_string).hexdigest()
def createNewAnimateur(nom, prenom, email): while True: username = sha_constructor(str(random.random())).hexdigest()[:5] try: User.objects.get(username__iexact=username) except User.DoesNotExist: break password = sha_constructor(str(random.random())).hexdigest()[:6] new_user = UserenaSignup.objects.create_user(username, email, password, True, False) # activé, pas de mail return createAnimateur(nom, prenom, email, new_user.id)
def get_secure_key(param2): """ This method returns secret key for invitations, confirmations and etc. """ param1 = settings.SECRET_KEY param3 = random.random() salt = sha_constructor(str(param1) + str(param2)).hexdigest() hsh = sha_constructor(salt + str(param3)).hexdigest() return hsh
def resend_activation(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('log.views.index')) if request.method == 'POST': form = ResendActivationForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] try: user = User.objects.get(email=email, is_active=0) except ObjectDoesNotExist: user = None if not user: form._errors["email"] = ("No account found for this email or already activated!",) else: profile = RegistrationProfile.objects.get(user=user) if profile.activation_key_expired(): salt = sha_constructor(str(random())).hexdigest()[:5] profile.activation_key = sha_constructor(salt+user.username).hexdigest() user.date_joined = timezone.now() user.save() profile.save() else: # as long as the key is not expired, don't let them send a new one # this is to avoid abuse expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) date = user.date_joined + expiration_date - timezone.now() if date > datetime.timedelta(days=1): time_to_wait = "two days" elif date > datetime.timedelta(hours=8): time_to_wait = "a day" elif date > datetime.timedelta(hours=3): time_to_wait = "a few hours" else: time_to_wait = "an hour" return render_to_response("registration/activation_resend_complete.html", RequestContext(request, {'success': False, 'time_to_wait': time_to_wait})) if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) profile.send_activation_email(site) return render_to_response("registration/activation_resend_complete.html", RequestContext(request, {'success': True})) else: form = ResendActivationForm() return render_to_response("registration/activation_resend_form.html", RequestContext(request, {'form': form}))
def add_member(sender, instance, created, **kwargs): if created: member=Member.objects.create(user=instance) salt = sha_constructor(str(random.random())).hexdigest()[:5] username = instance.username if isinstance(username, unicode): username = username.encode('utf-8') activation_key = sha_constructor(salt+username).hexdigest() EmailActivation.objects.create(account=instance, activation_key=activation_key)
def create_profile(self, email): """ 创建一个 Email - Key 对 """ salt = sha_constructor(str(random.random())).hexdigest()[:5] if isinstance(email, unicode): email = email.encode('utf-8') activation_key = sha_constructor(salt+email).hexdigest() return self.create(email=email, activation_key=activation_key)
def create_invitation(self, user): ## The key for the ``InvitationKey`` will be a SHA1 hash, generated ##from a combination of the ``User``'s username and a random salt. salt = sha_constructor(str(random.random())).hexdigest()[:5] key = sha_constructor("%s%s%s" % (datetime.datetime.now(), salt, user.username)).hexdigest() return self.create(from_user=user, key=key)
def save(self, *args, **kwargs): """ Uses `self.key` to confirm request to join channel. """ if not self.key: salt = sha_constructor(str(random.random())).hexdigest()[:5] hashed_email = sha_constructor(salt + self.email).hexdigest()[:10] self.key = hashed_email super(ConfirmationInfo, self).save(*args, **kwargs)
def save_form_data(self, instance, data): if data and self.width and self.height: content = self.resize_image(data.read(), width=self.width, height=self.height) salt = sha_constructor(str(random.random())).hexdigest()[:5] fname = sha_constructor(salt + settings.SECRET_KEY).hexdigest() + '.png' data = SimpleUploadedFile(fname, content, data.content_type) super(ExtendedImageField, self).save_form_data(instance, data)
def create_invitation(self, user): """ Create an ``InvitationKey`` and returns it. The key for the ``InvitationKey`` will be a SHA1 hash, generated from a combination of the ``User``'s username and a random salt. """ salt = sha_constructor(str(random.random())).hexdigest()[:5] key = sha_constructor(salt + user.username).hexdigest() return self.create(from_user=user, key=key)
def reset_activation(self): """ Reset the User account and this RegistrationProfile back to a state that a user can activate by resetting the user date_joined as today and generating a new activation_key """ self.user.date_joined = datetime.datetime.now() salt = sha_constructor(str(random.random())).hexdigest()[:5] self.activation_key = sha_constructor(salt + user.username).hexdigest()
def get_validation_hash(value): """ Create validation hash for submissions to verify submissions """ salt = sha_constructor(str(random.random())).hexdigest()[:5] slug = slugify(value) if isinstance(slug, unicode): slug = slug.encode('utf-8') return sha_constructor(salt + slug).hexdigest()
def create_pending_login(self, contact): if contact.user: return None salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt + contact.email).hexdigest() pending_login = self.create( contact=contact, date=datetime.datetime.now(), activation_key=activation_key, ) return pending_login
def create_invitation(self, user): """ Create an ``InvitationKey`` and returns it. The key for the ``InvitationKey`` will be a SHA1 hash, generated from a combination of the ``User``'s __unicode__ and a random salt. """ salt = sha_constructor(str(random.random())).hexdigest()[:5] key = sha_constructor( "%s%s%s" % (datetime.datetime.now(), salt, user)).hexdigest() return self.create(from_user=user, key=key)
def generate_activation_key(username): """generate activation key with username originally written by ubernostrum in django-registration_ .. _django-registration: https://bitbucket.org/ubernostrum/django-registration """ if isinstance(username, unicode): username = username.encode('utf-8') salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt + username).hexdigest() return activation_key
def create_profile(self, user): """ Create a ``RegistrationProfile`` for a given ``User``, and return the ``RegistrationProfile``. The activation key for the ``RegistrationProfile`` will be a SHA1 hash, generated from a combination of the ``User``'s username and a random salt. """ salt = sha_constructor(str(random.random())).hexdigest()[:5] activation_key = sha_constructor(salt + user.username).hexdigest() return self.create(user=user, activation_key=activation_key)
def reset_password_instance(request): if request.method == 'POST': fromEmail = "*****@*****.**" toEmail = request.POST.get('email') try: reset_instance = PasswordReset.objects.get(email=toEmail, done=False) return HttpResponse(simplejson.dumps({'message':"There is a request. Please check again!"})) except PasswordReset.DoesNotExist: msg = MIMEMultipart('alternative') msg['Subject'] = "Outclan - reset password" msg['From'] = fromEmail msg['To'] = toEmail salt = sha_constructor(str(random.random())).hexdigest()[:5] token = sha_constructor(salt + toEmail).hexdigest() PasswordReset(email=toEmail, token=token).save() link = "http://www.outclan.com/password/"+token text = "Hi!\n"+link+"\n" html = """\ <html> <head></head> <body> <p>Hi!<br> """+link+"""<br> </p> </body> </html> """ username = '******' password = "******" part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) s = smtplib.SMTP('smtp.sendgrid.net', 587) s.login(username, password) s.sendmail(fromEmail, toEmail, msg.as_string()) s.quit() return HttpResponse(simplejson.dumps({'message':"An email has been sent to you!"})) return HttpResponse('Not here!')
def generate_activation_key(self, send_email=True, password=None, realhost=None, next_url=None): if next_url is None: next_url = settings.LOGIN_URL salt = sha_constructor(str(random.random())).hexdigest()[:5] username = smart_str(self.username) self.activation_key = sha_constructor(salt + username).hexdigest() self.date_joined = dt.datetime.now() self.save() if send_email: self.email_activation_key(password, realhost, next_url=next_url)
def send_request_email(auth_party, activity, exp_id): """ Make record that describes authkey, address of correspondance, and state of authorisation. Send email to address, and wait for verification. """ exp = Experiment.objects.get(pk=exp_id) try: party_email = auth_party.get_email_addresses()[0] except IndexError: party_email = "" try: publish_auth = PublishAuthorisation.objects.get( experiment=exp, party_record=auth_party) except PublishAuthorisation.DoesNotExist: salt = sha_constructor(str(random.random())).hexdigest()[:5] logger.debug("salt=%s" % salt) username = unicode(auth_party.partyname) if isinstance(username, unicode): username = username.encode('utf-8') logger.debug("username=%s" % username) activation_key = sha_constructor(salt + username).hexdigest() logger.debug("activation_key=%s" % activation_key) logger.debug("party_email=%s" % party_email) publish_auth = PublishAuthorisation( auth_key=activation_key, experiment=exp, authoriser=auth_party.get_fullname(), email=party_email, status=PublishAuthorisation.PENDING_APPROVAL, party_record=auth_party, activity_record=activity) publish_auth.save() try: _send_email(publish_auth=publish_auth, activation_key=activation_key, exp=exp, activity=activity, auth_party=auth_party, party_email=party_email) except SMTPException, e: logger.error(e) return False except socket.gaierror, e: logger.error(e) return False
def generate_key(self, inviter): """ Generate a new ``Invite`` key and return it. The key for the ``Invite`` will be a SHA1 hash, generated from: * time-specific data * inviter-specific data * a random salt """ payload = ''.join([ str(timezone.now()), str(inviter), sha_constructor(str(random.random())).hexdigest(), ]) return base64.b32encode(sha_constructor(payload).digest())[:8].lower()
def generate_confirmation(self, email_address): """Generate and return a new EmailConfirmation w/ key. #TODO: ? Return existing confirmation and disallow multiple confirmations? :param email_address: EmailAddress instance :return: EmailConfirmation instance """ salt = sha_constructor(str(random())).hexdigest()[:5] confirmation_key = sha_constructor(salt + email_address.email).hexdigest() confirmation = self.create(email_address=email_address, sent=datetime.datetime.now(), confirmation_key=confirmation_key) return confirmation