Ejemplo n.º 1
0
def register(request):
    captcha_error = ""
    captcha_valid = True
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if settings.USE_CAPTCHA:        
            captcha_response = captcha.submit(request.POST.get("recaptcha_challenge_field", None),  
                                           request.POST.get("recaptcha_response_field", None),  
                                           settings.RECAPTCHA_PRIVATE_KEY,  
                                           request.META.get("REMOTE_ADDR", None))  
            captcha_valid = captcha_response.is_valid
        if not captcha_valid:  
            captcha_error = "&error=%s" % captcha_response.error_code 
        else:
            if form.is_valid():
                u = form.save()
                msg = render_to_string('registration/welcome.mail',
                            {'username': u.username},
                            context_instance = RequestContext(request))    
                u.email_user(_('Welcome to %(project)s') % {'project':settings.PROJECT_NAME}, msg)
                return render_to_response("contact/message.html",
                                          {'message': _('You can now sign in with the choosen username and password.')},
                                          context_instance = RequestContext(request))
    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('home'))
        
        form = RegistrationForm()
    return render_to_response("registration/register.html",
                              {'form': form,
                               'captcha_error': captcha_error,
                               'settings': settings},
                               context_instance = RequestContext(request))
Ejemplo n.º 2
0
    def clean(self):
        siteconfig = SiteConfiguration.objects.get_current()

        if siteconfig.get('auth_registration_show_captcha'):
            challenge = self.cleaned_data.get('recaptcha_challenge_field',
                                              None)
            response = self.cleaned_data.get('recaptcha_response_field', None)

            if challenge and response:
                captcha_response = \
                    captcha.submit(
                        challenge,
                        response,
                        siteconfig.get('recaptcha_private_key'),
                        self.request.META.get('REMOTE_ADDR', None))

                if not captcha_response.is_valid:
                    self.captcha_error_query_str = '&error=%s' % \
                        captcha_response.error_code

                    # This isn't actually seen in the Review Board UI,
                    # as the reCAPTCHA widget itself displays the error
                    # message. However, this may be useful for testing or
                    # debugging.
                    raise forms.ValidationError(
                        _("The text you entered didn't match what was "
                          "displayed"))
            else:
                self.captcha_error_query_str = '&error=incorrect-captcha-sol'

                raise forms.ValidationError(
                    _('You need to respond to the captcha'))

        return super(RegistrationForm, self).clean()
def save_child(request,parent=None,parentString=''):
	request.session['errors'] = ''
	if settings.USE_RECAPTCHA:
		response = captcha.submit(request.POST.get('recaptcha_challenge_field'),request.POST.get('recaptcha_response_field'),settings.RECAPTCHA_PRIVATE_KEY,request.META['REMOTE_ADDR']) 
		if not response.is_valid:
			request.session['errors'] = 'captcha'
			return redirect(settings.URL_ROOT+parentString)

	email = request.POST.get('email', '')
	request.session['email'] = email
	if not is_valid_email(email):
		request.session['errors'] = 'email'
		return redirect(settings.URL_ROOT+parentString) #invalid email, send back to start
	hash = hash_email(email)
	ip = request.META.get('REMOTE_ADDR')
	slider = 50
	newp = Person.objects.filter(email = email)
	dup = (len(newp) > 0)
	if dup:
		newp = newp[0]
		rating = Rating.objects.filter(person = newp)
		if len(rating) > 0:
			slider = rating[0].rating
	else:
		if parent == None or len(parent) == 0:
			newp = Person(email = email, hash = hash, ipaddress=ip, influence=0,parent_node=None,session_key=str(request.session.session_key))
			newp.save()
		else:
			newp = Person(email = email, hash = hash, ipaddress=ip, parent=parent[0].email,parent_node=parent[0],influence=0, session_key=str(request.session.session_key))
			newp.save()
			update_score(newp)
	t = loader.get_template('save.html')
	c = RequestContext(request, {'link':settings.URL_ROOT+str(newp.id),'score_link':settings.URL_ROOT+'score/'+str(newp.id),'csrf_token':csrf(request)['csrf_token'],'url':settings.URL_ROOT,'saved': '','slider': slider,'dup':dup})
	return HttpResponse(t.render(c))
Ejemplo n.º 4
0
    def wrapped(config,
                users,
                messages,
                *args,
                **kwargs):
      if config.captcha.enabled:
        from recaptcha.client import captcha

        challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
        response = bottle.request.POST.pop('recaptcha_response_field', None)

        if challenge is None or response is None:
          messages.error('Captcha values are missing')
          bottle.redirect('/')

        result = captcha.submit(challenge,
                                response,
                                config.captcha.recaptcha_private_key,
                                bottle.request.remote_addr)

        if not result.is_valid:
          messages.error('Captcha invalid')
          bottle.redirect(__on_error__)

      # Call the wrapped function
      return func(*args,
                  **kwargs)
Ejemplo n.º 5
0
def signup(request):
	if 'user' in request.session:
		return HttpResponseRedirect("/bookManiacs/")
	else:
		if 'name' in request.POST:
			name        = request.POST['name']
			email       = request.POST['email']
			phone       = request.POST['phone']
			password    = request.POST['pass']
			confirmPass = request.POST['confPass']
			bhawan      = request.POST['bhawan']
			room        = request.POST['room']
			userExist = Profile.objects.filter(email=email).exists()
			if userExist==False:
				# if makeValidation():
				if password == confirmPass:
					response = captcha.submit(  
						request.POST.get('recaptcha_challenge_field'),
						request.POST.get('recaptcha_response_field'),
						'6Le7XvASAAAAAKk5cQcHOwxBRNjKBl49I_yRw2ym',
						request.META['REMOTE_ADDR'],)
					if response.is_valid:
						p = Profile.objects.create(name = name, email = email, password = password, mobile_number = phone, room_number = room, hostel = bhawan)
						messageString = 'you have registered successfully'
						return render(request, 'bookManiacs/login.html', {'messageString': messageString})
					else:
						errorString = 'please fill the captcha correctly'
				else:
					errorString = 'your password did not match with the confirm password'
			else:
				errorString = 'This Id is already registered'
			return render(request, 'bookManiacs/signup.html', {'errorString': errorString})
		else:
			return render(request, 'bookManiacs/signup.html')
Ejemplo n.º 6
0
def signup(req):
	'''注册'''
	if req.user.is_authenticated():
		return HttpResponseRedirect('/')
	captcha_ok = True
	if req.method == 'POST':
		form = SignUpForm(req.POST)
		if form.is_valid():
			# check reCAPTCHA
			challenge, response = req.POST.get('recaptcha_challenge_field', ''), req.POST.get('recaptcha_response_field', '')
			if challenge and response:
				ret = captcha.submit(challenge, response, settings.CAPTCHA_PRIVATE_KEY, req.META['REMOTE_ADDR'])
				if ret.is_valid:
					user = form.save()
					# hack for not using authenticate()
					user.backend = 'django.contrib.auth.backends.ModelBackend'
					login(req, user)
					return HttpResponseRedirect('/')
			captcha_ok = False
	else:
		form = SignUpForm()
	return render_to_response('signup.html', {
		'form': form,
		'captcha_ok': captcha_ok,
	}, context_instance=RequestContext(req))
Ejemplo n.º 7
0
def register(request):
    if request.method == 'POST':
        if 'recaptcha_challenge_field' in 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 not check_captcha.is_valid:
                messages.error(request, "Captcha was incorrect!") #% check_captcha.error_code)
                return HttpResponseRedirect(reverse('register'))

        form = RegisterForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username,email,password = cd['username'], cd['email'], cd['password']   
            
            new_user = User.objects.create_user(username = username, email = email, password = password)  

            #TODO: fix this, weird postgres issue in django 1.3 see trac issue #15682
            user = User.objects.get(username=new_user.username)
            profile = UserProfile.objects.create(user=user)
            
            messages.success(request, "Thanks for registering %s! Welcome to tehorng." % new_user)
            
            authed_user = authenticate(username=username, password=password)
            login(request, authed_user)
            return HttpResponseRedirect(reverse('profile'))    
    else:
        form = RegisterForm(initial=request.POST)
    return render_to_response('registration/register.html', {
        'form': form,
        'captcha': mark_safe(captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)),
    }, context_instance=RequestContext(request))
Ejemplo n.º 8
0
 def post(self):
     p = Pregunta()
     p.titulo = cgi.escape(self.request.get('titulo'), True)
     p.contenido = cgi.escape(self.request.get('contenido'), True)
     p.get_tags( self.sc.get_alltags() )
     p.os = self.request.environ['HTTP_USER_AGENT']
     if users.get_current_user() and self.request.get('titulo') and self.request.get('contenido'):
         if self.request.get('anonimo') != 'on':
             p.autor = users.get_current_user()
         try:
             p.put()
             self.redirect( p.get_link() )
         except:
             self.redirect('/error/503')
     elif self.request.get('titulo') and self.request.get('contenido'):
         challenge = self.request.get('recaptcha_challenge_field')
         response  = self.request.get('recaptcha_response_field')
         remoteip  = self.request.remote_addr
         cResponse = captcha.submit(
             challenge,
             response,
             RECAPTCHA_PRIVATE_KEY,
             remoteip)
         if cResponse.is_valid:
             try:
                 p.put()
                 self.redirect( p.get_link() )
             except:
                 self.redirect('/error/503')
         else:
             self.redirect('/error/403c')
     else:
         self.redirect('/error/403')
Ejemplo n.º 9
0
def custom_register (request, *args, **kwargs):
    """
    Wrap the django-registration register view in a custom view, so that we can
    use reCAPTCHA.
    """
    if request.method == "POST":
        # Check the captcha
        check_captcha = captcha.submit(\
            request.POST["recaptcha_challenge_field"],
            request.POST["recaptcha_response_field"],
            settings.RECAPTCHA_PRIVATE_KEY,
            request.META["REMOTE_ADDR"])
        
        if not check_captcha.is_valid:
            # If the captcha is wrong, error
            form    = kwargs["form_class"](request.POST)
            context = {"form": form, "recaptcha_failed": True}
            
            if "extra_context" in kwargs:
                context.update(kwargs["extra_context"])
            
            return render_to_response("registration/registration_form.html",
                context, context_instance=RequestContext(request))
        
    return register(request, *args, **kwargs)
Ejemplo n.º 10
0
    def create_user(self, r, email, password, confirm, mobile, captcha_challenge, captcha_response):
        remote_ip = r.environ['REMOTE_ADDR']
        captcha_result = captcha.submit(captcha_challenge, captcha_response, self.captcha_key, remote_ip)
        if captcha_result.is_valid:
            # check for existing email and mobile
            self._check_duplicate_email(r.connection, email)
            self._check_duplicate_mobile(r.connection, mobile)

            log.debug('captcha is ok, saving registration data')
            confirm = ConfirmationCode()
            confirm.code = self._confirmation_code()
            mobile = ''.join(self.non_digits_regex.split(mobile))
            confirm.data = self._serialize(dict(email=email.lower(),
                                                password=password, 
                                                mobile=mobile))
            confirm.created = datetime.utcnow()
            status, data = r.hub.sendConfirmation(mobile, confirm.code)
            if str(status) == 'ok':
                r.session.save(confirm)
                r.session.flush()
                return dict(success=True, sms_id=data)
            else:
                log.debug('Failed to send sms: %s', data)
                raise ValidationFailedException(dict(mobile='Unable to send SMS: %s' % data))
        else:
            log.debug('captcha is invalid')
            raise ValidationFailedException(dict(captcha_response='Validation failed'))
Ejemplo n.º 11
0
def register(request):
    if request.method == "POST":
        if "recaptcha_challenge_field" in 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 not check_captcha.is_valid:
                messages.error(request, "Captcha didn't pan out! '%s'" % check_captcha.error_code)
                return HttpResponseRedirect(reverse("register"))

        form = RegisterForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username, email, password = cd["username"], cd["email"], cd["password"]
            new_user = User.objects.create_user(username=username, email=email, password=password)
            profile = UserProfile.objects.create(user=new_user)
            messages.success(request, "Thanks for registering %s! Welcome to tehorng." % new_user)

            authed_user = authenticate(username=username, password=password)
            login(request, authed_user)
            return HttpResponseRedirect(reverse("profile"))
    else:
        form = RegisterForm()
    return render_to_response(
        "registration/register.html",
        {"form": form, "captcha": mark_safe(captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY))},
        context_instance=RequestContext(request),
    )
Ejemplo n.º 12
0
def index(request):
    info = {}
    
    info['links'] = Link.objects.filter(is_public=True)
    
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            r = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
            if not r.is_valid:
                return redirect('/contact/') # Invalid form entry
            
            # Process the data in form.cleaned_data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            recipients = ['*****@*****.**', '*****@*****.**']
            
            email = EmailMessage('Contact Message From ' + name + ' - JessicaSteiber.com', message, email, recipients)
            email.send()
            
            info['msg'] = '<p class="success">Message successfully sent.</p>'
            info['form'] = ContactForm()
    else:
        info['form'] = ContactForm() # An unbound form
        info['msg'] = ''
    
    verses = Verse.objects.filter(is_public=True).order_by('?')
    info['verse'] = verses[0]
    
    info['active'] = 'contact'
    
    return render_to_response('contact/index.html', { 'info': info }, context_instance=RequestContext(request))
Ejemplo n.º 13
0
  def post(self):
    target_name = self.request.get('id')
    message = self.request.get('email_message') or None
    sender_email = self.request.get('email_address') or ''
    target = get_target(target_name)

    if not target:
      self.response.set_status(404)
      return

    if target.anonymous:
      response = captcha.submit(
          self.request.get('recaptcha_challenge_field'),
          self.request.get('recaptcha_response_field'),
          RECAPTCHA_PRIVATE_KEY,
          self.request.remote_addr)
      if not response.is_valid:
        logging.info('reCaptcha failed: error_code=%s', response.error_code)
        self.response.set_status(400)
        return
      reply_to = sender_email
    else:
      current_user = users.get_current_user()
      if not current_user:
        self.response.set_status(400)
        return
      reply_to = current_user.email()

    taskqueue.add(
        url='/work/send_email',
        params=dict(target_name=target_name,
                    reply_to=reply_to,
                    message=message),
        queue_name='send')
    logging.info('Enqueued email for target=%s', target_name)
Ejemplo n.º 14
0
    def pre_process_request(self, req, handler):
        if isinstance(handler, RegistrationModule):
            if not (self.private_key or self.private_key):
                self.log.warning('public_key and private_key under [recaptcha] are '
                                 'not configured. Not showing the reCAPTCHA form!')
                return handler
            self.check_config()
            if req.method == 'POST' and req.args.get('action') == 'create':
                response = captcha.submit(
                    req.args.get('recaptcha_challenge_field'),
                    req.args.get('recaptcha_response_field'),
                    self.private_key, req.remote_addr,
                )
                if not response.is_valid:
                    add_warning(req, 'reCAPTCHA incorrect. Please try again.')
                    req.environ['REQUEST_METHOD'] = 'GET'
                    req.args.pop('password', None)
                    req.args.pop('password_confirm', None)

        # Admin Configuration
        if req.path_info.startswith('/admin/accounts/config') and \
            req.method == 'POST':
            self.config.set('recaptcha', 'lang', req.args.get('recaptcha_lang'))
            self.config.set('recaptcha', 'public_key',
                            req.args.get('recaptcha_public_key'))
            self.config.set('recaptcha', 'private_key',
                            req.args.get('recaptcha_private_key'))
            self.config.set('recaptcha', 'theme',
                            req.args.get('recaptcha_theme'))
            self.config.save()
        return handler
Ejemplo n.º 15
0
  def post(self):
    if self.get_logged_in_person():
      p = self.get_logged_in_person() 
      challenge = self.request.get('recaptcha_challenge_field')
      response  = self.request.get('recaptcha_response_field')
      remoteip  = environ['REMOTE_ADDR']

      cResponse = captcha.submit(
                     challenge,
                     response,
                     recaptcha_keys.recaptcha_private_key,
                     remoteip)

      if cResponse.is_valid:
          # response was valid
          p.ishuman = True
          p.put()
          self.render('confirm')
      else:
        error = cResponse.error_code

        chtml = captcha.displayhtml(
          public_key = recaptcha_keys.recaptcha_public_key,
          use_ssl = False,
          error = cResponse.error_code)

        template_values = {
          'captchahtml': chtml
        }
        self.render('home', template_values)

    else:
      self.redirect('/')
Ejemplo n.º 16
0
def comment(request, post_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            if not request.user.is_authenticated():
                r = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
                if not r.is_valid:
                    return redirect('/blog/'+post_id+'/') # Invalid form entry
            f = form.save(commit=False);
          
            f.post_id = post_id
            if request.user.is_authenticated():
                f.author_id = request.user.id
                f.author_name = ''
                f.author_email = ''
            f.save()
        
            email_msg  = 'You have a new comment at http://www.jessicasteiber.com/blog/'+post_id+'/#comments'
            email_from = '*****@*****.**'
            email_to   = ['*****@*****.**', '*****@*****.**']
        
            # Send email notification
            send_mail('New Blog Comment - JessicaSteiber.com', email_msg, email_from, email_to)
        
            return redirect('/blog/'+post_id+'/#comments') # Go back to blog with new comment
        else:
            return redirect('/blog/'+post_id+'/') # Invalid form entry
    else:
        return redirect('/blog/'+post_id+'/') # Go back to blog
Ejemplo n.º 17
0
def attempt_payout(bank):
    form = bottle.request.forms
    addr = form.get('addr')

    if captcha and bank.captcha_priv_key:
        response = captcha.submit(
            form.get('recaptcha_challenge_field'),
            form.get('recaptcha_response_field'),
            bank.captcha_priv_key,
            bottle.request['REMOTE_ADDR'],
        )
        if not response.is_valid:
            return http_err(403, "I think you're a robot!")

    try:
        amt = bank.schedule_payment(addr)
    except ValueError:
        return http_err(400, "Invalid address: "+addr)
    except DuplicateKeyError as e:
        t, v = e.args
        return http_err(400, t+" ("+v+") already queued")

    if amt == 0:
        return http_err(595, "Out of "+bank.coin)

    return bottle.template('payout', amount=amt, address=addr, **bank.get_public_status())
Ejemplo n.º 18
0
    def captcha_check(self, *args, **kwargs):

        if not "recaptcha_challenge_field" in kwargs:
            raise cherrypy.HTTPRedirect("/new_user?error=No captcha challenge field. That is totally weird. Please try reloading the page.")

        if not "recaptcha_response_field" in kwargs:
            raise cherrypy.HTTPRedirect("/new_user?error=No captcha response field. That is totally weird. Please try reloading the page.")


        recaptcha_challenge_field = kwargs["recaptcha_challenge_field"]
        recaptcha_response_field = kwargs["recaptcha_response_field"]

        captcha_results = captcha.submit(
                recaptcha_challenge_field,
                recaptcha_response_field,
                cherrypy.request.app.config["captcha"]["private"],
                cherrypy.request.headers["Remote-Addr"],)

        if captcha_results.is_valid:
            # TODO redirect to "your email should get a code" page
            return "valid"

        if captcha_results.error_code:
            # needs an error message
            if captcha_results.error_code == "invalid-site-private-key":
                # TODO log and alert operator
                pass
            raise cherrypy.HTTPRedirect("/new_user?error=%s"%
                    captcha_results.error_code)
Ejemplo n.º 19
0
 def post(self):
     c = Comentario()
     c.contenido = cgi.escape(self.request.get('contenido'), True)
     c.id_enlace = self.request.get('id_enlace')
     c.os = self.request.environ['HTTP_USER_AGENT']
     c.ips = [self.request.remote_addr]
     if users.get_current_user() and self.request.get('contenido') and self.request.get('id_enlace'):
         if self.request.get('anonimo') != 'on':
             c.autor = users.get_current_user()
         self.finalizar( c )
     elif self.request.get('contenido') and self.request.get('id_enlace'):
         challenge = self.request.get('recaptcha_challenge_field')
         response = self.request.get('recaptcha_response_field')
         remoteip = self.request.remote_addr
         cResponse = captcha.submit(
             challenge,
             response,
             RECAPTCHA_PRIVATE_KEY,
             remoteip)
         if cResponse.is_valid:
             self.finalizar( c )
         else:
             self.redirect('/error/403c')
     else:
         self.redirect('/error/403')
Ejemplo n.º 20
0
def suggest_resource(request, **kwargs):

    suggest = None
    output = {}
    template = ''
    captcha_is_valid = True
    captcha_error = ''
    
    suggest = SuggestResource()
   
    form = ExternalSuggestResourceForm(request.POST, instance=suggest)

    if settings.RECAPTCHA_PRIVATE_KEY:
        # Check the captcha with reCAPTCHA (google service)
        captcha_response = captcha.submit(  
            request.POST.get('recaptcha_challenge_field'),  
            request.POST.get('recaptcha_response_field'),  
            settings.RECAPTCHA_PRIVATE_KEY,  
            request.META['REMOTE_ADDR'],)  

        if not captcha_response.is_valid:
            # captcha is wrong show a error message in the template.
            captcha_is_valid = False
            captcha_error = captcha_response.error_code           

    if form.is_valid() and captcha_is_valid:
        template = 'suggest/thanks.html'
        suggest = form.save()
    else:
        template = 'suggest/invalid-link.html'
        output['form'] = form
        output['captcha_error'] = captcha_error
    
    return render_to_response(template, output, context_instance=RequestContext(request))
Ejemplo n.º 21
0
def contact(request):
    captcha_error = ""
    captcha_pub_key = settings.RECAPTCHA_PUBLIC_KEY
    if request.method == 'POST':
        form = ContactForm(request.POST)
        cp_response = captcha.submit(request.POST.get("recaptcha_challenge_field", None),
                                         request.POST.get("recaptcha_response_field", None),
                                         settings.RECAPTCHA_PRIVATE_KEY,
                                         request.META.get("REMOTE_ADDR", None))

        if not cp_response.is_valid:
            captcha_error = "&error=%s" % cp_response.error_code
        else:
            if form.is_valid():
              cd = form.cleaned_data
              send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', '*****@*****.**'),
                ['*****@*****.**'],
              )
              return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form,'captcha_error': captcha_error, 'captcha_pub_key': captcha_pub_key})
Ejemplo n.º 22
0
def contact(request):
    '''
    Display and process the contact form.
    
    Keyword arguments:
    request -- the request object.
    
    Return:
    The contact form view (if pre-request) or a view with a success
    message.
    '''
    
    CAPTCHA_PUBLIC_KEY = settings.AF_RECAPTCHA_PUBLIC_KEY
    
    if request.method == 'POST':
        
        form = contactForm(request.POST)        
        
        if form.is_valid():
	    
	    # Check if the response CAPTCHA value is valid; else redirect back
	    # with an error.
            response = captcha.submit(  
                        request.POST.get('recaptcha_challenge_field'),  
                        request.POST.get('recaptcha_response_field'),  
                        settings.AF_RECAPTCHA_PRIVATE_KEY,  
                        request.META['REMOTE_ADDR'],)         
            
            if not response.is_valid:
		
                captchaWrong = True
                return render_to_response('contact.html', locals(), 
                              context_instance=RequestContext(request))
            
            subject = request.POST['userSubject']
            
            message = "Hello, you've received a message from AfterGlow Cloud.\n"
            
            message += "User: "******"userName"] + " (" \
                + request.POST["userEmail"] + ") says: \n\n"
            
            message += request.POST["userMessage"]
            
            from_email = settings.AF_FROM_EMAIL
	    
            try:
                send_mail("AfterGlow: " + subject, message, 
                          from_email, settings.AF_TO_EMAILS)
            except BadHeaderError:
                return HttpResponse('Invalid header found. Please try again.')
            
            # Boolean flag used to display a 'success' message on the view.
            mailSent = True

    else:
	
        form = contactForm()
    
    return render_to_response('contact.html', locals(), 
                              context_instance=RequestContext(request))
Ejemplo n.º 23
0
 def clean(self):
     error_list = []
    
     # Test userName is unique
     if 'userName' in self.cleaned_data:
         QS = User.objects.filter(username__exact=self.cleaned_data['userName'])
         if QS.count(): error_list.append("username '%s' is already in use" % (self.cleaned_data['userName']))
     
     # Test emailAddress
     if 'email' in self.cleaned_data:
         validaton_errorList = validate_email(self.cleaned_data['email'])
         if validaton_errorList:
             error_list += validaton_errorList            
         
     # Test passwords
     if 'pass1' in self.cleaned_data and 'pass2' in self.cleaned_data:
         validaton_errorList = validate_passwords(self.cleaned_data['pass1'], self.cleaned_data['pass2'])
         if validaton_errorList:
             error_list += validaton_errorList        
 
     # test if captcha is valid
     captcha_response = captcha.submit(self.recaptcha_challenge_field,  
                                       self.recaptcha_response_field,  
                                       settings.RECAPTCHA_PRIVATE_KEY,  
                                       self.REMOTE_ADDR) 
     if not captcha_response.is_valid:  
         error_list.append("incorrect captcha")
     
     if error_list: raise ValidationError(error_list)
     return self.cleaned_data        
Ejemplo n.º 24
0
    def clean(self):
        default_error_messages = {
            'captcha_invalid': _(u'Incorrect, please try again.')
        }
        cleaned_data = super(RegistrationFormCaptcha, self).clean()
        remote_ip = cleaned_data.get('remote_ip')
        values = cleaned_data.get('captcha')

        recaptcha_challenge_value = smart_unicode(values[0])
        recaptcha_response_value = smart_unicode(values[1])
        
        try:
            use_ssl = settings.RECAPTCHA_USE_SSL
        except AttributeError:
            use_ssl = False
            
        check_captcha = captcha.submit(recaptcha_challenge_value, 
            recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, remote_ip)

        if not check_captcha.is_valid:
            msg = default_error_messages['captcha_invalid']
            self._errors['captcha'] = self.error_class([msg])
            del cleaned_data['captcha']
            
        return self.cleaned_data
Ejemplo n.º 25
0
    def processPublicRegistration(self):
        log = logging.getLogger('csdt')
        log.debug("register_view.processPublicRegistration()")

        log.debug("context = %s" % self.context)
        log.debug("request = %s" % self.request)
        session = self.request.session

        log.debug("request values:")
        for k, v in self.request.params.iteritems():
            log.debug("key = %s value = %s" % (k, v))

        log.debug("session values:")
        for k, v in session.iteritems():
            log.debug("key = %s value = %s" % (k, v))
        
        if "first_name" not in self.request.params or "last_name" not in self.request.params or "email" not in self.request.params:
            log.warning("request.params is missing a parameter that is essential")
            raise HTTPNotFound()

        self.nonUsersOnlyAuthorization(session)

        host = self.request.host
        recaptcha_private_key = '6Ldi2MYSAAAAALJ_KaLfTzOTAg5iNHqOmvmgaQOg'
        captcha_result = captcha.submit(
            self.request.params['recaptcha_challenge_field'],
            self.request.params['recaptcha_response_field'],
            recaptcha_private_key,
            host,
        )
        if not captcha_result.is_valid:
            error = captcha_result.error_code
            json_hash = {'result': '-1', 'error':error}
            json_dump = json.dumps(json_hash)
            log.debug("json dump = %s" % json_dump)

            return Response(json_dump)

        first_name = self.request.params['first_name']
        last_name = self.request.params['last_name']
        email = self.request.params['email']
   
        user_id = self.context.doesEmailExist(email)
        if user_id is not None:
            json_hash = {'result': '-2'}
            json_dump = json.dumps(json_hash)
            log.debug("json dump = %s" % json_dump)

            return Response(json_dump)

        plaintext = first_name + ";" + last_name + ";" + email
        ciphertext = self.context.encryptUrlQuery(unicode(plaintext))

        self.context.createConfirmationLetter(self.request.host_url, email, first_name, last_name, ciphertext)

        json_hash = {'result': '0'}
        json_dump = json.dumps(json_hash)
        log.debug("json dump = %s" % json_dump)

        return Response(json_dump)
Ejemplo n.º 26
0
def check_recaptcha(turing_value,ip):
    '''
    Check recaptcha

    @type turing_value: str
    @param turing_value: turing value in JSON format, should have turing_value["challenge"] and turing_value["response"]
    @type ip: str
    @param ip: IP of client

    @rtype: boolean
    @return: True iff recaptcha pass
    '''
    if force_output != None:
        return force_output
    if not isinstance(turing_value, str):
        return False
    if not isinstance(ip, str):
        return False
    v = json.loads(s=turing_value,encoding="utf8")
    if not isinstance(v, dict):
        return False
    if not isinstance(v["challenge"], unicode):
        return False
    if not isinstance(v["response"], unicode):
        return False
    output = captcha.submit(v["challenge"], v["response"], core_config.RECAPTCHA_PRIVATE_KEY, ip)
    if not output.is_valid:
        return False
    return True
Ejemplo n.º 27
0
 def validate(self, value):
     captchaResponse = captcha.submit(value['recaptcha_challenge_name'], 
                                      value['recaptcha_response_name'], 
                                      settings.RECAPTCHA_PRIVATE_KEY, 
                                      '')
     if not captchaResponse.is_valid:
         raise ValidationError(self.default_error_messages['invalid_answer'])
Ejemplo n.º 28
0
    def process_request(self, req):
        self.check_config()
        action = req.args.get('action')

        if req.method == 'POST' and action == 'create':
            response = captcha.submit(
                req.args['recaptcha_challenge_field'],
                req.args['recaptcha_response_field'],
                self.private_key,
                req.remote_addr,
                )
            if not response.is_valid:
                data = {}
                data['registration_error'] = 'Captcha incorrect. Please try again.'
                data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
                data['recaptcha_theme'] = self.theme
                return "recaptcharegister.html", data, None
            else:
                ret = super(RecaptchaRegistrationModule, self).process_request(req)
                h, data, n = ret
                data['recaptcha_theme'] = self.theme
                return "recaptcharegister.html", data, n
        else:
            ret = super(RecaptchaRegistrationModule, self).process_request(req)
            h, data, n = ret
            data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
            data['recaptcha_theme'] = self.theme
            return "recaptcharegister.html", data, n
Ejemplo n.º 29
0
def captcha_verify(request, post_pk, pk):
    """ Verify the captcha response. If it is invalid,
        inform the user. Otherwise allow the post to be listed. """
    post = Post.objects.get(pk=post_pk)
    comment = Comment.objects.get(pk=pk)

    response = captcha.submit(
        request.POST.get("recaptcha_challenge_field"),
        request.POST.get("recaptcha_response_field"),
        settings.GOOGLE_CAPTCHA_PRIVATE_API_KEY,
        request.META["REMOTE_ADDR"],
    )

    if response.is_valid:
        comment.listed = True
        comment.save()
        return HttpResponseRedirect(
            reverse("blog:index") + "%d/%.2d/%s/#comments" % (post.pub_date.year, post.pub_date.month, post.slug)
        )
    else:
        ctx = RequestContext(
            request,
            {
                "google_captcha_api_key": settings.GOOGLE_CAPTCHA_PUBLIC_API_KEY,
                "post": post,
                "comment": comment,
                "captcha_response": "Invalid Captcha.",
            },
        )
        return render_to_response("blog/captcha.html", ctx)
Ejemplo n.º 30
0
def register():

    #Handle registration
    if request.method == 'POST':

        username = request.form.get('username', None)
        password = request.form.get('password', None)
        challenge = request.form.get('recaptcha_challenge_field', '')
        response = request.form.get('recaptcha_response_field', '')

        #Google Recaptcha
        response = captcha.submit(
            challenge,
            response,
            '6LdcwckSAAAAAGFCGW1Q4F0A7gkp43AzyTsHVkJh',
            request.remote_addr,
            )

        #Check for username and passwords
        if username and password and response.is_valid:

            #Actually do the db mucking
            ok = make_user(username, password)
            if not ok:
                return render_template("register.html")
            else:
                return redirect("/login/")

    return render_template("register.html", logged_in = not current_user.is_anonymous())
Ejemplo n.º 31
0
 def validate_captcha(self):
     rcf = self.cleaned_data['recaptcha_challenge_field']
     rrf = self.cleaned_data['recaptcha_response_field']
     check = captcha.submit(
         rcf, rrf, settings.RECAPTCHA_PRIVATE_KEY, self.ip)
     if not check.is_valid:
         raise forms.ValidationError(_(
             astakos_messages.CAPTCHA_VALIDATION_ERR))
Ejemplo n.º 32
0
 def get_captcha_response(self):
     """Returns an object containing the CAPTCHA response information for the
     given request's CAPTCHA field information."""
     challenge = self.request.get('recaptcha_challenge_field')
     response = self.request.get('recaptcha_response_field')
     remote_ip = os.environ['REMOTE_ADDR']
     return captcha.submit(challenge, response,
                           config.get('captcha_private_key'), remote_ip)
def save_child(request, parent=None, parentString=''):
    request.session['errors'] = ''
    if settings.USE_RECAPTCHA:
        response = captcha.submit(
            request.POST.get('recaptcha_challenge_field'),
            request.POST.get('recaptcha_response_field'),
            settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if not response.is_valid:
            request.session['errors'] = 'captcha'
            return redirect(settings.URL_ROOT + parentString)

    email = request.POST.get('email', '')
    request.session['email'] = email
    if not is_valid_email(email):
        request.session['errors'] = 'email'
        return redirect(settings.URL_ROOT +
                        parentString)  #invalid email, send back to start
    hash = hash_email(email)
    ip = request.META.get('REMOTE_ADDR')
    slider = 50
    newp = Person.objects.filter(email=email)
    dup = (len(newp) > 0)
    if dup:
        newp = newp[0]
        rating = Rating.objects.filter(person=newp)
        if len(rating) > 0:
            slider = rating[0].rating
    else:
        if parent == None or len(parent) == 0:
            newp = Person(email=email,
                          hash=hash,
                          ipaddress=ip,
                          influence=0,
                          parent_node=None,
                          session_key=str(request.session.session_key))
            newp.save()
        else:
            newp = Person(email=email,
                          hash=hash,
                          ipaddress=ip,
                          parent=parent[0].email,
                          parent_node=parent[0],
                          influence=0,
                          session_key=str(request.session.session_key))
            newp.save()
            update_score(newp)
    t = loader.get_template('save.html')
    c = RequestContext(
        request, {
            'link': settings.URL_ROOT + str(newp.id),
            'score_link': settings.URL_ROOT + 'score/' + str(newp.id),
            'csrf_token': csrf(request)['csrf_token'],
            'url': settings.URL_ROOT,
            'saved': '',
            'slider': slider,
            'dup': dup
        })
    return HttpResponse(t.render(c))
Ejemplo n.º 34
0
 def clean_captcha(self):
     value = None
     if self.request:
         challenge = self.data['recaptcha_challenge_field']
         response = self.data['recaptcha_response_field']
         captcha_response = captcha.submit(challenge,  response,  settings.RECAPTCHA_PRIVATE_KEY,  request_helpers.get_ip(self.request))
     if not captcha_response.is_valid:
         raise forms.ValidationError("Incorrect response entered.")
     return value
Ejemplo n.º 35
0
 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]
Ejemplo n.º 36
0
def checkCaptcha(request):
    check = captcha.submit( request.POST['recaptcha_challenge_field'],
                            request.POST['recaptcha_response_field'],
                            privateKey,
                            '192.168.1.1')
    if check.is_valid:
        return render(request, 'success.html')
    else:
        return render(request, 'failure.html') 
    def post(self):
        args = self.parser.parse_args()
        response = captcha.submit(args['recaptcha_challenge_field'],
                                  args['recaptcha_response_field'],
                                  '6LdaFvsSAAAAAPhdPEuKa5KBOYNGNPNCkhxIo8mG',
                                  request.headers.get('REMOTE_ADDR'))
        if response.is_valid:
            return Response("NICE")

        return abort(self.HTTP_FORBIDDEN)
Ejemplo n.º 38
0
 def submit(self):
     """Return an instance of recaptcha.client.captcha.RecaptchaResponse."""
     if request.environ.get('paste.testing', False):
         return RecaptchaResponse(False, 'paste.testing')
     recaptcha_challenge_field = request.POST.get(
         'recaptcha_challenge_field', None)
     recaptcha_response_field = request.POST.get('recaptcha_response_field',
                                                 None)
     return submit(recaptcha_challenge_field, recaptcha_response_field,
                   self._private_key, "127.0.0.1")
Ejemplo n.º 39
0
 def clean(self, data, initial):
     if initial is None or initial == '':
         raise Exception("ReCaptchaField requires the client's IP be set to the initial value")
     ip = initial
     resp = captcha.submit(data.get("recaptcha_challenge_field", None),
                           data.get("recaptcha_response_field", None),
                           settings.RECAPTCHA_SECRET, ip)
     if not resp.is_valid:
         raise forms.ValidationError(self.default_error_messages.get(
                 resp.error_code, "Unknown error: %s" % (resp.error_code)))    
Ejemplo n.º 40
0
def validate_captcha(request, form):
    """
    Validates the captcha challenge found on the contact form
    """
    response = captcha.submit(request.POST.get('recaptcha_challenge_field'),
                              request.POST.get('recaptcha_response_field'),
                              settings.RECAPTCHA_PRIVATE_KEY,
                              request.META.get('REMOTE_ADDR', None))

    return response.is_valid
Ejemplo n.º 41
0
 def clean(self, value):
     if value is None:
         raise ValidationError(_('Invalid request'))
     resp = captcha.submit(value.get('challenge', None),
                           value.get('response', None),
                           askbot_settings.RECAPTCHA_SECRET,
                           value.get('ip', None))
     if not resp.is_valid:
         self.widget.attrs['error'] = resp.error_code
         raise ValidationError(
             HUMAN_ERRORS.get(resp.error_code, _(u'Unknown error.')))
 def change_password(self, *args, **kwargs):
     ''' Updates a user accounts password '''
     user = User.by_user_name(self.session.data['user_name'])
     try:
         old_password = self.get_argument("old_password")
         new_password = self.get_argument("new_password")
         new_password_two = self.get_argument("new_password2")
     except:
         self.render("user/error.html", 
             operation="Changing Password",
             errors="Please fill out all forms"
         )
     try:
         response = captcha.submit(
             self.get_argument('recaptcha_challenge_field'),
             self.get_argument('recaptcha_response_field'),
             self.application.settings['recaptcha_private_key'],
             self.request.remote_ip
         )
     except:
         self.render("user/error.html", 
             operation="Changing Password",
             errors="Please fill out recaptcha"
         )
     if user.validate_password(old_password):
         if new_password == new_password_two:
             if 12 <= len(new_password):
                 if response.is_valid:
                     user.password = new_password
                     self.dbsession.add(user)
                     self.dbsession.flush()
                     self.render("user/settings.html",
                         message="Succesfully Changed Password!"
                     )
                 else:
                     self.render("user/error.html", 
                         operation="Changing Password",
                         errors="Invalid recaptcha"
                     )
             else:
                 self.render("user/error.html", 
                     operation="Change Password",
                     errors="Password must be at least 12 chars"
                 )
         else:
             self.render("user/error.html", 
                 operation="Changing Password",
                 errors="New password's didn't match"
             )
     else:
         self.render("user/error.html", 
             operation="Changing Password",
             errors="Invalid old password"
         )
Ejemplo n.º 43
0
 def clean(self, values):
     super(ReCaptchaField, self).clean(values[1])
     challenge = smart_unicode(values[0])
     response = smart_unicode(values[1])
     ip = smart_unicode(values[2])
     key = settings.RECAPTCHA_PRIVATE_KEY
     res = captcha.submit(challenge, response, key, ip)
     if not res.is_valid:
         raise forms.util.ValidationError(
             self.error_messages['captcha_invalid'])
     return challenge
Ejemplo n.º 44
0
def index(req):
    ipaddr = req.META.get('REMOTE_ADDR', '')
    _content = ''
    _need_recaptcha = False
    if req.method == 'POST':
        _content = req.POST.get('content', '')
        _need_recaptcha = needRecaptchar(ipaddr, _content)
        if _need_recaptcha and len(
                req.POST.get('recaptcha_challenge_field', '')) == 0:
            messages.error(req, MSG['RECAPTCHA_NEEDED'])
        elif _need_recaptcha and not captcha.submit(
                req.POST.get('recaptcha_challenge_field', ''),
                req.POST.get('recaptcha_response_field'),
                RECAPTCHA_PRIVATE_KEY, ipaddr).is_valid:
            messages.error(req, MSG['RECAPTCHA_INCORRECT'])
        elif not checkIP(ipaddr):
            messages.error(req, MSG['IP_NOT_VALID'])
        elif not (len(_content) < 120 and len(_content) > 5):
            messages.error(req, MSG['CONTENT_TOO_LONG'])
        elif ContentModel.objects.filter(ip=ipaddr, time__range=\
                (datetime.now()-timedelta(minutes=30), datetime.now())).count() > 0:
            messages.error(req, MSG['TOO_MANY_TIMES'])
        else:
            try:
                postStatu(_content, ipaddr)
            except:
                messages.error(req, MSG['PUBLISH_ERROR'])
                logging.error('Error in ' + str(ContentModel.objects.count()))
            else:
                messages.success(req, MSG['PUBLISH_OK'])
                _content = ''

# for doreamon icon
    try:
        icon = int(req.path[1:])
    except ValueError:
        icon = 0
    tourl = ''
    if icon == 0 or req.session.get('redirect', 0) == 0:
        req.session['redirect'] = 1
        tourl = '/' + str(random.randint(1, 16))
    else:
        req.session['redirect'] = 0
    isIphone = ('iPhone' in req.META.get('HTTP_USER_AGENT', '')
                and req.method == 'GET')
    return render_to_response('index.html', \
            {'ICO_NUM': icon, 'TOURL': tourl, 'ISIPHONE': isIphone,
                'LINKS': LINKS,
                'PLACEHOLER': PlaceholderModel.objects.order_by('?')[0].content,
                'content': _content,
                'RECAPTCHA_PUBLIC_KEY': RECAPTCHA_PUBLIC_KEY,
                'need_recaptcha': _need_recaptcha,
                'COLOR': random.choice(COLORS)},
            context_instance=RequestContext(req))
Ejemplo n.º 45
0
    def get_captcha_response(self):
        """Returns an object containing the CAPTCHA response information for the
        given request's CAPTCHA field information."""
        # Allows faking the CAPTCHA response by an HTTP request parameter, but
        # only locally, for testing purpose.
        faked_captcha_response = self.request.get('faked_captcha_response')
        if faked_captcha_response and self.request.remote_addr == '127.0.0.1':
            return captcha.RecaptchaResponse(
                is_valid=faked_captcha_response == 'success')

        captcha_response = self.request.get('g-recaptcha-response')
        return captcha.submit(captcha_response)
Ejemplo n.º 46
0
 def clean(self, values):
     super(FormCaptchaField, self).clean(values[1])
     if not settings.SHOW_CAPTCHAS:
         return values
     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(_(u'Invalid captcha'))
     return values[0]
Ejemplo n.º 47
0
    def password_reset(self):
        settings = SettingsModel().get_all_settings()
        captcha_private_key = settings.get('rhodecode_captcha_private_key')
        captcha_active = bool(captcha_private_key)
        captcha_public_key = settings.get('rhodecode_captcha_public_key')

        render_ctx = {
            'captcha_active': captcha_active,
            'captcha_public_key': captcha_public_key,
            'defaults': {},
            'errors': {},
        }

        if self.request.POST:
            password_reset_form = PasswordResetForm()()
            try:
                form_result = password_reset_form.to_python(
                    self.request.params)
                if captcha_active:
                    response = submit(
                        self.request.params.get('recaptcha_challenge_field'),
                        self.request.params.get('recaptcha_response_field'),
                        private_key=captcha_private_key,
                        remoteip=get_ip_addr(self.request.environ))
                    if captcha_active and not response.is_valid:
                        _value = form_result
                        _msg = _('bad captcha')
                        error_dict = {'recaptcha_field': _msg}
                        raise formencode.Invalid(_msg, _value, None,
                                                 error_dict=error_dict)

                # Generate reset URL and send mail.
                user_email = form_result['email']
                user = User.get_by_email(user_email)
                password_reset_url = self.request.route_url(
                    'reset_password_confirmation',
                    _query={'key': user.api_key})
                UserModel().reset_password_link(
                    form_result, password_reset_url)

                # Display success message and redirect.
                self.session.flash(
                    _('Your password reset link was sent'),
                    queue='success')
                return HTTPFound(self.request.route_path('login'))

            except formencode.Invalid as errors:
                render_ctx.update({
                    'defaults': errors.value,
                    'errors': errors.error_dict,
                })

        return render_ctx
Ejemplo n.º 48
0
 def clean(self, value):
     plugin = get_plugin('contactform')
     privkey = plugin.get_config().get('rprivk', None)
     if privkey:
         privkey = privkey.value
     else:
         privkey = ''
     challenge, response = value
     recaptcha_response = captcha.submit(challenge, response, privkey,
                                         self.client_addr)
     if not recaptcha_response.is_valid:
         raise ValidationError(_("The captcha was invalid, try again."))
Ejemplo n.º 49
0
def nouveau(request):
    if request.method == "POST":
        response = captcha.submit(
            request.POST.get('recaptcha_challenge_field'),
            request.POST.get('recaptcha_response_field'),
            '6LfDrPESAAAAABINT7Y69VTIviZLqijba7V3tgeK',
            request.META['REMOTE_ADDR'],
        )
        if not response.is_valid:
            return render_to_response('profil/inscription.html',
                                      {'msg_error': response.error_code},
                                      RequestContext(request))
            return redirect('/profil/')
        pseudo = request.POST['pseudo']
        if pseudo == '':
            msg = "Le pseudo est vide"
            return render_to_response('profil/inscription.html',
                                      {'msg_error': msg},
                                      RequestContext(request))
        elif request.POST['pwd1'] == "":
            msg = "Le mot de passe est vide"
            return render_to_response('profil/inscription.html',
                                      {'msg_error': msg},
                                      RequestContext(request))
        elif User.objects.filter(username=pseudo) or Profil.objects.filter(
                pseudo=pseudo):
            msg = "Ce pseudo est déjà utilisé"
            return render_to_response('profil/inscription.html',
                                      {'msg_error': msg},
                                      RequestContext(request))
        elif request.POST['pwd1'] != request.POST['pwd2']:
            msg = "Mots de passe non identiques"
            return render_to_response('profil/inscription.html',
                                      {'msg_error': msg},
                                      RequestContext(request))
        elif " " in request.POST['pseudo']:
            msg = "Pas d'espace dans un pseudo"
            return render_to_response('profil/inscription.html',
                                      {'msg_error': msg},
                                      RequestContext(request))
        else:
            new_user = User.objects.create(username=pseudo, is_active=True)
            new_user.set_password(request.POST['pwd1'])
            new_user.save()
            new_profil = Profil.objects.create(pseudo=pseudo, u=new_user)
            new_profil.save()
            u = authenticate(username=new_user.username,
                             password=request.POST['pwd1'])
            login(request, u)
            return redirect('/')
    else:
        return redirect('/profil/')
Ejemplo n.º 50
0
 def recaptcha(self):    
     """ """
     try:
         challenge = request.form['recaptcha_challenge_field']
         response  = request.form['recaptcha_response_field']
         cResponse = captcha.submit(
                      challenge,
                      response,
                      "6Ldph8cSAAAAAFZt4S2na02xnflgTC3jDNBX91_C",
                      request.remote_addr)
         return cResponse.is_valid
     except:
         return True
Ejemplo n.º 51
0
    def validate_captcha(self):
        rcf = self.cleaned_data['recaptcha_challenge_field']
        rrf = self.cleaned_data['recaptcha_response_field']
        ip_address = self._request.META['REMOTE_ADDR']

        # only submit captcha information if it is enabled
        if self.captcha_enabled:
            check = captcha.submit(rcf, rrf, settings.RECAPTCHA_PRIVATE_KEY,
                                   ip_address)

            if not check.is_valid:
                raise forms.ValidationError(
                    'You have not entered the correct words')
Ejemplo n.º 52
0
 def clean(self):
     super(InviteUserForm, self).clean()
     if CAPTCHA:  # reCAPTCHA works on production
         recaptcha_response_value = self.cleaned_data[
             'recaptcha_response_field']
         recaptcha_challenge_value = self.cleaned_data[
             'recaptcha_challenge_field']
         check_captcha = captcha.submit(recaptcha_challenge_value,
                                        recaptcha_response_value,
                                        RECAPTCHA_PRIVATE_KEY, {})
         if not check_captcha.is_valid:
             self.add_error('recaptcha_response_field', 'Try captcha again')
     return self.cleaned_data
Ejemplo n.º 53
0
    def is_captcha_valid(self,
                         cr,
                         uid,
                         ids,
                         challenge,
                         response,
                         context=None):
        assert len(ids) == 1

        website = self.browse(cr, uid, ids[0])
        res = captcha.submit(challenge, response,
                             website.recaptcha_private_key, website.name)
        return res.is_valid
Ejemplo n.º 54
0
    def _clean_captcha(self):
        if self.need_captcha and \
                getattr(settings, 'RECAPTCHA_PRIVATE_KEY', None) and \
                getattr(settings, 'RECAPTCHA_PUBLIC_KEY', None):
            challenge_field = self.data.get('recaptcha_challenge_field')
            response_field = self.data.get('recaptcha_response_field')
            client = self.recaptcha_ip  # Must be set by our view code.
            check_captcha = captcha.submit(challenge_field, response_field,
                                           settings.RECAPTCHA_PRIVATE_KEY,
                                           client)

            if check_captcha.is_valid is False:
                self.errors['recaptcha'] = 'Invalid captcha value'
Ejemplo n.º 55
0
    def register_post(self):
        captcha_private_key = SettingsModel().get_setting_by_name(
            'rhodecode_captcha_private_key')
        captcha_active = bool(captcha_private_key)
        auto_active = 'hg.register.auto_activate' in User.get_default_user()\
            .AuthUser.permissions['global']

        register_form = RegisterForm()()
        try:
            form_result = register_form.to_python(self.request.params)
            form_result['active'] = auto_active

            if captcha_active:
                response = submit(
                    self.request.params.get('recaptcha_challenge_field'),
                    self.request.params.get('recaptcha_response_field'),
                    private_key=captcha_private_key,
                    remoteip=get_ip_addr(self.request.environ))
                if captcha_active and not response.is_valid:
                    _value = form_result
                    _msg = _('bad captcha')
                    error_dict = {'recaptcha_field': _msg}
                    raise formencode.Invalid(_msg, _value, None,
                                             error_dict=error_dict)

            new_user = UserModel().create_registration(form_result)
            event = UserRegistered(user=new_user, session=self.session)
            self.request.registry.notify(event)
            self.session.flash(
                _('You have successfully registered with RhodeCode'),
                queue='success')
            Session().commit()

            redirect_ro = self.request.route_path('login')
            raise HTTPFound(redirect_ro)

        except formencode.Invalid as errors:
            del errors.value['password']
            del errors.value['password_confirmation']
            return self.register(
                defaults=errors.value, errors=errors.error_dict)

        except UserCreationError as e:
            # container auth or other auth functions that create users on
            # the fly can throw this exception signaling that there's issue
            # with user creation, explanation should be provided in
            # Exception itself
            self.session.flash(e, queue='error')
            return self.register()
Ejemplo n.º 56
0
def validate_layout_submit(request):
    if request.method != 'POST':
        return redirect(layout_submit)

    if settings.RECAPTCHA_ENABLED:
        check_captcha = captcha.submit(
            request.POST['recaptcha_challenge_field'],
            request.POST['recaptcha_response_field'],
            settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if not check_captcha.is_valid:
            return layout_submit(request)

    form = StationLayoutQuarantineForm(request.POST)

    if not form.is_valid():
        return layout_submit(request)

    new_layout = StationLayoutQuarantine(
        name=form.cleaned_data['name'],
        email=form.cleaned_data['email'],
        station=form.cleaned_data['station'],
        active_date=form.cleaned_data['active_date'],
        detector_1_alpha=form.cleaned_data['detector_1_alpha'],
        detector_1_beta=form.cleaned_data['detector_1_beta'],
        detector_1_radius=form.cleaned_data['detector_1_radius'],
        detector_1_height=form.cleaned_data['detector_1_height'],
        detector_2_alpha=form.cleaned_data['detector_2_alpha'],
        detector_2_beta=form.cleaned_data['detector_2_beta'],
        detector_2_radius=form.cleaned_data['detector_2_radius'],
        detector_2_height=form.cleaned_data['detector_2_height'],
        detector_3_alpha=form.cleaned_data['detector_3_alpha'],
        detector_3_beta=form.cleaned_data['detector_3_beta'],
        detector_3_radius=form.cleaned_data['detector_3_radius'],
        detector_3_height=form.cleaned_data['detector_3_height'],
        detector_4_alpha=form.cleaned_data['detector_4_alpha'],
        detector_4_beta=form.cleaned_data['detector_4_beta'],
        detector_4_radius=form.cleaned_data['detector_4_radius'],
        detector_4_height=form.cleaned_data['detector_4_height'])

    new_layout.generate_hashes()
    new_layout.save()
    new_layout.sendmail_submit()

    return render(
        request, 'layout_submitted.html', {
            'name': form.cleaned_data['name'],
            'email': form.cleaned_data['email'],
            'station': form.cleaned_data['station']
        })
Ejemplo n.º 57
0
def DoRecaptchaValidation(request, template, template_dict):
    if settings.SCALEREG_SIMPLECFP_USE_RECAPTCHA:
        try:
            recaptcha_response = submit(
                request.POST['recaptcha_challenge_field'],
                request.POST['recaptcha_response_field'],
                settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        except:
            # If we cannot get a recaptcha, let the user continue.
            return None
        if not recaptcha_response.is_valid:
            template_dict['recaptcha_html'] = GenerateRecaptchaHTML(
                request, recaptcha_response.error_code)
            return cfp_render_to_response(request, template, template_dict)
    return None
Ejemplo n.º 58
0
    def validate_captcha(self):
        rcf = self.cleaned_data['recaptcha_challenge_field']
        rrf = self.cleaned_data['recaptcha_response_field']
        ip_address = self._request.META['REMOTE_ADDR']

        # only submit captcha information if it is enabled
        if self.captcha_enabled:
            try:
                check = captcha.submit(rcf, rrf, settings.RECAPTCHA_PRIVATE_KEY, ip_address)
                if not check.is_valid:
                    raise forms.ValidationError('You have not entered the correct words')
            except URLError, timeout:
                # We often sometimes see error messages that recaptcha url is unreachable and
                # this causes 500 errors. If recaptcha is unreachable, just skip captcha validation.
                pass
Ejemplo n.º 59
0
 def _validate_captcha(self):
     rcf = self.cleaned_data['recaptcha_challenge_field']
     rrf = self.cleaned_data['recaptcha_response_field']
     if rrf == '':
         raise forms.ValidationError(
             _('You did not enter any of the two words shown in the image.')
         )
     else:
         from recaptcha.client import captcha as recaptcha
         ip = self._request.META['REMOTE_ADDR']
         private_key = getattr(settings, "RECAPTCHA_PRIVATE_KEY")
         check = recaptcha.submit(rcf, rrf, private_key, ip)
         if not check.is_valid:
             raise forms.ValidationError(
                 _('The words you entered did not match the image.'))
Ejemplo n.º 60
0
 def _validate_captcha(self):
     if not self.recaptcha_always_validate:
         rcf = self.cleaned_data['recaptcha_challenge_field']
         rrf = self.cleaned_data['recaptcha_response_field']
         if rrf == '':
             raise forms.ValidationError(
                 _('You did not enter the two words shown in the image.'))
         else:
             from recaptcha.client import captcha as recaptcha
             ip = self._request.META['REMOTE_ADDR']
             check = recaptcha.submit(rcf, rrf, self._recaptcha_private_key,
                                      ip)
             if not check.is_valid:
                 raise forms.ValidationError(
                     _('The words you entered did not match the image.'))