Ejemplo n.º 1
0
    def get(self):
        chtml = captcha.displayhtml(
            public_key="6LcfNesSAAAAALpz578J4CXiHk3hwgPZIWSAvtVe",
            use_ssl=False,
            error=None)

        template_values = {'captchahtml': chtml}

        #self.response.write(template_values)

        self.response.write("""

<html> 
<h1> Go Bromius Image Sharer </h1>
</br>
<p> Share an image! </p>

<form name="post_image_form" action="post_image" method="post" enctype="multipart/form-data">

File name:<input type="file" name="imgfile"> <br>
		""")

        self.response.write(chtml)
        self.response.write("""
<input type="submit" value="Submit"</br>

</form>

</html>

		""")
Ejemplo n.º 2
0
	def get(self):
		chtml = captcha.displayhtml(
		public_key = "6LcfNesSAAAAALpz578J4CXiHk3hwgPZIWSAvtVe",
		use_ssl = False,
		error = None)

		template_values = {
		'captchahtml': chtml
		}

		
		#self.response.write(template_values)

		self.response.write("""

<html> 
<h1> Go Bromius Image Sharer </h1>
</br>
<p> Share an image! </p>

<form name="post_image_form" action="post_image" method="post" enctype="multipart/form-data">

File name:<input type="file" name="imgfile"> <br>
		""")

		self.response.write(chtml)
		self.response.write("""
<input type="submit" value="Submit"</br>

</form>

</html>

		""")
Ejemplo n.º 3
0
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 )
Ejemplo n.º 4
0
    def renderInPage(self):
        """
        Render comments form in page context.
        """
        _ = self.macro.request.getText
        html = u'''<div class="comments_form">
        <form method="POST" action="%(page_uri)s">
        <input type="hidden" name="do" value="comment_add">
        ''' % { 'page_uri': self.macro.request.request.url }

        if self.msg:
            html += u'<div id="comment_message">'
            html += u'<p>%s</p>' % self.msg
            html += u'</div>'

        if self.errors:
            html += u'<div id="comment_error">'
            if len(self.errors) > 1:
                html += u'<p>%s</p><ul>'  % _('Your comment has errors:')
            else:
                html += u'<p>%s</p><ul>'  % _('Your comment has one error:')
            for error in self.errors:
                html += u'<li>%s</li>' % error
            html += u'</div>'

        html += '''
        <ul>
            <li>
                <span class="name">%(name_label)s</span>
                <input type="text" id="name" maxlength=128 name="user_name"
                           value="%(user_name)s" size=8>
                <span class="comment_body">%(comment_label)s</span>
                <input type="text" name="comment" value="%(comment)s" size=64>
            ''' % {
            'name_label': u'名前: ',
            'comment_label': u'コメント: ',
            'page_name': self.page_name,
            'user_name': self.comment['user_name'],
            'comment':   self.comment['comment'],}

        if get_cfg(self.macro, 'comment_recaptcha', False) and not self.passpartout:
            import captcha
            html += u"""
            <tr>
                <th>%(recaptcha_label)s</th>
                <td>%(recaptcha)s</td>
            </tr>""" % {
            'recaptcha' : captcha.displayhtml(
                                get_cfg(self.macro, 'comment_recaptcha_public_key')),
            'recaptcha_label': _('Are you human?') }

        html += """
             <input type="submit" value="%(label)s">
        </form></div>""" % { 'label': _('Send comment') }

        try:
            return self.macro.formatter.rawHTML(html)
        except:
            return self.macro.formatter.escapedText('')
Ejemplo n.º 5
0
    def show_index(self, params={}, c_error=None):
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')

        params['chtml'] = captcha.displayhtml(
          public_key = RECAPTCHA_PUBLIC,
          use_ssl = False,
          error = c_error)
          
        self.response.out.write(template.render(path, params))
Ejemplo n.º 6
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 )
Ejemplo n.º 7
0
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"
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
	def get(self):
		chtml = captcha.displayhtml(
		public_key = recaptcha_public_key,
		use_ssl = False,
		error = None)
			
		# Set the template parameters to pass back to the template.
		template_values = {
			'categories': categories(),
			'captchahtml': chtml
		}
	
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))
Ejemplo n.º 10
0
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),
    )
Ejemplo n.º 11
0
    def get(self):
        greetings="parametro"
        
        chtml = captcha.displayhtml(
                                    public_key = "6LfAO78SAAAAAHsj8mGWXKvrG8QWxMBWznhLZxTe",
                                    use_ssl = False,
                                    error = None)
        

        template_values = {
            'greetings': greetings,
             'captchahtml': chtml,
           }

        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, template_values))
Ejemplo n.º 12
0
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))
Ejemplo n.º 13
0
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 )
Ejemplo n.º 14
0
	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))
Ejemplo n.º 15
0
    def get(self, slug):
        article = Article.get_for_slug(slug)
        
        comments = None
        
        chtml = captcha.displayhtml(  public_key = "6LdnKr8SAAAAANd9vNW6i-2yMeaEaO2vgeDWn3dh",  use_ssl = False,  error = None)
        
        if article:
            comments = Comment.get_all_by_articleId(article.id)
            template = 'show-single-article.html'
            articles = [article]
            more = None
        else:
            template = 'not-found.html'
            articles = []

        self.response.out.write(self.render_articles(articles=articles,
                                                     request=self.request,
                                                     recent=self.get_recent(),
                                                     template_name=template,
                                                     comments=comments,
                                                     chtml=chtml))
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
def recover_user(request):
	global base_title
	global global_nav, user_nav
	
	title = base_title + "Recovery"
	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.
		captcha_test = captcha.displayhtml(captcha_publickey)
		
		# If user has sent POST data (not logged in)
		if request.method == 'POST':
			# Check info via regex
			u_name = v.clean_usernameRE(request.POST["usern"])
			email = v.clean_emailRE(request.POST["email"])
			

			if email == request.POST["email"] and u_name:
				try:
					user = User.objects.get(username__iexact=u_name)
					user_profile = get_or_create_profile(user)
					
					# Current time
					time_now = now()					
					
					# Recovery time
					recovery_time = user_profile.recovery_time
					
					if time_now > recovery_time:
						# Key has been requested too many times in 2 hours.
						error = "Recovery keys can only be requested once every 2 hours."
						response = render_to_response(
							'error.html', 
							locals()
							)
					else:
						# Connect to SMTP server
						connection = mail.get_connection()
						connection.open()
						
						# Create a recovery key
						user_profile.recovery_key = KeyGen()
						user_profile.save()

						# Create account recovery link
						message_recoveryurl = baseurl+"/recover/?key="+str(user_profile.recovery_key)
						message_recoveryurl = message_recoveryurl+"&user="******"<$user>", str(user.username))
						message = message.replace("<$recoverylink>", message_recoveryurl)
						message = message.replace("<$time>", str(user_profile.recovery_time))
				
						# Send email
						email = EmailMessage(
							"Account Recovery", 
							message,
							EMAIL_HOST_USER,
							[user.email]
							)

						email.send()
						connection.close()
						
						# Tell user to check their email.
						error = "Check your email for a recovery link."
						response = render_to_response(	
							'error.html', 
							locals()
							)

				except User.DoesNotExist:
					error = "No user with that email exists."
					response = render_to_response(	
						'error.html', 
						locals()
						)
			else:
				error = "No user with that email exists."
				response = render_to_response(	
					'error.html', 
					locals()
					)
		else:
		# Didn't submit, give recovery form.
			response = render_to_response(
				'auth/recovery.html',
				locals(),
				context_instance=RequestContext(request)
				)
	# You're signed in, no recovery for you.
	else:
		return HttpResponseRedirect('/')

	return response
Ejemplo n.º 18
0
def recaptcha(context):
        return {'captcha': captcha.displayhtml(RECAPTCHA_PUB_KEY)}
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
 def showCaptcha(self):
     """ """
     return captcha.displayhtml(getattr(self, 'public_key'))
Ejemplo n.º 21
0
    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))
Ejemplo n.º 22
0
def recover_user(request):
    global base_title
    global global_nav, user_nav

    title = base_title + "Recovery"
    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.
        captcha_test = captcha.displayhtml(captcha_publickey)

        # If user has sent POST data (not logged in)
        if request.method == 'POST':
            # Check info via regex
            u_name = v.clean_usernameRE(request.POST["usern"])
            email = v.clean_emailRE(request.POST["email"])

            if email == request.POST["email"] and u_name:
                try:
                    user = User.objects.get(username__iexact=u_name)
                    user_profile = get_or_create_profile(user)

                    # Current time
                    time_now = now()

                    # Recovery time
                    recovery_time = user_profile.recovery_time

                    if time_now > recovery_time:
                        # Key has been requested too many times in 2 hours.
                        error = "Recovery keys can only be requested once every 2 hours."
                        response = render_to_response('error.html', locals())
                    else:
                        # Connect to SMTP server
                        connection = mail.get_connection()
                        connection.open()

                        # Create a recovery key
                        user_profile.recovery_key = KeyGen()
                        user_profile.save()

                        # Create account recovery link
                        message_recoveryurl = baseurl + "/recover/?key=" + str(
                            user_profile.recovery_key)
                        message_recoveryurl = message_recoveryurl + "&user="******"<$user>",
                                                  str(user.username))
                        message = message.replace("<$recoverylink>",
                                                  message_recoveryurl)
                        message = message.replace(
                            "<$time>", str(user_profile.recovery_time))

                        # Send email
                        email = EmailMessage("Account Recovery", message,
                                             EMAIL_HOST_USER, [user.email])

                        email.send()
                        connection.close()

                        # Tell user to check their email.
                        error = "Check your email for a recovery link."
                        response = render_to_response('error.html', locals())

                except User.DoesNotExist:
                    error = "No user with that email exists."
                    response = render_to_response('error.html', locals())
            else:
                error = "No user with that email exists."
                response = render_to_response('error.html', locals())
        else:
            # Didn't submit, give recovery form.
            response = render_to_response(
                'auth/recovery.html',
                locals(),
                context_instance=RequestContext(request))
    # You're signed in, no recovery for you.
    else:
        return HttpResponseRedirect('/')

    return response
Ejemplo n.º 23
0
	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))
Ejemplo n.º 24
0
	def get(self):
		chtml = captcha.displayhtml(public_key = NewHandler.CAPTCHA_PUBLIC_KEY,use_ssl = False,error = None)
		template_values = {'captchahtml': chtml, "session": self.session}
		template = JINJA_ENVIRONMENT.get_template('user/new.html')
		self.response.write(template.render(template_values))
Ejemplo n.º 25
0
    def renderInPage(self):
        """
        Render comments form in page context.
        """
        _ = self.macro.request.getText
        html = u"""<div class="comments_form">
        <form method="POST" action="%(page_uri)s">
        <input type="hidden" name="do" value="comment_add">
        <table>""" % {
            "page_uri": self.macro.request.request_uri
        }

        html += """
            <tr>
                <td colspan=2 id="center_cell"><b>%(header)s</b></td>
            </tr>
            <tr>
                <th>%(name_label)s</th>
                <td>
                    <input type="text" id="name" maxlength=128 name="user_name"
                           value="%(user_name)s">
                </td>
            </tr>
            <tr>
                <th>%(comment_label)s</th>
                <td>
                    <textarea name="comment">%(comment)s</textarea>
                </td>
            </tr>
            """ % {
            "page_name": self.page_name,
            "user_name": self.comment["user_name"],
            "comment": self.comment["comment"],
            "header": _("Comment this page"),
            "name_label": _("Name:"),
            "comment_label": _("Comment:"),
        }

        if self.msg:
            html += u'<tr><td colspan = 2><div id="comment_message">'
            html += u"<p>%s</p>" % self.msg
            html += u"</div></td></tr>"

        if self.errors:
            html += u'<tr><td colspan = 2><div id="comment_error">'
            if len(self.errors) > 1:
                html += u"<p>%s</p><ul>" % _("Your comment has errors:")
            else:
                html += u"<p>%s</p><ul>" % _("Your comment has one error:")
            for error in self.errors:
                html += u"<li>%s</li>" % error
            html += u"</ul></div></td></tr>"

        if get_cfg(self.macro, "comment_recaptcha", False):
            import captcha

            html += u"""
            <tr>
                <th>%(recaptcha_label)s</th>
                <td>%(recaptcha)s</td>
            </tr>""" % {
                "recaptcha": captcha.displayhtml(get_cfg(self.macro, "comment_recaptcha_public_key")),
                "recaptcha_label": _("Are you human?"),
            }

        html += """
             <tr>
                <td colspan=2 id="center_cell"><input type="submit" value="%(label)s">
                </td>
            </tr>
        </table></form></div>""" % {
            "label": _("Send comment")
        }

        try:
            return self.macro.formatter.rawHTML(html)
        except:
            return self.macro.formatter.escapedText("")
Ejemplo n.º 26
0
from django.contrib import admin
from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap
from django.views.generic import list_detail
from django.views.decorators.cache import cache_page
from colddirt.dirty.models import Dirt, Word
from colddirt.dirty import views
from colddirt.feeds import LatestDirts, PerDirt
from colddirt.forms import *
import captcha

rand_dict = {
    'queryset': Dirt.objects.order_by('?')[:250],
    'template_object_name' : 'dirty',
    'paginate_by': 15,
    'extra_context': {'form': DirtyForm().as_ul(),
                      'html_captcha': captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)}
}  

newdirt_dict = {
    'queryset': Dirt.objects.order_by('-publish_date')[:250],
    'template_object_name' : 'dirty',
    'paginate_by': 15,
    'extra_context': {'form': DirtyForm().as_ul(),
                      'html_captcha': captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)}
} 

word_dict = {
    'queryset': Dirt.objects.all(), 
    'template_object_name' : 'dirt_object',
    'extra_context': {'form': DirtyForm().as_ul(),
                      'html_captcha': captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)}
Ejemplo n.º 27
0
        t = jinja_env.get_template(template)
        return t.render(params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))


class Post(db.Model):
    content = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    lang = db.StringProperty()
    name = db.StringProperty()


chtml = captcha.displayhtml(
    public_key="6Lf4R9QSAAAAAJ5HtpuRxDFBbEIyENx8RYvJLwJO",
    use_ssl=False,
    error=None)


class NewPost(Handler):
    def render_newpost(self, name="", content="", error=""):
        global chtml
        self.render("newpost.html",
                    name=name,
                    content=content,
                    error=error,
                    chtml=chtml)

    def get(self):
        self.render_newpost()
Ejemplo n.º 28
0
 def render(self, name, value, attrs=None):
     html = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)
     return mark_safe(u'%s' % html)
Ejemplo n.º 29
0
def recaptcha(context):
    return {"captcha": captcha.displayhtml(RECAPTCHA_PUB_KEY)}
Ejemplo n.º 30
0
 def render(self, name, value, attrs=None):
     return mark_safe(u'%s' % captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY))
Ejemplo n.º 31
0
 def get(self):
     pageParams = checkLogin(self)
     pageParams['captcha'] = captcha.displayhtml(public_key = "6Lc_gb8SAAAAAJWVBIquKY9vHVQEAyhRitnxYb3A",use_ssl=False, error=None)
     self.response.out.write( template.render('contact.html', pageParams))
Ejemplo n.º 32
0
	def render_str(self, template, **params):
		t = jinja_env.get_template(template)
		return t.render(params)

	def render(self, template, **kw):
		self.write(self.render_str(template, **kw))

class Post(db.Model):
	content = db.TextProperty(required = True)
	created = db.DateTimeProperty(auto_now_add = True)
	lang = db.StringProperty()
	name = db.StringProperty()

chtml = captcha.displayhtml(
    public_key = "6Lf4R9QSAAAAAJ5HtpuRxDFBbEIyENx8RYvJLwJO",
    use_ssl = False,
    error = None)

class NewPost(Handler):
	def render_newpost(self, name="", content="", error=""):
                global chtml
                self.render("newpost.html", name=name, content=content, error=error, chtml=chtml)

	def get(self):
		self.render_newpost()

	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')
Ejemplo n.º 33
0
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