def fgpass(request): if request.method == 'POST': check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR']) if check_captcha.is_valid is False: error = 'The verification code you have entered is not valid' return render_to_response('emailpassword.html', {'error': error}, context_instance=RequestContext(request)) else: try: toemail = request.POST['userEmail'] user_key = ''.join(random.sample('Lksrtg8945ljkfsfd397470CfDbPh', 15)) user_obj = CiviguardUsersModel.objects.get(emailAdd=toemail) user_obj.passResetCode = user_key user_obj.save() link = '' res = domain(request) if res[0] == True: link = 'http://%s.civiguard.me/resetmail/?pvalue=%s' % (res[1], user_key) else: link = 'http://%s.civiguard.me/resetmail/?pvalue=%s' % (res[1], user_key) fromemail = '*****@*****.**' subject = 'Password Reset' text_content = """ You can reset your password by visiting this link %s """ % link msg = EmailMultiAlternatives(subject, text_content, fromemail, [toemail]) msg.send() return render_to_response('notice.html', {'email': toemail}, context_instance=RequestContext(request)) except Exception, ex: return HttpResponse('Error %s' % ex)
def do(request): WZ = Z.SetWhoZwho(request) if request.method == 'POST': # If the form has been submitted... form = ForgotLoginForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass check_captcha = captcha.submit (form.cleaned_data['recaptcha_challenge_field'], form.cleaned_data['recaptcha_response_field'], WZ['CaptchaPrivate'], "127.0.0.1") if not check_captcha.is_valid: WZ['ErrorMessage'] = "[FL01]: Captcha response was incorrect." else: users = User.objects.all(). \ filter(first_name__exact=form.cleaned_data['first_name']). \ filter(last_name__exact=form.cleaned_data['last_name']). \ filter(email__exact=form.cleaned_data['email']) if len(users) == 1: send_mail( 'Forgotten login ID.', 'Login ID: ' + users[0].username, WZ['AdminEmail'], [users[0].email], fail_silently=False) WZ['ErrorMessage'] = "[FL02]: Login ID sent to your email." else: WZ['ErrorMessage'] = "[FL03]: Invalid Login ID." else: WZ['ErrorMessage'] = str(form.errors) else: form = ForgotLoginForm() captcha_html = captcha.displayhtml(WZ['CaptchaPublic'], use_ssl = True) c = { 'form': form, 'WZ': WZ, 'captcha_html': captcha_html } c.update(csrf(request)) return render_to_response('UserForgotLogin.html', c )
def post(self): name = self.request.get("name") content = self.request.get("content") lang = self.request.get("lang") challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] cResponse = captcha.submit( challenge, response, "6Lf4R9QSAAAAAAibMAmiP28JCkO_E5NdF9QgjkMY", remoteip ) if cResponse.is_valid: if content: if not name: name = "Untitled" p = Post(name=name, content=content, lang=lang) p.put() KEY = p.key().id() self.redirect("/"+str(KEY), str(KEY)) else: error = "content, please!" else: error = "captcha invalid. try again" self.render_newpost(name, content, error)
def signupLDAPUser(self, username, password, ms_eu, ms_other, institution, abbrev, REQUEST=None, RESPONSE=None): """ process the request for a new account """ if REQUEST is not None: session = REQUEST.SESSION ms = ms_eu or ms_other if self.use_captcha: #check if captcha is valid check_captcha = captcha.submit(REQUEST.get('recaptcha_challenge_field', ''), REQUEST.get('recaptcha_response_field', ''), getattr(self, 'private_key'), REQUEST.get('REMOTE_ADDR', '') ) if check_captcha.is_valid is False: #Captcha is wrong show a error . session.set('err_captcha', 'Incorrect. Try again') #validate form fields if not username: session.set('err_username', 'Please enter a username') if not ms: session.set('err_ms', 'Please enter a Member State') if not institution: session.set('err_institution', 'Please enter the Institution') local_users = self.acl_users.getLocalUsers() user_ob = self.acl_users.getUser(username) if user_ob: if [user for user in local_users if user[0] == user_ob.getUserDN()]: session.set('err_username', 'Sorry, that username already exists!') if not password: session.set('err_password', 'The password field is empty') if username and password: #try to login with the LDAP account user = self.login_ldap(username, password) if user is None: session.set('err_login', 'Username and password do not match') else: if not session.keys(): self.map_ldap_account(username) self.create_account_details(username, '', '', institution, abbrev, ms, '') #send notification email to the administrators self.send_ldap_notification(username) session.set('op_completed', True) else: #put form field values on session session.set('username', username) session.set('ms_eu', ms_eu) session.set('ms_other', ms_other) session.set('institution', institution) session.set('abbrev', abbrev) return RESPONSE.redirect(REQUEST.HTTP_REFERER) else: raise NotImplemented
def clean(self, values): super(ReCaptchaField, self).clean(values[1]) recaptcha_challenge_value = smart_unicode(values[0]) recaptcha_response_value = smart_unicode(values[1]) check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {}) if not check_captcha.is_valid: raise forms.util.ValidationError(self.error_messages['captcha_invalid']) return values[0]
def comment(request): from django.contrib.comments.views.comments import post_comment import captcha #captcha_html = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY) msg = _("Captcha was incorrect") if request.POST.has_key('recaptcha_challenge_field') and request.POST.has_key('recaptcha_response_field'): captcha_response = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR']) if captcha_response.is_valid: return post_comment(request, request.POST['target']) return HttpResponseBadRequest("cannot recognize this form")
def comment_post(request, id=None): instance = None if id is not None: instance = BlogEntryComment.objects.get(id=id) captcha_response = captcha.submit( request.POST.get("recaptcha_challenge_field", None), request.POST.get("recaptcha_response_field", None), RECAPTCHA_PRIVATE_KEY, request.META.get("REMOTE_ADDR", None), ) if request.method == "POST": form = jacey_forms.BlogEntryCommentForm(request.POST, instance=instance) clean = form.is_valid() rdict = {"bad": "false"} if not clean: rdict.update({"bad": "true"}) d = {} for e in form.errors.iteritems(): d.update({e[0]: unicode(e[1])}) # e[0] is the id, unicode(e[1]) is the error HTML. rdict.update({"errs": d}) else: # look to wrap in transaction if captcha_response.is_valid: new_blog_entry_comment = form.save(commit=False) blog_entry_key = request.POST.get("key", False) blog_entry = db.get(blog_entry_key) new_blog_entry_comment.reference = blog_entry.key() new_blog_entry_comment = form.save() # let's send an email to jacey to let her know someone commented # TODO: factor this into its own reusable method sender_name = request.POST.get("name", False) # sender_email = request.POST.get('*****@*****.**', False) sender_email = "*****@*****.**" sender_subject = "Someone commented on one of your photos!" sender_message = request.POST.get("comment", False) mail.send_mail( sender=sender_email, to="Jacey <*****@*****.**>", cc="Dylan Lorimer <*****@*****.**>", subject=sender_subject, body=sender_message, ) else: captcha_error = "&error=%s" % captcha_response.error_code if request.is_ajax(): return HttpResponse(simplejson.dumps(rdict), mimetype="application/javascript") else: return HttpResponseRedirect("/") else: form = jacey_forms.BlogEntryForm(instance=instance) return render_to_response("base_content.html", rdict, captcha_error)
def clean(self, values): super(ReCaptchaField, self).clean(values[1]) recaptcha_challenge_value = smart_unicode(values[0]) recaptcha_response_value = smart_unicode(values[1]) check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {}) if not check_captcha.is_valid: raise forms.util.ValidationError( self.error_messages['captcha_invalid']) return values[0]
def now(request): WZ = Z.SetWhoZwho(request) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): check_captcha = captcha.submit (form.cleaned_data['recaptcha_challenge_field'], form.cleaned_data['recaptcha_response_field'], WZ['CaptchaPrivate'], "127.0.0.1") if not check_captcha.is_valid: WZ['ErrorMessage'] = "[UR01]: Captcha response was incorrect." else: users = User.objects.all().filter(username__exact=form.cleaned_data['login_id']) if len(users) < 1: new_user = User() new_user.username = form.cleaned_data['login_id'] new_user.first_name = form.cleaned_data['first_name'] new_user.last_name = form.cleaned_data['last_name'] new_user.email = form.cleaned_data['email'] new_user.set_password(form.cleaned_data['password']) new_user.save() new_name = Name() new_name.preferred = form.cleaned_data['first_name'] new_name.first = form.cleaned_data['first_name'] new_name.last = form.cleaned_data['last_name'] new_name.authority = Z.NewRW new_name.user = new_user new_name.save() new_name.owner = new_name.id new_name.save() auth_user = authenticate(username=new_user, password=form.cleaned_data['password']) if auth_user is not None: if auth_user.is_active: login(request, auth_user) WZ['Authenticated'] = 1 request.session['last_time'] = time() WZ = Z.SetWhoZwho(request, '.') return HttpResponseRedirect('/WhoZwho/' + WZ['Tabs'][WZ['ActiveTab']][3]) else: WZ['ErrorMessage'] = "[UR02]: Login ID disabled." else: WZ['ErrorMessage'] = "[UR03]: Login ID is invalid." else: WZ['ErrorMessage'] = "[UR04]: The selected Login ID is already in use." else: WZ['ErrorMessage'] = str(form.errors) else: form = RegistrationForm() # An unbound form captcha_html = captcha.displayhtml(WZ['CaptchaPublic'], use_ssl = True) c = { 'form': form, 'WZ': WZ, 'captcha_html': captcha_html } c.update(csrf(request)) return render_to_response('UserRegistration.html', c )
def free_comment_wrapper(request, extra_context={}, context_processors=None): if request.POST: check_captcha = captcha.submit( request.POST.get("recaptcha_challenge_field", ""), request.POST.get("recaptcha_response_field", ""), settings.RECAPTCHA_PRIVATE_KEY, request.META["REMOTE_ADDR"], ) if check_captcha.is_valid is False: raise Http404, "Invalid Captcha Attempt" extra_context["recaptcha_html"] = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY) return post_free_comment(request, extra_context, context_processors) raise Http404, "Only POSTs are allowed"
def do(request): WZ = Z.SetWhoZwho(request) if WZ["ErrorMessage"]: return GoLogout(request, WZ) if request.method == "POST": # If the form has been submitted... form = UserChangePasswordForm(request.POST, request.FILES) if form.is_valid(): # All validation rules pass check_captcha = captcha.submit( form.cleaned_data["recaptcha_challenge_field"], form.cleaned_data["recaptcha_response_field"], WZ["CaptchaPrivate"], "127.0.0.1", ) if not check_captcha.is_valid: WZ["ErrorMessage"] = "[CP01]: Captcha response was incorrect." else: try: user = User.objects.get(username__exact=WZ["User"]) except: return GoLogout(request, WZ, "[CP02]: Password change disabled.") user.set_password(form.cleaned_data["password"]) user.save() user.name.password_timeout = None user.name.save() auth_user = authenticate(username=WZ["User"], password=form.cleaned_data["password"]) if auth_user is not None: if auth_user.is_active: login(request, auth_user) WZ["Authenticated"] = 1 request.session["last_time"] = time() WZ = Z.SetWhoZwho(request, ".") return HttpResponseRedirect("/WhoZwho/" + WZ["Tabs"][WZ["ActiveTab"]][3]) else: WZ["ErrorMessage"] = "[CP03]: Login ID disabled." else: WZ["ErrorMessage"] = "[CP04]: Login ID disabled." else: WZ["ErrorMessage"] = str(form.errors) else: form = UserChangePasswordForm() captcha_html = captcha.displayhtml(WZ["CaptchaPublic"], use_ssl=True) context = {"captcha_html": captcha_html, "form": form, "WZ": WZ} context.update(csrf(request)) return render_to_response("UserChangePassword.html", context)
def save_comment(self): _ = self.macro.request.getText if get_input(self.macro, "do") != u"comment_add": # This is not a comment post do nothing return if get_cfg(self.macro, "comment_recaptcha", False): import captcha self.captcha = captcha.submit( get_input(self.macro, "recaptcha_challenge_field"), get_input(self.macro, "recaptcha_response_field"), get_cfg(self.macro, "comment_recaptcha_private_key"), self.macro.request.remote_addr, ) self.get_comment() self.errors = self.errors_check() if not self.errors: # Save the comment # Find out where to save the comment: if get_cfg(self.macro, "comment_moderate", True): page = Page(self.macro.request, get_cfg(self.macro, "comment_approval_page", "CommentsApproval")) comment_dir = page.getPagePath("", check_create=0) else: page = Page(self.macro.request, self.page_name) comment_dir = page.getPagePath("comments", check_create=1) now = datetime.now() random_str = "".join([choice(letters + digits) for i in range(20)]) comment_file = "%s-%s.txt" % (now.strftime("%s"), random_str) file_name = os.path.join(comment_dir, comment_file) comment = self.comment comment["page"] = self.page_name comment["time"] = now if get_cfg(self.macro, "comment_store_addr", False): comment["remote_addr"] = self.macro.request.remote_addr write_comment(file_name, comment) if get_cfg(self.macro, "comment_moderate", True): self.msg = _("Your comment awaits moderation. Thank you.") else: self.msg = _("Your comment has been posted. Thank you.") # clean up the fields to display self.comment = {"user_name": "", "comment": "", "email": ""}
def comment(request): from django.contrib.comments.views.comments import post_comment import captcha #captcha_html = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY) msg = _("Captcha was incorrect") if request.POST.has_key( 'recaptcha_challenge_field') and request.POST.has_key( 'recaptcha_response_field'): captcha_response = captcha.submit( request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR']) if captcha_response.is_valid: return post_comment(request, request.POST['target']) return HttpResponseBadRequest("cannot recognize this form")
def signup(request): import captcha email = "" key = request.REQUEST.get("key", "") pu = None if key: try: pu = PseudoUser.objects.get(pk=key) email = pu.email except: key = "" if request.method == "POST": form = SignUpForm(request.POST) check_captcha = captcha.submit( request.POST["recaptcha_challenge_field"], request.POST["recaptcha_response_field"], settings.RECAPTCHA_PRIVATE_KEY, request.META["REMOTE_ADDR"], ) if check_captcha.is_valid and form.is_valid(): first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] email = form.cleaned_data["email"] username = form.cleaned_data["username"] password = form.cleaned_data["password"] create_account(first_name, last_name, username, email, password) user = authenticate(username=username, password=password) login(request, user) if pu: from auxiliary import base36_to_int hc_id, t = pu.host_class_to.split(",") hc = HostClass.objects.get(pk=base36_to_int(hc_id)) hcm = HostClassMember(host_class=hc, user=user) hcm.save() return HttpResponseRedirect("/h/v/" + hc.pk) else: return HttpResponseRedirect("/accounts/edit/") else: form = SignUpForm({"email": email}) html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY, use_ssl=True) return render_to_response( "accounts/signup.html", {"form": form, "key": key, "html_captcha": html_captcha}, context_instance=RequestContext(request), )
def signup(request, template_name='registration/register.html'): captcha_form = captcha.displayhtml("6LfitQAAAAAAAPuPkbRUUbT6mjhFbTGaS_nwKjkl") if request.method == 'POST': recaptcha_challenge_field = request.POST["recaptcha_challenge_field"] recaptcha_response_field = request.POST["recaptcha_response_field"] private_key = "6LfitQAAAAAAAGlpZA4DyouLEWRkfqLwBawQAxrq" remoteip = request.META['REMOTE_ADDR'] captcha_response = captcha.submit(recaptcha_challenge_field=recaptcha_challenge_field, recaptcha_response_field=recaptcha_response_field, private_key=private_key, remoteip=remoteip) if captcha_response.is_valid: new_data = request.POST form = UserForm(data=new_data) if form.is_valid(): new_user = form.save() profile = Profile(user=new_user, first_name=new_data['first_name'], last_name=new_data['last_name'], email=new_data['email'], country='us') profile.save() login(request, authenticate(username=new_data['username'], password=new_data['password2'])) # Why doesn't this work? AttributeError: 'User' object has no attribute 'backend' #login(request, new_user) return HttpResponseRedirect("/accounts/profile/") else: form = UserForm(request.POST) captcha_error = "<span style='color:red'>Incorrect captcha, please try again!</span>" else: form = UserForm() captcha_error = "" return render_to_response(template_name, dict(form=form, captcha_form=captcha_form, captcha_error=captcha_error), context_instance=RequestContext(request))
def do(request): WZ = Z.SetWhoZwho(request) if request.method == 'POST': # If the form has been submitted... form = ForgotPasswordForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass check_captcha = captcha.submit (form.cleaned_data['recaptcha_challenge_field'], form.cleaned_data['recaptcha_response_field'], WZ['CaptchaPrivate'], "127.0.0.1") if not check_captcha.is_valid: WZ['ErrorMessage'] = "[FP01]: Captcha response was incorrect." else: users = User.objects.all(). \ filter(username__exact=form.cleaned_data['login_id']). \ filter(email__exact=form.cleaned_data['email']) if len(users) == 1: temporary_password = GenerateTemporaryPassword() users[0].set_password(temporary_password) users[0].save() users[0].name.password_timeout = int(time()) users[0].name.save() send_mail( 'Password Reset', 'A password reset request for your account has been received and a new ' + \ 'temporary password has been assigned (see below). Visit ' + WZ['httpURL'] + '/login ' + \ 'within the next 20 minutes and choose a new permanent password. If you need more ' + \ 'time, you may visit ' + WZ['httpURL'] + '/fgpwd at any time to request another ' + \ 'temporary password.\n\nLogin ID: ' + users[0].username + \ '\nTemporary password: '******'AdminEmail'], [users[0].email], fail_silently=False) WZ['ErrorMessage'] = "[FP02]: Temporary password sent to your email." else: WZ['ErrorMessage'] = "[FP03]: Invalid Login ID/email." else: WZ['ErrorMessage'] = str(form.errors) else: form = ForgotPasswordForm() captcha_html = captcha.displayhtml(WZ['CaptchaPublic'], use_ssl = True) c = { 'form': form, 'WZ': WZ, 'captcha_html': captcha_html } c.update(csrf(request)) return render_to_response('UserForgotPassword.html', c )
def post(self): lat = self.request.get("lat", "") lon = self.request.get("lon", "") description = self.request.get("description", "") incidentdate = self.request.get("date", "") # variables for recaptcha challenge = self.request.get("challenge", "") response = self.request.get("response", "") remoteip = os.environ["REMOTE_ADDR"] if not (lat and lon and description): # utils.setErrorResponse(self.response, 400, "Missing Required Arguments") self.response.headers["Content-Type"] = "text/json" # self.response.set_status(400) self.response.out.write(json.dumps(dict(result="failed", message="Missing Required Arguments. Try again."))) return cResponse = captcha.submit(challenge, response, "6LfKnsQSAAAAABUdzDpWvKmf_2lpRaXmwZPaVzSj", remoteip) if not cResponse.is_valid: self.response.headers["Content-Type"] = "text/json" # response.set_status(400) self.response.out.write(json.dumps(dict(result="failed", message="Invalid Captcha. Try again."))) return incident = models.KotongIncident(description=description, location=db.GeoPt(float(lat), float(lon))) if incidentdate: try: dt = datetime.datetime.strptime(incidentdate, "%m/%d/%Y") incident.date = dt.date() except ValueError: # utils.setErrorResponse(self.response, 400, "Invalid Incident Date Format") self.response.headers["Content-Type"] = "text/json" # self.response.set_status(400) self.response.out.write(json.dumps(dict(result="failed", message="Invalid Date Format. Try again."))) return incident.put() self.response.headers["Content-Type"] = "text/json" self.response.out.write(json.dumps(dict(result="saved", key=str(incident.key()))))
def post(self, op_type): self.response.headers['Content-Type'] = 'text/plain' session = get_current_session() if not session.is_active() or not session.has_key('my_id'): return self.do_output('captcha-not-logged-in') uid = session['my_id'] challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') if not challenge or not response: return self.do_output('captcha-bad-response') resp = captcha.submit(challenge, response, '6LdFE7oSAAAAAPuHb_bHlp4i6omCQkPlWySQjShD', self.request.remote_addr) if resp.is_valid: note_captcha_solved(op_type, uid) return self.do_output('captcha-ok') else: return self.do_output('captcha-failed-%s' % resp.error_code)
def post(self): challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') cResponse = captcha.submit(challenge, response, CAPTCHA_PRIVATE_KEY, REMOTE_ADDR) valid = True errors=None if cResponse.is_valid: username = self.request.get('username') user = UserModel.find_by_username(username) if not (user is None): valid = False errors=["Usuario %s ya existe "% username] else: validation = validateForm(self.request.POST, NewHandler.FIELD_COND) if(not validation[0]): valid = False errors = validation[1] else: password = self.request.get('password') passwordConfirmation = self.request.get('passwordConfirmation') if(password != passwordConfirmation): valid = False errors = ["Las contrasenas no coinciden"] else: hashed_pass = hashlib.sha224(password).hexdigest() name = self.request.get('name') email = self.request.get('email') if(self.request.get('isadmin') and self.request.get('isadmin')=="True"): usertype="Admin" else: usertype = "User" user = UserModel(key=ndb.Key('UserModel', username), username=username, name=name, email=email, active=False, usertype=usertype, password=hashed_pass) user.put() self.redirect('/') else: valid= False errors = ["Captcha not valid"] if not valid: error = cResponse.error_code chtml = captcha.displayhtml(public_key = CAPTCHA_PUBLIC_KEY,use_ssl = False,error = None) template_values = {'captchahtml':chtml, "errors" : errors, "session": self.session} template = JINJA_ENVIRONMENT.get_template('/user/new.html') self.response.write(template.render(template_values))
def post(self): post = self.request email = post.get('email') password = post.get('parola') if not email: self.template_values["errors"] = "Campul email nu poate fi gol." self.render() return if not password: self.template_values["errors"] = "Campul parola nu poate fi gol." self.render() return captcha_response = submit(post.get(CAPTCHA_POST_PARAM), CAPTCHA_PRIVATE_KEY, post.remote_addr) # if the captcha is not valid return if not captcha_response.is_valid: self.template_values[ "errors"] = "Se pare ca a fost o problema cu verificarea reCAPTCHA. Te rugam sa incerci din nou." self.render() return try: user = self.auth.get_user_by_password(email, password, remember=True) # succes self.redirect(self.uri_for('contul-meu')) except (InvalidAuthIdError, InvalidPasswordError) as e: warn('Invalid email or password: {0}'.format(email)) self.template_values['email'] = email self.template_values[ "errors"] = "Se pare ca aceasta combinatie de email si parola este incorecta." self.render()
def post(self): valid = True name = cgi.escape(self.request.get('author')) email = cgi.escape(self.request.get('email')) website = cgi.escape(self.request.get('url')) body = cgi.escape(self.request.get('comment')) articleId = cgi.escape(self.request.get('articleId')) slug = cgi.escape(self.request.get('slug')) comment_when = cgi.escape(self.request.get('comment_when')) challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = self.request.remote_addr cResponse = captcha.submit(challenge, response, "YOUR-PRIVATE-KEY", remoteip) if not cResponse.is_valid: valid = False #todo show error error = cResponse.error_code if not name: valid = False if not email: valid = False if not body: valid = False logging.info('Start user User-Agent') #get user agent userAgent = self.request.headers['User-Agent'] site = "jsoncharts.appspot.com" try: valid = akismet.comment_check("YOUR-API-KEY", site, remoteip, userAgent, comment_content=body) except akismet.AkismetError, e: valid = False logging.info('error')
def post(self): post = self.request email = post.get('email') if not email: self.template_values["errors"] = "Campul email nu poate fi gol." self.render() return captcha_response = submit(post.get(CAPTCHA_POST_PARAM), CAPTCHA_PRIVATE_KEY, post.remote_addr) # if the captcha is not valid return if not captcha_response.is_valid: self.template_values[ "errors"] = "Se pare ca a fost o problema cu verificarea reCAPTCHA. Te rugam sa incerci din nou." self.render() return user = self.user_model.get_by_auth_id(email) if not user: self.template_values.update( {"errors": "Se pare ca nu exita un cont cu aceasta adresa!"}) self.render() return self.send_email("reset-password", user) self.template_values.update({ "errors": False, "found": "Un email a fost trimis catre acea adresa" }) self.render()
def post(self): name = self.request.get("name") content = self.request.get("content") lang = self.request.get("lang") challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] cResponse = captcha.submit(challenge, response, "6Lf4R9QSAAAAAAibMAmiP28JCkO_E5NdF9QgjkMY", remoteip) if cResponse.is_valid: if content: if not name: name = "Untitled" p = Post(name=name, content=content, lang=lang) p.put() KEY = p.key().id() self.redirect("/" + str(KEY), str(KEY)) else: error = "content, please!" else: error = "captcha invalid. try again" self.render_newpost(name, content, error)
def process_comment_submission(handler, parent=None): sanitize_comment = get_sanitizer_func(handler, allow_attributes=['href', 'src'], blacklist_tags=['img', 'script']) property_hash = restful.get_sent_properties(handler.request.get, [('name', cgi.escape), ('email', cgi.escape), ('homepage', cgi.escape), ('title', cgi.escape), ('body', sanitize_comment), ('article_id', cgi.escape), 'recaptcha_challenge_field', 'recaptcha_response_field', ('published', get_datetime)]) # If we aren't administrator, abort if bad captcha if not users.is_current_user_admin(): cap_challenge = property_hash.get('recaptcha_challenge_field') cap_response = property_hash.get('recaptcha_response_field') cap_validation = captcha.RecaptchaResponse(False) if cap_challenge and cap_response: cap_validation = captcha.submit( cap_challenge, cap_response, config.BLOG['recap_private_key'], handler.request.remote_addr ) if not cap_validation.is_valid: logging.info( "Invalid captcha: %s", cap_validation.error_code ) handler.response.set_status(401, 'Invalid Captcha') # Unauthorized return if 'article_id' not in property_hash: return handler.error(400) article = db.Query(models.blog.Article).filter( 'permalink =', property_hash['article_id'] ).get() # Generate a thread string. if parent: logging.debug("Comment has parent: %s", parent.key()) thread_string = parent.next_child_thread_string() else: logging.debug("Comment is off main article") thread_string = article.next_comment_thread_string() property_hash['thread'] = thread_string # Get and store some pieces of information from parent article. # TODO: See if this overhead can be avoided if not article.num_comments: article.num_comments = 1 else: article.num_comments += 1 property_hash['article'] = article.put() try: comment = models.blog.Comment(**property_hash) comment.put() except: logging.debug("Bad comment: %s", property_hash) return handler.error(400) # Notify the author of a new comment (from matteocrippa.it) if config.BLOG['send_comment_notification'] and not users.is_current_user_admin(): recipient = "%s <%s>" % (config.BLOG['author'], config.BLOG['email']) article_link = config.BLOG['root_url'] + "/" + article.permalink comment_link = '%s#comment-%s' % (article_link, comment.key()) body = ('''A new comment has just been posted on %s by %s:\n\n"%s" \n\nReply to the comment here: %s''' % (article_link, comment.name, comment.body, comment_link)) mail.send_mail(sender=config.BLOG['email'], to=recipient, subject="New comment by %s" % (comment.name), body=body) # Render just this comment and send it to client view_path = view.find_file(view.templates, "bloog/blog/comment.html") response = template.render( os.path.join("views", view_path), { 'comment': comment, "use_gravatars": config.BLOG["use_gravatars"] }, debug=config.DEBUG) handler.response.out.write(response) view.invalidate_cache(comment.article.permalink)
def register_user(request): global base_title global global_nav, user_nav title = base_title + "Register" global_navigation = global_nav() # If user is not logged on if not request.user.is_authenticated(): # Return user navigation for an anonymous session user_navigation = user_nav(False) # Set up captcha html. from settings import captcha_publickey, captcha_privatekey captcha_test = captcha.displayhtml(captcha_publickey) # If user has sent POST data (not logged in) if request.method == 'POST': registration_errors = [] # Error list ''' Check and validate data ''' # Is human? HumanTestResult = captcha.submit( request.POST["recaptcha_challenge_field"], request.POST["recaptcha_response_field"], captcha_privatekey, get_ip(request)) # If not human: display errors if HumanTestResult.is_valid: # Matching passwords? password = v.clean_password(request.POST["passw"]) if not request.POST["passw"] == request.POST["repassw"]: registration_errors.append("Passwords don't match.") if password == None: registration_errors.append("No password entered.") elif password == -1: registration_errors.append( "Passwords have to be at least 5 characters.") # Username related errors username = v.clean_username(request.POST["usern"]) if username == None: registration_errors.append("No username entered.") elif username == -2: registration_errors.append( "This username isn't available.") elif username == -1: registration_errors.append( "Username's can only be 30 characters.") elif username == False: registration_errors.append( "Username wasn't just characters numbers ") # Email related errors email = v.clean_email(request.POST["email"]) if email == None: registration_errors.append("No email entered.") elif email == -2: registration_errors.append( "This email already has an account.") elif email == -1: registration_errors.append( "Emails can only be 245 characters.") elif email == False: registration_errors.append("Invalid email.") # Invalid CAPTCHA, display only that error giving no more information to the bot else: registration_errors.append("Invalid human verification code.") captcha_test = captcha.displayhtml(captcha_publickey, False, HumanTestResult.error_code) # Connect to SMTP server connection = mail.get_connection() connection.open() # If no errors: create user. if len(registration_errors) == 0: new_user = User.objects.create_user(username, email, request.POST["repassw"]) new_user.is_active = True new_user.save() # Create activation key and user profile activation_key = KeyGen() # Add 2 hours so a recovery key can be made instantly after # account creation. thetime = new_user.date_joined + datetime.timedelta(hours=2) profile = UserProfile(activate_key=activation_key, activated=False, recovery_time=thetime, user=new_user) profile.save() # User is created and saved. Send an activation link via email # Activation link message_activateurl = baseurl + "/activate/?key=" + str( activation_key) message_activateurl = message_activateurl + "&user="******"/deactivate/?key=" + str( activation_key) message_deactivateurl = message_deactivateurl + "&user="******"<$user>", str(new_user.username)) message = message.replace("<$activatelink>", message_activateurl) message = message.replace("<$disablelink>", message_deactivateurl) # Send email email = EmailMessage("Account Activation", message, EMAIL_HOST_USER, [new_user.email]) email.send() connection.close() # Return new account page accountname = new_user.username response = render_to_response( 'auth/newaccount.html', locals(), context_instance=RequestContext(request)) else: # Return registration form with errors in registration_errors response = render_to_response( 'auth/registration.html', locals(), context_instance=RequestContext(request)) # If user hasn't sent POST data (not logged on) else: response = render_to_response( 'auth/registration.html', locals(), context_instance=RequestContext(request)) # User is logged on else: user_navigation = user_nav(request.user.username) error = "You cannot register while logged in." response = render_to_response('error.html', locals()) return response
def post(self): logging.info("New signup request...\n\tEmail: %s\n\tAdd/Remove: %s\n\tReference: %s\n\tNotes: %s", self.request.get('string'), self.request.get('signup'), self.request.get('reference'), self.request.get('comments')) # first validate the email address if not email_re.search(self.request.get('string')): error_msg = "This address - %s - is not a valid email address. Check the formatting." % self.request.get('string') logging.error(error_msg) self.response.out.write("Oops. The email address was malformed! Please try again.") return message = mail.EmailMessage(sender="APOD Email <*****@*****.**>") blocked = False bcc = False # determine if this is a signup or remove request if self.request.get('signup') == 'signup': # first validate the captcha challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = self.request.get('remote_addr') logging.info("Captcha request... \n\tchallenge: %s\n\tresponse: %s\n\tIP: %s\n\t", challenge,response,remoteip) cResponse = captcha.submit( challenge, response, config.RECAPTCHA_PRIVATE_KEY, remoteip) if cResponse.is_valid: logging.debug('Captcha Success!') email_addr = self.request.get('string').lower() # first check to see if the user is already on the list q = db.GqlQuery("SELECT * FROM UserSignup WHERE email = :1", email_addr) remove_entry = q.fetch(1) if len(remove_entry) > 0: error_msg = "This address - %s - is already on the distribution list." % email_addr logging.error(error_msg) self.response.out.write("Oops. It looks like this email address is already on the list.") return # if signing up, create a new user and add it to the store userSignup = data_model.UserSignup() userSignup.email = email_addr userSignup.referral = self.request.get('reference') userSignup.notes = self.request.get('comments') # filter out requests if there is a URL in the comments field if re.search("http",userSignup.referral) or re.search("http",userSignup.notes): error_msg = "Request to add - %s - has been BLOCKED because of illegal text in the comments field." % email_addr logging.error(error_msg) template_values = {'error':error_msg} # setup the specific email parameters message.subject="APOD Email Signup BLOCKED" message.to = email_addr path = os.path.join(os.path.dirname(__file__), 'templates/invalid-email.html') message.html = template.render(path,template_values) # setup the confirmation page on the web #path = os.path.join(os.path.dirname(__file__), 'templates/invalid.html') msg = "Oops. No can do. This request is getting blocked because it looks fishy." else: # add the user to the database! userSignup.put() template_values = {'email':userSignup.email, 'referral':userSignup.referral, 'notes':userSignup.notes, } # setup the specific email parameters message.subject="APOD Email Signup Confirmation" message.to = email_addr path = os.path.join(os.path.dirname(__file__), 'templates/added-email.html') message.html = template.render(path,template_values) # setup the confirmation page on the web #path = os.path.join(os.path.dirname(__file__), 'templates/added.html') msg = "<h2>Excellent! You've been added to the list.</h2><p class='lead'>Please consider a donation to support this project.</p>" else: blocked = True msg = cResponse.error_code logging.error('Captcha Fail %s ' % msg) else: email_addr = self.request.get('string').lower() # if removing a user, first check to see that the request is valid q = db.GqlQuery("SELECT * FROM UserSignup WHERE email = :1", email_addr) remove_entry = q.fetch(1) if len(remove_entry) > 0: # if the user was found, remove them db.delete(remove_entry) # setup the specific email parameters message.subject="APOD Email Removal Request" message.to = self.request.get('string') template_values = { 'email':email_addr, 'referral':self.request.get('reference'), 'notes':self.request.get('comments'), } path = os.path.join(os.path.dirname(__file__), 'templates/removed-email.html') message.html = template.render(path,template_values) # ... and show the thank you confirmation page msg = "<h2>You've been removed from the list... Thanks!</h2>" # email me if they've left comments if len(self.request.get('comments')) > 0: bcc = True else: error_msg = "This address - %s - is not on the distribution list!?" % email_addr logging.error(error_msg) msg = "Oops. This address doesn't appear to be on the list." blocked = True # send the message off... if not blocked: logging.debug("Sending email!") task = Task(url='/emailqueue', params={'email':message.to,'subject':message.subject,'body':message.html,'bcc':bcc}) task.add('emailqueue') # report back on the status logging.debug(msg) self.response.out.write(msg)
def post(self): challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] cResponse = captcha.submit( challenge, response, recaptcha_private_key, remoteip) if cResponse.is_valid: success = True else: error = cResponse.error_code success = False chtml = captcha.displayhtml( public_key = recaptcha_public_key, use_ssl = False, error = cResponse.error_code) template_values = { 'error': cResponse.error_code, 'event': self.request.get('event'), 'venue': self.request.get('venue'), 'description': self.request.get('description'), 'categories': categories(), 'selectedcategory': self.request.get('category'), 'eventdate': self.request.get('eventdate'), 'eventtime': self.request.get('eventtime'), 'email': self.request.get('email'), 'private': self.request.get('private'), 'captchahtml': chtml } if (success == True): # Create a uniqie, guid name for the event. This fixes the problem of everyone having to have a unique event name. # uniquename = str(uuid.uuid4()).split("-")[0] uniquename = str(uuid.uuid4()).split("-")[0] + '/' + self.request.get('event').replace(' ', '-').replace('&', 'and').replace('\'', '').replace('\"', '').replace('.', '').replace("!", "").replace("@", "at").replace("*", "") password = str(uuid.uuid4()).split("-")[0] # Create a new Promotion record. promotion = Promotion() promotion.uniquename = uniquename promotion.venue = self.request.get('venue') promotion.event = self.request.get('event') promotion.description = db.Text(self.request.get('description')) promotion.date = self.request.get('eventdate') promotion.time = self.request.get('eventtime') promotion.email = self.request.get('email') promotion.category = self.request.get('category') promotion.password = password # Set if event is private or not. if not (self.request.get('private') == ''): promotion.private = True else: promotion.private = False image = str(self.request.get("image")) if not image is "": imageresized = images.resize(image, 453) promotion.image = db.Blob(imageresized) imagethumb = images.resize(image, 30) promotion.imagethumbnail = db.Blob(imagethumb) promotion.imageoriginal = db.Blob(image) promotion.put() # Create email and send to user. message = mail.EmailMessage(sender="PartyPlannr Support <*****@*****.**>", subject="New PartyPlannr Event Created") message.to = self.request.get('email') message.body = """ Your event has been created: "%s" To view your event click the link below: http://www.partyplannr.com/%s Please let us know if you have any questions. PartyPlannr """ % (self.request.get('event'), uniquename) #self.response.out.write(message.body) message.send() # Redirect to the new URL for the event. self.redirect("/%s" % uniquename, True) else: path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values))
def process_comment_submission(handler, parent=None): sanitize_comment = get_sanitizer_func(handler, allow_attributes=['href', 'src'], blacklist_tags=['img', 'script']) property_hash = restful.get_sent_properties( handler.request.get, [('name', cgi.escape), ('email', cgi.escape), ('homepage', cgi.escape), ('title', cgi.escape), ('body', sanitize_comment), ('article_id', cgi.escape), 'recaptcha_challenge_field', 'recaptcha_response_field', ('published', get_datetime)]) # If we aren't administrator, abort if bad captcha if not users.is_current_user_admin(): cap_challenge = property_hash.get('recaptcha_challenge_field') cap_response = property_hash.get('recaptcha_response_field') cap_validation = captcha.RecaptchaResponse(False) if cap_challenge and cap_response: cap_validation = captcha.submit(cap_challenge, cap_response, config.BLOG['recap_private_key'], handler.request.remote_addr) if not cap_validation.is_valid: logging.info("Invalid captcha: %s", cap_validation.error_code) handler.response.set_status(401, 'Invalid Captcha') # Unauthorized return if 'article_id' not in property_hash: return handler.error(400) article = db.Query(models.blog.Article).filter( 'permalink =', property_hash['article_id']).get() # Generate a thread string. if parent: logging.debug("Comment has parent: %s", parent.key()) thread_string = parent.next_child_thread_string() else: logging.debug("Comment is off main article") thread_string = article.next_comment_thread_string() property_hash['thread'] = thread_string # Get and store some pieces of information from parent article. # TODO: See if this overhead can be avoided if not article.num_comments: article.num_comments = 1 else: article.num_comments += 1 property_hash['article'] = article.put() try: comment = models.blog.Comment(**property_hash) comment.put() except: logging.debug("Bad comment: %s", property_hash) return handler.error(400) # Notify the author of a new comment (from matteocrippa.it) if config.BLOG[ 'send_comment_notification'] and not users.is_current_user_admin(): recipient = "%s <%s>" % (config.BLOG['author'], config.BLOG['email']) article_link = config.BLOG['root_url'] + "/" + article.permalink comment_link = '%s#comment-%s' % (article_link, comment.key()) body = ('''A new comment has just been posted on %s by %s:\n\n"%s" \n\nReply to the comment here: %s''' % (article_link, comment.name, comment.body, comment_link)) mail.send_mail(sender=config.BLOG['email'], to=recipient, subject="New comment by %s" % (comment.name), body=body) # Render just this comment and send it to client view_path = view.find_file(view.templates, "bloog/blog/comment.html") response = template.render(os.path.join("views", view_path), { 'comment': comment, "use_gravatars": config.BLOG["use_gravatars"] }, debug=config.DEBUG) handler.response.out.write(response) view.invalidate_cache(comment.article.permalink)
def post(self): fullname = self.request.get("fullname") email1 = self.request.get("email1") email2 = self.request.get("email2") subject = self.request.get("subject") body = self.request.get("body") pageParams = checkLogin(self) pageParams['email1'] = self.request.get('email1') pageParams['email2'] = self.request.get('email2') pageParams['fullname'] = self.request.get('fullname') pageParams['subject'] = self.request.get('subject') pageParams['body'] = self.request.get('body') challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] pageParams['captcha'] = captcha.displayhtml(public_key = "6Lc_gb8SAAAAAJWVBIquKY9vHVQEAyhRitnxYb3A",use_ssl=False, error=None) cResponse = captcha.submit(challenge,response,"6Lc_gb8SAAAAAK85P9VLyReVYFy15xkqP1DBrBxa",remoteip) if not cResponse.is_valid: pageParams['error'] = cResponse.error_code self.response.out.write( template.render('contact.html', pageParams)) return if fullname is None or len(fullname) == 0: pageParams['error'] = "Please provide your name." self.response.out.write( template.render('contact.html', pageParams)) return if email1 is None or len(email1) == 0: pageParams['error'] = "Email address required." self.response.out.write( template.render('contact.html', pageParams)) return if email2 is None or len(email2) == 0: pageParams['error'] = "Email address confirmation required." self.response.out.write( template.render('contact.html', pageParams)) return if email1 != email2: pageParams['error'] = "Email confirmation failed. Please enter your email again." self.response.out.write( template.render('contact.html', pageParams)) return if subject is None or len(subject) == 0: pageParams['error'] = "Subject required." self.response.out.write( template.render('contact.html', pageParams)) return if body is None or len(body) == 0: pageParams['error'] = "Your message is empty." self.response.out.write( template.render('contact.html', pageParams)) return msg = template.render('contact.eml', pageParams) mail.send_mail(sender='CryptoEditor <'+senderEmailAddress+'>', to=supportEmailAddress, subject=subject, body=msg) pageParams['message'] = "Your message has been sent with success." self.response.out.write( template.render('contact.html', pageParams))
def post(self, post_slug=""): if post_slug: t_values = {} post_id = self.request.POST['post_id'] post = Entry.get_by_id(long(post_id)) if post: # ok, we find the post, try to add comment to this post logging.warning("find one post with post_id %s" % (post_id)) t_values['post'] = post # dump(post) # check google recaptcha, these two fileds might not exist due to connection to reCAPTCHA recaptcha_challenge_field = self.request.POST.get('recaptcha_challenge_field', "") recaptcha_response_field = self.request.POST.get('recaptcha_response_field', "") remote_ip = self.request.environ['REMOTE_ADDR'] private_key = "6LdwFdISAAAAAOYRK7ls3O-kXPTnYDEstrLM2MRo" antispam_flag = False try: result = submit(recaptcha_challenge_field, recaptcha_response_field, private_key, remote_ip) logging.info("google recaptcha %s, %s" % (result.is_valid, result.error_code)) if result.is_valid: antispam_flag = True except: e = sys.exc_info()[0] logging.info(e) # create comment for this post if antispam_flag: logging.info("PostManager - add comment") comm_author = self.request.POST['author'] comm_email = self.request.POST['email'] comm_weburl = self.request.POST['weburl'] comm_content = self.request.POST['comment'] comment_ip = self.request.environ['REMOTE_ADDR'] comm = Comment(entry=post, author=comm_author, email=comm_email, weburl=comm_weburl, content=comm_content, ip=comment_ip) comm.put() t_values['alert_message'] = "Thanks %s for your comment!" % (comm_author) else: logging.warning("comment ignored because antispam failed") t_values['alert_message'] = "Sorry, your comment was ignored because of reCAPTCHA failure!" # find all comments comments = Comment.all().filter("entry =", post).order("date") logging.info("PostHandler, post, find %d comments" % (comments.count())) if post_id: # only update commentcount when new comment is added post.commentcount = comments.count() post.put() t_values['comments'] = comments else: logging.warning("post_id %s does not exist" % (post_id)) links = Link.all().order("date") t_values['links'] = links categories = Category.all() t_values['categories'] = categories pages = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').order("date") t_values['pages'] = pages return self.response.out.write(render_template("post.html", t_values, "basic", False)) else: self.redirect(uri_for("weblog.index"))
def initial_request(self): first_name = cgi.escape(self.request.get('first-name')) last_name = cgi.escape(self.request.get('last-name')) phone = cgi.escape(self.request.get('phone')) company = cgi.escape(self.request.get('company')) email = cgi.escape(self.request.get('email')) challenge = cgi.escape(self.request.get('recaptcha_challenge_field')) response = cgi.escape(self.request.get('recaptcha_response_field')) remoteip = os.environ['REMOTE_ADDR'] params={ "first_name": first_name, "last_name": last_name, "phone": phone, "company": company, "email": email, } # Do a bunch of form verification cResponse = captcha.submit(challenge, response, RECAPTCHA_PRIVATE, remoteip) error = False if len(first_name) > 100 or " " in first_name: params["name_error"] = "Invalid name." error = True if not re.match(email_re, email): params["email_error"] = "That email address is not valid. Nice try Adrien!" error = True # check user doesn't already have a request users = db.GqlQuery("SELECT * FROM InstanceUser WHERE email = :email", email=email) if users.count() > 0: params["email_error"] = "That email address has already been used. Sorry!" error = True if not cResponse.is_valid: self.show_index(c_error=cResponse.error_code, params=params) return if error: self.show_index(params=params) return # Now bung a record in out datastore for later perusal, after we # confirm email if accurate token = hashlib.sha1('%s$%s' % (email, SALT)).hexdigest() # Store email, token user = InstanceUser(first_name=first_name, last_name=last_name, company=company, phone=phone, email=email, token=token); user.put() # Send email mail.send_mail(sender="Acunu.com Downloads <*****@*****.**>", to=email, subject="Your Acunu trial instance", body= EMAIL % {"first_name": first_name, "token": token, "domain_name": self.request.host_url}) self.message("Please check your email for further instructions")
def post(self, ngo_url): post = self.request errors = { "fields": [], "server": False } self.ngo = NgoEntity.get_by_id(ngo_url) if self.ngo is None: self.error(404) return # if we have an ajax request, just return an answer self.is_ajax = self.request.get("ajax", False) def get_post_value(arg, add_to_error_list=True): value = post.get(arg) # if we received a value if value: # it should only contains alpha numeric, spaces and dash if re.match(r'^[\w\s.\-ăîâșț]+$', value, flags=re.I | re.UNICODE) is not None: # additional validation if arg == "cnp" and len(value) != 13: errors["fields"].append(arg) return "" return value # the email has the @ so the first regex will fail elif arg == 'email': # if we found a match if re.match(r'[^@]+@[^@]+\.[^@]+', value) is not None: return value errors["fields"].append(arg) return '' else: errors["fields"].append(arg) elif add_to_error_list: errors["fields"].append(arg) return "" donor_dict = {} # the donor's data donor_dict["first_name"] = get_post_value("nume").title() donor_dict["last_name"] = get_post_value("prenume").title() donor_dict["father"] = get_post_value("tatal").title() donor_dict["cnp"] = get_post_value("cnp", False) donor_dict["email"] = get_post_value("email").lower() donor_dict["tel"] = get_post_value("tel", False) donor_dict["street"] = get_post_value("strada").title() donor_dict["number"] = get_post_value("numar", False) # optional data donor_dict["bl"] = get_post_value("bloc", False) donor_dict["sc"] = get_post_value("scara", False) donor_dict["et"] = get_post_value("etaj", False) donor_dict["ap"] = get_post_value("ap", False) donor_dict["city"] = get_post_value("localitate").title() donor_dict["county"] = get_post_value("judet") # if he would like the ngo to see the donation donor_dict['anonymous'] = post.get('anonim') != 'on' # the ngo data ngo_data = { "name": self.ngo.name, "account": self.ngo.account.upper(), "cif": self.ngo.cif, "special_status": self.ngo.special_status } if len(errors["fields"]): self.return_error(errors) return captcha_response = submit(post.get(CAPTCHA_POST_PARAM), CAPTCHA_PRIVATE_KEY, self.request.remote_addr) # if the captcha is not valid return if not captcha_response.is_valid: errors["fields"].append("codul captcha") self.return_error(errors) return # the user's folder name, it's just his md5 hashed db id user_folder = security.hash_password('123', "md5") # a way to create unique file names # get the local time in iso format # run that through SHA1 hash # output a hex string filename = "{0}/{1}/{2}".format(USER_FORMS, str(user_folder), sha1( datetime.datetime.now().isoformat() ).hexdigest()) pdf = create_pdf(donor_dict, ngo_data) file_url = CloudStorage.save_file(pdf, filename) # close the file after it has been uploaded pdf.close() # create the donor and save it donor = Donor( first_name = donor_dict["first_name"], last_name = donor_dict["last_name"], city = donor_dict["city"], county = donor_dict["county"], email = donor_dict['email'], tel = donor_dict['tel'], anonymous = donor_dict['anonymous'], # make a request to get geo ip data for this user geoip = self.get_geoip_data(), ngo = self.ngo.key, pdf_url = file_url ) donor.put() # set the donor id in cookie self.session["donor_id"] = str(donor.key.id()) self.session["has_cnp"] = bool(donor_dict["cnp"]) # send and email to the donor with a link to the PDF file self.send_email("twopercent-form", donor) # if not an ajax request, redirect if self.is_ajax: self.response.set_status(200) response = { "url": self.uri_for("ngo-twopercent-success", ngo_url=ngo_url), "form_url": file_url } self.response.write(json.dumps(response)) else: self.redirect( self.uri_for("ngo-twopercent-success", ngo_url=ngo_url) )
def save_comment( self ): _ = self.macro.request.getText if get_input(self.macro, 'do' ) != u'comment_add': # This is not a comment post do nothing return if get_cfg(self.macro, 'comment_recaptcha', False ) and not self.passpartout: import captcha self.captcha = captcha.submit ( get_input(self.macro, 'recaptcha_challenge_field'), get_input(self.macro, 'recaptcha_response_field'), get_cfg(self.macro, 'comment_recaptcha_private_key'), self.macro.request.remote_addr ) self.get_comment() self.errors = self.errors_check() if not self.errors: # Save the comment # Find out where to save the comment: if self.moderate: # This commet will be added to the moderation queue page = Page(self.macro.request, get_cfg(self.macro, 'comment_approval_page', 'CommentsApproval')) comment_dir = page.getPagePath('', check_create=0) else: # The comment will be immediately posted page = Page(self.macro.request,self.page_name) comment_dir = page.getPagePath('comments', check_create=1) # Compose the comment structure and write it now = datetime.now() random_str = ''.join([choice(letters + digits) for i in range(20)]) comment_file = '%s-%s.txt' % (now.strftime("%s"), random_str) file_name = os.path.join(comment_dir, comment_file) comment = self.comment comment['page'] = self.page_name comment['time'] = now if get_cfg(self.macro, 'comment_store_addr', False): comment['remote_addr'] = self.macro.request.remote_addr if self.moderate: self.msg = _('Your comment awaits moderation. Thank you.') else: self.msg = _('Your comment has been posted. Thank you.') write_comment( file_name, comment ) if self.moderate: # If we have defined a list of moderators to notify and this user is # moderated then a message is sent to the moderator list moderators = get_cfg(self.macro, 'comment_moderators', None) if moderators: sendmail.sendmail( self.macro.request, moderators.split(','), _('New comment awaits moderation for page %(page)s' % self.comment ), _('New comment awaits moderation:\n\nPage: %(page)s\nFrom: %(user_name)s\nMessage:\n\n%(comment)s\n\n--' % self.comment )) else: # Send notification to page subscribers if the page notify_subscribers(self.macro, self.comment) # clean up the fields to display self.reset_comment()
def register(request, success_url=None, form_class=RegistrationForm, template_name='registration/registration_form.html', extra_context=None): """ Allow a new user to register an account. Following successful registration, issue a redirect; by default, this will be whatever URL corresponds to the named URL pattern ``registration_complete``, which will be ``/accounts/register/complete/`` if using the included URLConf. To change this, point that named pattern at another URL, or pass your preferred URL as the keyword argument ``success_url``. By default, ``registration.forms.RegistrationForm`` will be used as the registration form; to change this, pass a different form class as the ``form_class`` keyword argument. The form class you specify must have a method ``save`` which will create and return the new ``User``. By default, use the template ``registration/registration_form.html``; to change this, pass the name of a template as the keyword argument ``template_name``. **Required arguments** None. **Optional arguments** ``form_class`` The form class to use for registration. ``extra_context`` A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. ``success_url`` The URL to redirect to on successful registration. ``template_name`` A custom template to use. **Context:** ``form`` The registration form. Any extra variables supplied in the ``extra_context`` argument (see above). **Template:** registration/registration_form.html or ``template_name`` keyword argument. """ test_cookie_worked = True if request.method == 'POST': # Check the test cookie test_cookie_worked = request.session.test_cookie_worked() if test_cookie_worked: request.session.delete_test_cookie() # Check the captcha if settings.ACCOUNT_REGISTRATION_USE_RECAPTCHA: try: check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR']) except KeyError: # To avoid getting error e-mails when spammers fail at scripting ;) check_captcha = captcha.RecaptchaResponse(is_valid=False) # Check the form form = form_class(data=request.POST, files=request.FILES) if form.is_valid() and test_cookie_worked and (not(settings.ACCOUNT_REGISTRATION_USE_RECAPTCHA) or check_captcha.is_valid): new_user = form.save() # success_url needs to be dynamically generated here; setting a # a default value using reverse() will cause circular-import # problems with the default URLConf for this application, which # imports this file. return HttpResponseRedirect(success_url or reverse('registration_complete')) if settings.ACCOUNT_REGISTRATION_USE_RECAPTCHA and not(check_captcha.is_valid): form.errors['captcha'] = '<ul class="errorlist"><li>Incorrect CAPTCHA solution.</li></ul>' else: form = form_class() if extra_context is None: extra_context = {} request.session.set_test_cookie() context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value html_captcha = None if settings.ACCOUNT_REGISTRATION_USE_RECAPTCHA: html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY) return render_to_response(template_name, { 'form': form, 'captcha': html_captcha, 'test_cookie_worked': test_cookie_worked, }, context_instance=context)
def post(self): post = self.request first_name = post.get('nume') last_name = post.get('prenume') email = post.get('email') password = post.get('parola') if not first_name: self.template_values["errors"] = "Campul nume nu poate fi gol." self.render() return if not last_name: self.template_values["errors"] = "Campul prenume nu poate fi gol." self.render() return if not email: self.template_values["errors"] = "Campul email nu poate fi gol." self.render() return if not password: self.template_values["errors"] = "Campul parola nu poate fi gol." self.render() return captcha_response = submit(post.get(CAPTCHA_POST_PARAM), CAPTCHA_PRIVATE_KEY, post.remote_addr) # if the captcha is not valid return if not captcha_response.is_valid: self.template_values[ "errors"] = "Se pare ca a fost o problema cu verificarea reCAPTCHA. Te rugam sa incerci din nou." self.render() return unique_properties = ['email'] success, user = self.user_model.create_user(email, unique_properties, first_name=first_name, last_name=last_name, email=email, password_raw=password, verified=False) if not success: #user_data is a tuple self.template_values[ "errors"] = "Exista deja un cont cu aceasta adresa." self.template_values.update({ "nume": first_name, "prenume": last_name, "email": email }) self.render() return self.send_email("signup", user) try: # login the user after signup self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) # redirect to my account self.redirect(self.uri_for('contul-meu')) except Exception, e: self.template_values[ "errors"] = "Se pare ca a aparut o problema. Te rugam sa incerci din nou" self.render()
def register_user(request): global base_title global global_nav, user_nav title = base_title + "Register" global_navigation=global_nav() # If user is not logged on if not request.user.is_authenticated(): # Return user navigation for an anonymous session user_navigation = user_nav(False) # Set up captcha html. from settings import captcha_publickey, captcha_privatekey captcha_test = captcha.displayhtml(captcha_publickey) # If user has sent POST data (not logged in) if request.method == 'POST': registration_errors = [] # Error list ''' Check and validate data ''' # Is human? HumanTestResult = captcha.submit( request.POST["recaptcha_challenge_field"], request.POST["recaptcha_response_field"], captcha_privatekey, get_ip(request) ) # If not human: display errors if HumanTestResult.is_valid: # Matching passwords? password = v.clean_password(request.POST["passw"]) if not request.POST["passw"] == request.POST["repassw"]: registration_errors.append("Passwords don't match.") if password == None: registration_errors.append("No password entered.") elif password == -1: registration_errors.append("Passwords have to be at least 5 characters.") # Username related errors username = v.clean_username(request.POST["usern"]) if username == None: registration_errors.append("No username entered.") elif username == -2: registration_errors.append("This username isn't available.") elif username == -1: registration_errors.append("Username's can only be 30 characters.") elif username == False: registration_errors.append("Username wasn't just characters numbers ") # Email related errors email = v.clean_email(request.POST["email"]) if email == None: registration_errors.append("No email entered.") elif email == -2: registration_errors.append("This email already has an account.") elif email == -1: registration_errors.append("Emails can only be 245 characters.") elif email == False: registration_errors.append("Invalid email.") # Invalid CAPTCHA, display only that error giving no more information to the bot else: registration_errors.append("Invalid human verification code.") captcha_test = captcha.displayhtml( captcha_publickey, False, HumanTestResult.error_code ) # Connect to SMTP server connection = mail.get_connection() connection.open() # If no errors: create user. if len(registration_errors) == 0: new_user = User.objects.create_user( username, email, request.POST["repassw"] ) new_user.is_active = True new_user.save() # Create activation key and user profile activation_key = KeyGen() # Add 2 hours so a recovery key can be made instantly after # account creation. thetime = new_user.date_joined + datetime.timedelta(hours=2) profile = UserProfile( activate_key=activation_key, activated=False, recovery_time=thetime, user=new_user) profile.save() # User is created and saved. Send an activation link via email # Activation link message_activateurl = baseurl+"/activate/?key="+str(activation_key) message_activateurl = message_activateurl+"&user="******"/deactivate/?key="+str(activation_key) message_deactivateurl = message_deactivateurl+"&user="******"<$user>", str(new_user.username)) message = message.replace("<$activatelink>", message_activateurl) message = message.replace("<$disablelink>", message_deactivateurl) # Send email email = EmailMessage( "Account Activation", message, EMAIL_HOST_USER, [new_user.email] ) email.send() connection.close() # Return new account page accountname = new_user.username response = render_to_response( 'auth/newaccount.html', locals(), context_instance=RequestContext(request) ) else: # Return registration form with errors in registration_errors response = render_to_response( 'auth/registration.html', locals(), context_instance=RequestContext(request) ) # If user hasn't sent POST data (not logged on) else: response = render_to_response( 'auth/registration.html', locals(), context_instance=RequestContext(request) ) # User is logged on else: user_navigation = user_nav(request.user.username) error = "You cannot register while logged in." response = render_to_response( 'error.html', locals() ) return response
def signupUser(self, username, password, confirm, name, email, institution, abbrev, ms_eu, ms_other, qualification, REQUEST=None, RESPONSE=None): """ process the request for a new account """ if REQUEST is not None: session = REQUEST.SESSION ms = ms_eu or ms_other if self.use_captcha: #check if captcha is valid check_captcha = captcha.submit(REQUEST.get('recaptcha_challenge_field', ''), REQUEST.get('recaptcha_response_field', ''), getattr(self, 'private_key'), REQUEST.get('REMOTE_ADDR', '') ) if check_captcha.is_valid is False: #Captcha is wrong show a error . session.set('err_captcha', 'Incorrect. Try again') #validate form fields if not username: session.set('err_username', 'Please enter a username') else: #check username username_expr = re.compile('^[a-z0-9]*$') if not re.match(username_expr, username): session.set('err_username', 'Only lowercase letters and numbers allowed') if self.acl_users.getUser(username): session.set('err_username', 'Sorry, that username already exists!') if not password or not confirm: session.set('err_password', 'Password and confirmation must be specified') if (password or confirm) and (password != confirm): session.set('err_password', 'Passwords must match!') email_expr = re.compile('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$', re.IGNORECASE) if not re.match(email_expr, email): session.set('err_email', 'Please enter a correct email address') if not ms: session.set('err_ms', 'Please enter a Member State') if not institution: session.set('err_institution', 'Please enter the Institution') if not name: session.set('err_name', 'Please enter your name') if not session.keys(): #create account self.create_account(username, password, confirm) self.create_account_details(username, name, email, institution, abbrev, ms, qualification) #send an email with the activation link self.send_confirmation(username, name, email) session.set('op_completed', True) else: #put form field values on session session.set('username', username) session.set('password', password) session.set('confirm', confirm) session.set('name', name) session.set('email', email) session.set('institution', institution) session.set('abbrev', abbrev) session.set('ms_eu', ms_eu) session.set('ms_other', ms_other) session.set('qualification', qualification) return RESPONSE.redirect(REQUEST.HTTP_REFERER) else: raise NotImplemented