Пример #1
0
def register(request):
  if request.method == "POST":
    form = UserRegistrationForm(request.POST)
    if form.is_valid():
      username = form.cleaned_data['username']
      password = form.cleaned_data['password']
      first_name = form.cleaned_data['first_name']
      last_name = form.cleaned_data['last_name']
      email = form.cleaned_data['email']
      user = User.objects.create_user(username, email, password)
      user.first_name = first_name
      user.last_name = last_name
      user.is_active = False
      user.save()

      salt = sha.new(str(random.random())).hexdigest()[:5]
      activation_key = sha.new(salt + user.username).hexdigest()
      user_profile = UserProfile(user=user, activation_key=activation_key)
      user_profile.save()
      base_url = request.get_host()
      account_activation_link = "%s/user_id=%s&auth_key=%s" % (base_url, username, activation_key)
      subject = "Welcome to WebSaver! Please activate your account."
      template_var = { "username": username,
                       "account_activation_link": account_activation_link }
      send_template_email(subject, "*****@*****.**", [email], "websaver/template/emails/registration_activation_email.html", template_var)
      return HttpResponseRedirect('/')
  else:
    form = UserRegistrationForm(auto_id="%s_id")

  c = RequestContext(request, {
      'form': form,
  })
  c.update(csrf(request))
  t = loader.get_template('websaver/template/base.html')
  return HttpResponse(t.render(c))
Пример #2
0
def register(request):
    code = ""
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        email = request.POST['email']
        form = RegistrationForm(request.POST)
        if form.is_valid():
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_code = sha.new(salt+username).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(7)
            user = User.objects.create_user(username=username, email=email, password=password)
            user.is_active = False
            user.save()
            profile = form.save(commit=False)
            profile.user = user
            profile.activation_code = activation_code
            profile.key_expires = key_expires
            profile.save()
            return render_to_response('accounts/register.html', 
                {'code':activation_code, 'profile':profile}, context_instance=RequestContext(request))
        else:
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_code = sha.new(salt+username).hexdigest()
            return render_to_response('accounts/register.html',
                {'form':form, 'code':activation_code}, context_instance=RequestContext(request))
    else:
        form = RegistrationForm()
        return render_to_response('accounts/register.html',{'form':form, 'code':code})
Пример #3
0
	def _get_sha1_auth(self):
		''' get sha of sid + Initiator jid + Target jid '''
		if 'is_a_proxy' in self.file_props:
			del(self.file_props['is_a_proxy'])
			return sha.new('%s%s%s' % (self.sid, self.file_props['proxy_sender'], 
				self.file_props['proxy_receiver'])).hexdigest()
		return sha.new('%s%s%s' % (self.sid, self.initiator, self.target)).hexdigest()
Пример #4
0
 def create_action(
     self,
     user,
     instance,
     cluster,
     action,
     action_value=None,
     operating_system=None
 ):
     # create a new action and expireany older actions
     for action in self.filter(
         applicant=user,
         instance=instance,
         cluster=cluster,
         action=action
     ).exclude(activation_key='ALREADY_ACTIVATED'):
         action.expire_now()
     salt = sha.new(str(random.random())).hexdigest()[:5]
     activation_key = sha.new(salt + user.username).hexdigest()
     return self.create(
         applicant=user,
         instance=instance,
         cluster=cluster,
         action=action,
         action_value=action_value,
         activation_key=activation_key,
         operating_system=operating_system
     )
Пример #5
0
def register_application_req(request):

    form = AppRegistrationForm(request.POST)
    
    if not form.is_valid():
      return render_to_response('applications/register.html',
				default_context(request, form=form))

    ip = request.META['REMOTE_ADDR']
    code = request.POST['code']
    name = request.POST['name']
    email = request.POST['email']
    url = request.POST['website_url']

    if 'save' in request.POST and request.POST['save'] == 'Save':
      id = request.POST['id']
      print "Updating ea " + id
      ea = ExternalApplication.objects.get(ea_id=id)
      ea.ea_name = name
      ea.ea_code = code
      ea.ea_contact_email = email
      ea.ea_web_site_url = url
    else:
      # Compute a random key
      key = sha.new(str(random.randint(0,1000000))+ip+code+name).hexdigest()
      secret = sha.new(str(random.randint(0,1000000))+code+ip+name).hexdigest()
      ea = ExternalApplication(ea_name=name,ea_code=code,ea_key=key,ea_ip_address=ip,ea_active_status='Pending',ea_secret=secret, ea_contact_email=email, ea_web_site_url=url)

      # add authentication token for this application
      at = AuthenticationToken(at_account_id=None,at_token=key,at_secret=secret)
      at.save()

    ea.save()
    return HttpResponseRedirect('.')
Пример #6
0
def forgot_password(request):
    reset_password_form = forms.ResetPasswordForm()
    username_form = forms.UsernameForm()
    if request.method == 'GET' and 'password_key' in request.GET:
        try:
            profile = UserProfile.objects.get(activation_key = request.GET['password_key'])
            profile.save()
            user = profile.user
            reset_password_form = forms.ResetPasswordForm(initial = {'user' : user.id, })
            return render_to_response('users/reset_password_form.html', locals(), context_instance = global_context(request))
        except UserProfile.DoesNotExist:
            raise Http404
    elif request.method == 'POST':
        username_form = forms.UsernameForm(request.POST)
        if username_form.is_valid():
            username = username_form.cleaned_data['username']
            user = User.objects.get(username = username)
            profile = user.get_profile()
            salt = sha.new(str(random.random())).hexdigest()[:5]
            profile.activation_key = sha.new(salt+user.username).hexdigest()
            profile.save()
            
            mail_template = get_template('email/forgot_password.html')
            body = mail_template.render(Context( {
                'username' : user.username,
                'SITE_URL' : settings.SITE_URL,
                'passwordkey' : profile.activation_key 
            } ))
            send_mail('[Shaastra 2011] Password reset request', body,'*****@*****.**', [user.email,], fail_silently = False)
            return HttpResponseRedirect('%smyshaastra/forgot_password/done/' % settings.SITE_URL)
    return render_to_response('users/username_form.html', locals(), context_instance = global_context(request))
Пример #7
0
 def create_inactive_user(self, username, password, email, send_email=True):
     """
     Creates a new User and a new RegistrationProfile for that
     User, generates an activation key, and mails it.
     
     Pass ``send_email=False`` to disable sending the email.
     
     """
     # Create the user.
     new_user = User.objects.create_user(username, email, password)
     new_user.is_active = False
     new_user.save()
     
     # Generate a salted SHA1 hash to use as a key.
     salt = sha.new(str(random.random())).hexdigest()[:5]
     activation_key = sha.new(salt+new_user.username).hexdigest()
     
     # And finally create the profile.
     new_profile = self.create(user=new_user,
                               activation_key=activation_key)
     
     if send_email:
         from django.core.mail import send_mail
         current_domain = Site.objects.get_current().domain
         subject = "Activate your new account at %s" % current_domain
         message_template = loader.get_template('registration/activation_email.txt')
         message_context = Context({ 'site_url': 'http://%s/' % current_domain,
                                     'activation_key': activation_key,
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
         message = message_template.render(message_context)
         send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
     return new_user
Пример #8
0
def microidify(mail, nick):
    "Creates a microid hash"
    hash = sha.new(
        sha.new("mailto:" + mail).hexdigest()
        + sha.new("http://ircious.flukkost.nu/user/%s/" % nick.nickname).hexdigest()
    ).hexdigest()
    return "mailto+http:sha1:" + hash
Пример #9
0
    def create_inactive_user(self, username, password, email, send_email=True):

        # Create the user.
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()
        
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation_key = sha.new(salt+new_user.username).hexdigest()
        
        # And finally create the profile.
        new_profile = self.create(user=new_user,
                                  activation_key=activation_key)
        
        if send_email:
            from django.core.mail import send_mail
            subject = "Activate your new account at %s" % settings.SITE_URL
            message_template = loader.get_template('activation_email.txt')
            message_context = Context({ 'site_url': 'http://%s' % settings.SITE_URL,
                                        'activation_key': activation_key,
                                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
            message = message_template.render(message_context)
            print settings.DEFAULT_FROM_EMAIL
            send_mail(subject, message, settings.EMAIL_HOST, [new_user.email])
        return new_user
Пример #10
0
def cadastrarUsuario(request):
	dados = request.POST
	senha = dados['senha']
	senhaConfirmacao = dados['senhaconfirmacao']
	if senha == senhaConfirmacao: #Verifica se os campos senha e confirmação de senha estão preenchidos iguais
		login = dados['login']
		usuario = User.objects.get(username = login)
		print 'oi'
		if usuario is None: #caso o usuário não exista
			#Criando novo usuário inativo
			newUser = User.objects.create_user(login, login + '@cin.ufpe.br', senha)
			newUser.is_active = false
			newUser.save()
			
			#Construindo a chave de ativação para a conta
			salt = sha.new(str(random.random())).hexdigest()[:5]
			chaveAtivacao = sha.new(salt+new_user.username).hexdigest()
			dataExpiracao = datetime.datetime.today() + datetime.timedelta(2)
			
			c = RequestContext (request, {})
		elif usuario.is_active: #caso já exista um usuário com esse login e sua conta esteja ativa
			c = 'Já existe um usuário com esse login'
		else: #caso já exista um usuário com esse login mas sua conta não esteja ativa
			print 'opa' #mandar e-mail
	else:
		c = 'Você escreveu duas senhas diferentes'
	return HttpResponse(c)
Пример #11
0
 def validateUserAndPassword(self, username, password):
     """
     Looks first if the user is configured in the configuration file,
     e.g. standard users like the "manager" account. If not the user
     databases, like "Member", are checked. The encrypted password is
     validated.
 """
     if (username, sha.new(password).hexdigest()) not in users:
         if len(username) >= 2:
             # which database to use for user authentification
             if username[:2].lower() == "mi":
                 user = Member.search(username[2:])
             else:
                 self.warning("wrong prefix for username '%s'" % username)
                 raise LoginError, "WrongUsername"
             # check user exist and unique
             if user.count() == 0:
                 self.warning("user '%s' not found" % username)
                 raise LoginError, "WrongUsername"
             elif user.count() > 1:
                 self.warning("User '%s' not unique" % username)
                 raise LoginError, "WrongUsername"
             else:
                 # check password
                 if user[0].passwordHash == sha.new(password).hexdigest():
                     # correct user from Member database
                     self.info("User '%s' authorized" % username)
                 else:
                     self.warning("Wrong password for user '%s' in Member database" % username)
                     raise LoginError, "WrongPassword"
         else:
             self.warning("Username '%s' to short" % username)
             raise LoginError, "WrongUsername"
Пример #12
0
def signIn():
	print "Please input ID and Password"
	id_plain = raw_input("User ID : ")
	acc = open("access", "r")
	user_id = []
	user_pw = []
	for line in acc:
		user_id.append(line.split(":")[0])
		user_pw.append(line.split(":")[1].strip().split(", "))

	user_acc = dict(zip(user_id, user_pw))
	
	print user_acc
	
	while (id_plain in user_id) == False:
		print "Sorry, you are not registered member."
		yn = raw_input("Are you want to re-input your id? (Y / N)")
		if yn == 'Y' or yn == 'y':
			id_plain = raw_input("User ID : ")
		elif yn == 'N' or yn == 'n':
			print "Return to main menu"
			return 0
	password_plain = raw_input("User Password : "******"Sorry, the entered password is not correct"
		yn = raw_input("Are you want to re-input your password? (Y / N)")
		if yn == 'Y' or yn == 'y':
			password_plain = raw_input("User Password : "******"Return to main menu"
			return 0
	print "Hello", id_plain + ":", user_acc[id_plain][1:], "!"
Пример #13
0
def set_mail(user, email):
	if email != "":
		profile = user.get_profile()
		# Build the activation key for their account
		salt = sha.new(str(random.random())).hexdigest()[:5]
		confirmation_key = sha.new(salt+user.username).hexdigest()
		key_expires = datetime.datetime.today() + datetime.timedelta(2)



		profile.confirmation_key = confirmation_key
		profile.key_expires = key_expires
		profile.mail_confirmed = False
		profile.save()
		user.email = email
		user.save()
		# Send an email with the confirmation link

		email_subject = 'Your new hardware-fuer-alle.de email confirmation'
		email_body = """Hallo, %s, um deine E-Mail Adresse bei hardware-fuer-alle.de einzutragen musst du sie noch bestätigen\n
		Bitte klicke hierfür innerhalb der nächsten 48 Stunden auf diesen Link:\n\nhttp://hardware-fuer-alle.de/beta/accounts/confirm/%s""" % (
			user.username,
			profile.confirmation_key)
		send_mail(email_subject,
				email_body,
				'*****@*****.**',
				[user.email])
Пример #14
0
def cadastrar_usuario(request):
    dados = template_data(request)
    if request.method == 'POST':
        form = UsuarioForm(request.POST, auto_id=False, error_class=DivErrorList)
        if form.is_valid():
            u = form.save()
            salt = sha.new(str(random.random())).hexdigest()[:5]
            chave = sha.new(salt + u.username).hexdigest()
            expira = datetime.datetime.today() + datetime.timedelta(2)
            usuario = Usuario(conta=u,
                              cpf=form.cleaned_data['cpf'],
                              chave_de_ativacao=chave,
                              expiracao_chave=expira,
                              nascimento=form.cleaned_data['nascimento'],
                              sexo=form.cleaned_data['sexo'],
                              telefone=form.cleaned_data['telefone_contato'])
            request.session['pass'] = form.cleaned_data['senha']
            request.session['conta'] = u
            request.session['usuario_cadastro'] = usuario
            form = EnderecoForm()
            dados['form'] = form
            return render_to_response('finalizar_cadastro.html', dados,
                              context_instance=RequestContext(request))
        else:
            dados['form'] = form
            return render_to_response('cadastro.html', dados,
                                      context_instance=RequestContext(request))
    else:
        form = UsuarioForm()
        dados['form'] = form
    return render_to_response('cadastro.html', dados,
                              context_instance=RequestContext(request))
Пример #15
0
def _verify_ftp_upload_integrity(file, file_url):
    """Download the file, and make sure that it matches the original.

    Returns True on success, and raises an Exception on failure.

    FIXME: Ideally we wouldn't have to download the whole file, we'd have
           some better way of verifying the integrity of the upload.
    """
    file.seek(0)
    old_hash = sha.new(file.read()).hexdigest()
    tries = 0

    # Try to download the file. Increase the number of retries, or the
    # timeout duration, if the server is particularly slow.
    # eg: Akamai usually takes 3-15 seconds to make an uploaded file
    #     available over HTTP.
    while tries < config.ftp_upload_integrity_retries:
        time.sleep(3)
        tries += 1
        try:
            temp_file = urllib2.urlopen(file_url)
            new_hash = sha.new(temp_file.read()).hexdigest()
            temp_file.close()

            # If the downloaded file matches, success! Otherwise, we can
            # be pretty sure that it got corrupted during FTP transfer.
            if old_hash == new_hash:
                return True
            else:
                raise FTPUploadException(
                    'Uploaded File and Downloaded File did not match')
        except urllib2.HTTPError, e:
            pass
Пример #16
0
 def set_password(self, raw_password):
     """
     Hashes the password w/ random salt and stores it.
     """
     salt = sha.new(str(random.random())).hexdigest()[:7]
     hsh = sha.new(salt + smart_str(raw_password)).hexdigest()
     self.password = '******' % (salt, hsh)
Пример #17
0
    def generate_image(self, ipAddress):
        
        num_numbers = randint(1, 4)
        num_letters = 5 - num_numbers
        tipo_validacao = randint(0,1)
        pergunta=""
       
        imgtextL = ''.join([choice('QWERTYUOPASDFGHJKLZXCVBNM') for i in range(num_letters)])
        imgtextN = ''.join([choice('123456789') for i in range(num_numbers)])

        SALT = SECRET_KEY[:20]
        imgtext = ''.join([choice(imgtextL + imgtextN) for i in range(5)])
        im=Image.open(MEDIA_ROOT + 'images/jpg/captcha.jpg')
        draw = ImageDraw.Draw(im)
        font = ImageFont.truetype("/media/font/yellow_submarine.ttf", 30)
        draw.text((28,10),imgtext, font=font, fill=(255,255,255))
        temp = MEDIA_ROOT + "images/temp/" + ipAddress + '.jpg'
        tempname = ipAddress + '.jpg'
        im.save(temp, "JPEG")
       
        if tipo_validacao == 0:
            pergunta="n&uacute;meros"
            imghash = sha.new(SALT+imgtextN).hexdigest()
        if tipo_validacao == 1:
            pergunta="letras"
            imghash = sha.new(SALT+imgtextL).hexdigest()
        return {'captcha_img_name':tempname, 'hash_code_captcha':imghash, 'tipo_validacao':pergunta}
Пример #18
0
def register(request):
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid() :
            username = form.clean_username()
            password = form.clean_password2()
            
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_key = sha.new(salt+username).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)
            
            user = form.save()
            #  user.is_active = False
            user.save()
            profile = UserProfile(user=user,
                                      activation_key=activation_key,
                                      key_expires=key_expires)
            profile.save()
            
            user = authenticate(username=username, password=password)
            login(request, user)
            #do stuff
            return HttpResponseRedirect("/")
            
    else:
        form = UserCreateForm()
    return render_to_response("registration/register.html", {"form" : form }, context_instance=RequestContext(request))
    def create_inactive_user(self, username, password, email, send_email=True):
        """
        Creates a new User and a new RegistrationProfile for that
        User, generates an activation key, and mails it.
        
        Pass ``send_email=False`` to disable sending the email.
        
        """
        # Create the user.
        new_user = User.objects.create_user(username, email, password)
        
        new_user.is_active = False
        new_user.save()
        
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation_key = sha.new(salt+new_user.email).hexdigest()
        
        # And finally create the profile.
        new_profile = self.create(user=new_user, activation_key=activation_key)
        
        if send_email:
            current_domain = Site.objects.get_current().domain
            contxt=Context({ 'site_url': 'http://%s/' % current_domain,'activation_key': activation_key,'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
            message_template = loader.get_template('registration/activation_email.html')
            message=message_template.render(contxt)
            msg=EmailMultiAlternatives('Activate your account at Itechtalents',message,settings.DEFAULT_FROM_EMAIL,[new_user.email])
            msg.attach_alternative(message, "text/html")
            msg.send()
	return new_user    
Пример #20
0
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    # Check to see if unicode names worked out.
    if not request.FILES['file_unicode'].file_name.endswith(u'test_\u4e2d\u6587_Orl\xe9ans.jpg'):
        return HttpResponseServerError()

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = sha.new(value.read()).hexdigest()
        else:
            new_hash = sha.new(value).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    return HttpResponse('')
 def send_confirmation(self, email_address):
     salt = sha.new(str(random())).hexdigest()[:5]
     confirmation_key = sha.new(salt + email_address.email).hexdigest()
     current_site = Site.objects.get_current()
     # check for the url with the dotted view path
     try:
         path = reverse("emailconfirmation.views.confirm_email",
             args=[confirmation_key])
     except NoReverseMatch:
         # or get path with named urlconf instead
         path = reverse(
             "emailconfirmation_confirm_email", args=[confirmation_key])
     activate_url = u"http://%s%s" % (unicode(current_site.domain), path)
     context = {
         "user": email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "confirmation_key": confirmation_key,
     }
     subject = render_to_string(
         "emailconfirmation/email_confirmation_subject.txt", context)
     # remove superfluous line breaks
     subject = "".join(subject.splitlines())
     message = render_to_string(
         "emailconfirmation/email_confirmation_message.txt", context)
     send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
               [email_address.email], priority="high")
     return self.create(
         email_address=email_address,
         sent=datetime.now(),
         confirmation_key=confirmation_key)
Пример #22
0
def get_my_client(sandbox=True):
	# WARNING -don't forget path wsse file !!!! 
	
	#print path
	#print os.getcwd()
	#Variables
	user_name='*****@*****.**'
	password = '******'
	
	#Init client
	if sandbox:
		wsdl_file='sandbox_ShippingAPI_V2_0_8.wsdl'
		application_id=sandbox_app_id
	else:
		wsdl_file='ShippingAPI_V2_0_8.wsdl'
		application_id=work_app_id
		
	client= getClient('file://'+path+'/schemas/'+wsdl_file, key, cert)
	
	#Calc Variables
	tt=datetime.now()
	create_date =  time.strftime('%Y-%m-%dT%H:%M:%SZ', tt.timetuple())

	nonce =  str(random.randint(0,9999999999))
	hashedpassword = sha.new(password).digest()
	digest = sha.new(nonce + create_date + hashedpassword).digest()
	pass_digi = base64.b64encode(digest)
	code_nonce = base64.b64encode(nonce)
	trans_id= str(random.randint(0,9999999999))
	
	#Print debug info
	#print 'Nonce = ', nonce
	#print 'pass_digi= ', pass_digi
	#print 'code_nonce= ', code_nonce
	#print 'create_date= ', create_date
	#print 'trans id= ', trans_id
	
	#Set Security Header
	security = Security()
	
	token = UsernameToken(user_name, pass_digi)
	token.setnonce(code_nonce)
	token.setcreated(create_date)
	
	security.tokens.append(token)
	
	client.set_options(wsse=security)
	
	#Set vals integrationHeader
	indetification={
					'applicationId': application_id,
					'transactionId':trans_id,
					}
	header={
					'dateTime': create_date,
					'version': '2',
					'identification':indetification,
	}

	return client, header
Пример #23
0
  def save(self,request):
      new_user=super(UserForm,self).save(commit=False)
      new_user.username=new_user.username.lower()
      new_user.slug=slugify(new_user.username)
      new_user.is_active=False
      new_user.set_password(new_user.password)

      #create activation key
      salt = sha.new(str(random.random())).hexdigest()[:5]
      new_user.activation_key = sha.new(salt+new_user.username).hexdigest()

      new_user.save()
      #EMAIL USER OF ACTIVATION KEY
      from django.core.mail import send_mail
      if request.is_secure():
        current_site = 'https://%s' % request.get_host()
      else:
        current_site = 'http://%s' % request.get_host()

      subject = render_to_string('account/activation_email_subject.html',
                                 { 'site': current_site })
      # Email subject *must not* contain newlines
      subject = ''.join(subject.splitlines())

      message = render_to_string('account/activation_email.html',
                                 { 'activation_key': new_user.activation_key,
                                   'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                   'site': current_site })
      if getattr(settings,'EMAIL_HOST',False):
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
      return new_user
Пример #24
0
def pending_message(from_address, to_address, subject, comment):
    """
    Create a pending message and send the activation email.
    """
    import random, sha
    from django.contrib.sites.models import Site
    from django.conf import settings

    # Store the email in the pending message db
    salt = sha.new(str(random.random())).hexdigest()[:5]
    activation_key = sha.new(salt+subject+from_address).hexdigest()

    # Fix the to_address if necessary
    to_address = ','.join(to_address)

    # Prepare the message to send to the user
    message = Pending_Messages(from_address=from_address,
                to_address=to_address,
                subject=subject,
                comment=comment,
                digest=activation_key)
    message.save()
    message_template = loader.get_template('activate_comment.txt')
    message_context = Context({ 'activation_key': activation_key,
                                'subject': subject,
                                'text': comment,
                                'to_address': to_address,
                                'from_address': from_address,
                                'site_url': Site.objects.get_current().domain
                                })
    message = message_template.render(message_context)
    # Send the email to the user
    subject = 'Activate the bug actions you prepared at Amancay'
    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [from_address])
Пример #25
0
def register(request):
	if request.POST:
		regForm = RegistrationForm(request.POST)
		
		if request.user.is_authenticated():
			return render_to_response('Accounts/register.html',{'has_account':True})
		
		new_data = request.POST.copy()
		errors = regForm.get_validation_errors(new_data)
		
		if not errors:
			# save the user
			regForm.do_html2python(new_data)
			new_user = regForm.save(new_data)
			# Build the activation key for their account  
			salt = sha.new(str(random.random())).hexdigest()[:5]
			activation_key = sha.new(salt+new_user.username).hexdigest()
			key_expires = datetime.datetime.today() + datetime.timedelta(2)
			 
			# Create and save their profile
			new_profile = UserProfile(user = new_user, activation_key = activation_key,key_expires=key_expires)
			new_profile.save 
		
	
	else:
		   regForm=RegistrationForm()
	return render_to_response('Accounts/register.html',{ 'form':regForm})
Пример #26
0
    def deactivate_subscription(self, instance, email_template='newsletters/opt-out.html', send_email=True):
        """
        emails its deactivation key to the user.
        Returns the Subscription.

        To disable the email, call with send_email=False.
        """
        salt = sha.new(str(random.random())).hexdigest()[:5]
        deactivation_key = sha.new(salt+instance.email).hexdigest()[:16]
        
        instance.activation_key = deactivation_key
        instance.save()
        
        if send_email:
            from django.core.mail import send_mail
            from django.template.loader import render_to_string
            from django.contrib.sites.models import Site

            current_site = Site.objects.get_current()

            subject = ugettext('Confirm your unsubscription to %s' % (current_site.name))

            message = render_to_string(email_template,
                                       { 'deactivation_key': instance.activation_key,
                                         'site': current_site,
                                         'user': instance,
                                         'email': instance.email
                                        })

            send_mail(subject, message, settings.NEWSLETTER_FROM_EMAIL, [instance.email], fail_silently=True)
        return instance
Пример #27
0
    def create_inactive_subscription(self, instance, email_template='newsletters/opt-in.html', send_email=True, activation_key=None):
        """
        Creates a new, inactive Subscription, generates a
        Subscription and emails its activation key to the
        user. Returns the new Subscription.

        To disable the email, call with send_email=False.
        """
        if not activation_key:
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_key = sha.new(salt+instance.email).hexdigest()[:16]
        
        instance.activation_key = activation_key
        instance.subscribed = False
        instance.save()
        
        if send_email:
            from django.core.mail import send_mail
            from django.template.loader import render_to_string
            from django.contrib.sites.models import Site
            
            current_site = Site.objects.get_current()

            subject = ugettext('Confirm your subscription to %s' % (current_site.name))

            message = render_to_string(email_template,
                                       { 'activation_key': instance.activation_key,
                                         'expiration_days': settings.NEWSLETTER_ACTIVATION_DAYS,
                                         'site': current_site,
                                         'user': instance,
                                         'email': instance.email 
                                        })

            send_mail(subject, message, settings.NEWSLETTER_FROM_EMAIL, [instance.email], fail_silently=True)
        return instance
Пример #28
0
    def create_email_change(self, user, new_email, send_email=True):
        """
        Create ActionRecord for email change and mails link
        with activation key to user's email.

        Pass ``send_email=False`` to disable sending the email.
        """
        if not user.email:
            user.email = new_email
            user.save()
            return
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        action_key = sha.new(salt+user.email).hexdigest()

        # And finally create the record.
        user.email_new = new_email
        user.save()
        record, created = self.get_or_create(user=user,
                                             type='E',
                                             defaults={'action_key': action_key})

        if send_email:
            current_domain = Site.objects.get_current().domain
            subject = "Change your email address at %s" % current_domain
            message_template = loader.get_template('accounts/password_reset.txt')
            message_context = Context({'site_url': '%s://%s' % (settings.SITE_PROTOCOL, current_domain),
                                       'action_key': record.action_key,
                                       'expiration_days': settings.ACTION_RECORD_DAYS,
                                       'user': user})
            message = message_template.render(message_context)
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        return record
Пример #29
0
def mkpasswd(pwd,hash='ssha'):
    """Generate hashed passwords. Originated from mkpasswd in Luma
    """
    alg = {
        'ssha':'Seeded SHA-1',
        'sha':'Secure Hash Algorithm',
        'smd5':'Seeded MD5',
        'md5':'MD5',
        'crypt':'Standard unix crypt'
    }
    # Don't add support for sambapasswords unless we're using it
    if (update_sambapassword):
        alg['lmhash'] = 'Lanman hash'
        alg['nthash'] = 'NT Hash'
    if hash not in alg.keys():
        return "Algorithm <%s> not supported in this version." % hash
    else:
        salt = getsalt()
        if hash == "ssha":
            return "{SSHA}" + base64.encodestring(sha.new(str(pwd) + salt).digest() + salt)
        elif hash == "sha":
            return "{SHA}" + base64.encodestring(sha.new(str(pwd)).digest())
        elif hash == "md5":
            return "{SHA}" + base64.encodestring(md5.new(str(pwd)).digest())
        elif hash == "smd5":
            return "{SMD%}" + base64.encodestring(md5.new(str(pwd) + salt).digest() + salt)
        elif hash == "crypt":
            return "{CRYPT}" + crypt.crypt(str(pwd),getsalt(length=2))
        # nt/lm-hash are used directly in their own password-attributes.. no need to prefix the hash
        elif hash == "lmhash":
            return smbpasswd.lmhash(pwd)
        elif hash == "nthash":
            return smbpasswd.nthash(pwd)
Пример #30
0
	def save(self, *args, **kwargs):
		if not self.id:
			self.key_generated = timezone.now()
              
           

			salt = sha.new(str(random.random())).hexdigest()[:5]
			verification_key = sha.new(salt+self.email).hexdigest()

                
			self.verification_key = verification_key
			self.set_unusable_password()
			self.is_verified=False
			subject = "Activate your account"
			print self.email
			html_content = render_to_string('registration/mail/welcome.html', { 'first_name':self.first_name,
																	'last_name':self.last_name,
																'site_url': settings.SITE_URL, 
                                                               'verification_key': verification_key,
                                                                'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
			text_content = strip_tags(html_content)
                                   # create the email, and attach the HTML version as well.
			msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_TO, to=[self.email])
			msg.attach_alternative(html_content, "text/html")
			msg.send()
		super(AppUser, self).save(*args, **kwargs)
Пример #31
0
 def gen_boundary():
     """Returns a random string to use as the boundary for a message"""
     bits = random.getrandbits(160)
     return sha.new(str(bits)).hexdigest()
Пример #32
0
def token2hash(token):
    m = sha.new(token)
    return m.digest()[:8]
Пример #33
0
def sha1(file):
    z = open(file, 'rb')
    sha1 = sha.new(z.read()).hexdigest()
    return (sha1)
Пример #34
0
def generate_authenticator_response(nt_response,
                                    peer_challenge,
                                    authenticator_challenge,
                                    username,
                                    password=False,
                                    password_hash=False):
    """
   GenerateAuthenticatorResponse(
   IN  0-to-256-unicode-char Password,
   IN  24-octet              NT-Response,
   IN  16-octet              PeerChallenge,
   IN  16-octet              AuthenticatorChallenge,
   IN  0-to-256-char         UserName,
   OUT 42-octet              AuthenticatorResponse )
   {
      16-octet              PasswordHash
      16-octet              PasswordHashHash
      8-octet               Challenge

      /*
       * "Magic" constants used in response generation
       */

      Magic1[39] =
         {0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76,
          0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65,
          0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67,
          0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74};

      Magic2[41] =
         {0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B,
          0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F,
          0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E,
          0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F,
          0x6E};

      /*
       * Hash the password with MD4
       */

      NtPasswordHash( Password, giving PasswordHash )

      /*
       * Now hash the hash
       */

      HashNtPasswordHash( PasswordHash, giving PasswordHashHash)

      SHAInit(Context)
      SHAUpdate(Context, PasswordHashHash, 16)
      SHAUpdate(Context, NTResponse, 24)
      SHAUpdate(Context, Magic1, 39)
      SHAFinal(Context, Digest)

      ChallengeHash( PeerChallenge, AuthenticatorChallenge, UserName,
                     giving Challenge)

      SHAInit(Context)
      SHAUpdate(Context, Digest, 20)
      SHAUpdate(Context, Challenge, 8)
      SHAUpdate(Context, Magic2, 41)
      SHAFinal(Context, Digest)

      /*
       * Encode the value of 'Digest' as "S=" followed by
       * 40 ASCII hexadecimal digits and return it in
       * AuthenticatorResponse.
       * For example,
       *   "S=0123456789ABCDEF0123456789ABCDEF01234567"
       */

   }
    """
    Magic1 = "\x4D\x61\x67\x69\x63\x20\x73\x65\x72\x76\x65\x72\x20\x74\x6F\x20\x63\x6C\x69\x65\x6E\x74\x20\x73\x69\x67\x6E\x69\x6E\x67\x20\x63\x6F\x6E\x73\x74\x61\x6E\x74"
    Magic2 = "\x50\x61\x64\x20\x74\x6F\x20\x6D\x61\x6B\x65\x20\x69\x74\x20\x64\x6F\x20\x6D\x6F\x72\x65\x20\x74\x68\x61\x6E\x20\x6F\x6E\x65\x20\x69\x74\x65\x72\x61\x74\x69\x6F\x6E"

    # the2nd: modifed for OTPme to allow verification without the need to have a clear-text password
    # if we got a password we have to generate its hash and hash_hash
    if password:
        password_hash = nt_password_hash(password, False)
        password_hash_hash = hash_nt_password_hash(password_hash)
    elif password_hash:
        # if we got the password_hash we only have to generate the hash_hash
        password_hash_hash = hash_nt_password_hash(password_hash)

    sha_hash = sha.new()
    sha_hash.update(password_hash_hash)
    sha_hash.update(nt_response)
    sha_hash.update(Magic1)
    digest = sha_hash.digest()

    challenge = challenge_hash(peer_challenge, authenticator_challenge,
                               username)

    sha_hash = sha.new()
    sha_hash.update(digest)
    sha_hash.update(challenge)
    sha_hash.update(Magic2)
    digest = sha_hash.digest()

    return "S=" + convert_to_hex_string(digest)
Пример #35
0
 def _shaDecoder(self, cleartext, cryptotext):
     import sha
     return sha.new(cleartext).hexdigest() == cryptotext
Пример #36
0
 def _shaEncoder(self, cleartext):
     import sha
     return sha.new(cleartext).hexdigest()
Пример #37
0
    def apply(self, option=None):
        

        action_record = []

        # Step 1: Check to see if NTP package is installed.
        results = sb_utils.os.software.is_installed(pkgname=self.__pkgname)
        if results == False:
            msg = "%s package is not installed on the system" % self.__pkgname
            self.logger.info(self.module_name, 'Not Applicable: ' + msg)
            return 0, ''

        # Did module receive ntp.conf text?
        if option == None or option == '':
            msg = "No ntp.conf text provided"
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) 

        # Capture current running status?
        results = sb_utils.os.service.status(svcname=self.__svcname)
        if results == True:
            action_record.append('RUNNING=yes\n') 
        else:
            action_record.append('RUNNING=no\n') 

        # Chkconfig status? Is it configured to be started during boot?
        results = sb_utils.os.service.is_enabled(svcname=self.__svcname)
        if results == True:
            action_record.append('CHKCONFIG=on\n') 
        else:
            sb_utils.os.service.enable(svcname=self.__svcname)
            action_record.append('CHKCONFIG=off\n') 
        

        # Replace contents of ntp.conf it doesn't match the provided content
        master_fingerprint = sha.new(option).hexdigest()
        apply_problem = False
        if self._sha1(self.__ntpconf) != master_fingerprint:
            if os.path.isfile(self.__ntpconf):
                # Capture ntp.conf contents
                try:
                    infile = open(self.__ntpconf, 'r')
                    lines = infile.readlines()
                    infile.close()
                except IOError, err:
                    msg = "Unable to read %s: %s" % (self.__ntpconf, err)
                    self.logger.error(self.module_name, 'Apply Error: ' + msg)
                    raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
            else:
                lines = "EMPTY\n"
        
            record = "NTPCONFIGFILE\n%s\n" % (''.join(lines))
            action_record.append(record)
                 

            # Copy provided content into ntp.conf
            try: 
                out_obj = open(self.__ntpconf, 'w')
                out_obj.write(option)
                out_obj.close()
                msg = "Apply Performed: %s updated." % (self.__ntpconf)
                self.logger.notice(self.module_name, msg)
            except (OSError, IOError), err: 
                apply_problem = True
                msg = "Unable to update %s: %s" % (self.__ntpconf, err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
Пример #38
0
 def new(algo):
     if algo == 'md5':
         return md5.new()
     if algo == 'sha1':
         return sha.new()
     raise ValueError, "Bad checksum type"
Пример #39
0
def hashPassword(sid, password):
    """
    Create a SHA1-digest string of a session identifier and password.
    """
    import sha
    return sha.new("%s%s" % (sid, password)).hexdigest()
Пример #40
0
def _make_hash(data):
    return "hash-data:SHA:" + sha.new(pickle.dumps(data)).hexdigest()[:20]
Пример #41
0
    def findInvalidFiles(self):
        filesInCurrPiece = []
        sha1Hasher = sha.new()
        pieceUsed = 0L
        pieceIndex = 0
        filesProcessed = 0

        for fileName, fileSize in self.fileList:
            fileIndex = 0
            fileChunk = None

            try:
                fileData = open(fileName)
            except IOError:
                fileData = None

            while pieceUsed + (fileSize - fileIndex) >= self.pieceLen:
                sizeToRead = self.pieceLen - pieceUsed
                try:
                    fileChunk = fileData.read(sizeToRead)
                    if len(fileChunk) < sizeToRead:
                        fileChunk = fileChunk + '\0' * (sizeToRead -
                                                        len(fileChunk))
                except:
                    fileChunk = '\0' * sizeToRead

                sha1Hasher.update(fileChunk)
                filesInCurrPiece.append(fileName)

                if sha1Hasher.digest() != self.pieceList[pieceIndex]:
                    self.badPieceCount = self.badPieceCount + 1
                    for newInvFile in filesInCurrPiece:
                        if newInvFile not in self.invalidList:
                            self.invalidList.append(newInvFile)
                else:
                    for newGoodFile in filesInCurrPiece:
                        if newGoodFile not in self.filesWithGood:
                            self.filesWithGood.append(newGoodFile)

                sha1Hasher = sha.new()
                pieceUsed = 0
                fileIndex = fileIndex + sizeToRead
                pieceIndex = pieceIndex + 1
                filesInCurrPiece = []

                print >> sys.stderr, '%(fc)u of %(ft)u files (%(fb)u bad) - %(pc)u of %(pt)u pieces (%(pb)u bad) - %(pct)05.2f%% complete\r' % {
                    'fc': filesProcessed,
                    'ft': len(self.fileList),
                    'fb': len(self.invalidList),
                    'pc': pieceIndex,
                    'pt': len(self.pieceList),
                    'pb': self.badPieceCount,
                    'pct': (100.0 * pieceIndex) / len(self.pieceList)
                },

            sizeToRead = fileSize - fileIndex
            if sizeToRead > 0:
                try:
                    fileChunk = fileData.read(sizeToRead)
                    if len(fileChunk) < sizeToRead:
                        fileChunk = fileChunk + '\0' * (sizeToRead -
                                                        len(fileChunk))
                except:
                    fileChunk = '\0' * sizeToRead

                sha1Hasher.update(fileChunk)
                filesInCurrPiece.append(fileName)
                pieceUsed = pieceUsed + sizeToRead
            filesProcessed = filesProcessed + 1
            print >> sys.stderr, '%(fc)u of %(ft)u files (%(fb)u bad) - %(pc)u of %(pt)u pieces (%(pb)u bad) - %(pct)05.2f%% complete\r' % {
                'fc':
                filesProcessed,
                'ft':
                len(self.fileList),
                'fb':
                len(self.invalidList),
                'pc':
                pieceIndex,
                'pt':
                len(self.pieceList),
                'pb':
                self.badPieceCount,
                'pct':
                (100.0 *
                 (pieceIndex +
                  (1.0 * pieceUsed) / self.pieceLen)) / len(self.pieceList)
            },
        print
Пример #42
0
 def make_hash(cls, ip, fullname):
     return sha.new("%s%s" % (fullname, g.tracking_secret)).hexdigest()
Пример #43
0
def student_edit_view(context, request):

    if IStudent.providedBy(context):
        student = context
        context = student.__parent__
        add_form = False
    else:
        student = Student(id=uuid.uuid4())
        add_form = True

    errors = {}
    defaults = {}

    if 'form.submitted' in request.POST:
        try:
            # FormEncode validation
            defaults = dict(request.POST)
            state = FormencodeState()
            state.user_id = student.user_name
            if add_form:
                form_result = student_add_schema.to_python(request.POST, state)
            else:
                form_result = student_schema.to_python(request.POST, state)
        except formencode.validators.Invalid, why:
            errors = why.error_dict
        else:
            changed = False

            # Convert password to SHA hash
            if form_result.get('password', None):
                form_result['password'] = '******' % sha.new(
                    form_result['password']).hexdigest()
                changed = True

            # Handle portrait upload
            if form_result['portrait'] is not None:

                # Scale image and convert to JPEG
                im = Image.open(form_result['portrait'].file)
                im.thumbnail((128, 128), Image.ANTIALIAS)
                # Convert to RGB if neccessary
                if im.mode != "RGB":
                    im = im.convert("RGB")
                outfile = StringIO()
                im.save(outfile, "JPEG")
                outfile.seek(0)

                student.portrait = File('portrait.jpg', outfile.read())
                changed = True

            del form_result['portrait']

            # Apply schema fields to the student object
            field_names = [
                p.key for p in class_mapper(Student).iterate_properties
            ]
            for field_name in field_names:
                if field_name in form_result.keys():
                    if form_result[field_name] != getattr(student, field_name):
                        setattr(student, field_name, form_result[field_name])
                        changed = True

            # Add student if this is the add form
            if add_form:
                session = DBSession()
                session.add(student)

                if not form_result['password']:
                    reset_url = model_url(get_root(request), request,
                                          'retrieve_password.html')
                    student.send_password_reset(reset_url)

            return HTTPFound(
                location=model_url(context, request, str(student.id)))
Пример #44
0
 def sha1hex(data):
   return sha.new(data).hexdigest().lower()
Пример #45
0
def new_user_id():
    sid = sha.new(repr(time.time())).hexdigest()
    return sid
Пример #46
0
def hashSID(sid, initiator, target):
    import sha
    return sha.new("%s%s%s" % (sid, initiator, target)).hexdigest()
Пример #47
0
        import python_des
    Des = python_des.Des
    # Import Psyco if available
    try:
        # http://psyco.sourceforge.net
        import psyco
        psyco.full()
    except ImportError:
        pass

try:
    from hashlib import sha1
except ImportError:
    # older Python release
    import sha
    sha1 = lambda s: sha.new(s)

import cgi
import logging

logging.basicConfig()
#logging.basicConfig(level=logging.DEBUG)


class Sectionizer(object):
    bkType = "Book"

    def __init__(self, filename, ident):
        self.contents = file(filename, 'rb').read()
        self.header = self.contents[0:72]
        self.num_sections, = struct.unpack('>H', self.contents[76:78])
Пример #48
0
    def post(self):
        (forum, siteroot,
         tmpldir) = forum_siteroot_tmpldir_from_url(self.request.path_info)
        if not forum or forum.is_disabled:
            return self.redirect("/forum/")
        if self.request.get('Cancel'):
            return self.redirect(siteroot)

        ip = get_remote_ip()
        if ip in BANNED_IPS:
            return self.redirect(siteroot)

        self.send_cookie()

        vals = [
            'TopicId', 'num1', 'num2', 'Captcha', 'Subject', 'Message',
            'Remember', 'Email', 'Name', 'Url'
        ]
        (topic_id, num1, num2, captcha, subject, message, remember_me, email,
         name, homepage) = req_get_vals(self.request, vals)
        message = to_unicode(message)

        remember_me = True
        if remember_me == "": remember_me = False
        rememberChecked = ""
        if remember_me: rememberChecked = "checked"

        validCaptcha = True
        try:
            captcha = int(captcha)
            num1 = int(num1)
            num2 = int(num2)
        except ValueError:
            validCaptcha = False

        homepage = sanitize_homepage(homepage)
        tvals = {
            'siteroot': siteroot,
            'forum': forum,
            'num1': num1,
            'num2': num2,
            'num3': int(num1) + int(num2),
            "prevCaptcha": captcha,
            "prevSubject": subject,
            "prevMessage": message,
            "rememberChecked": rememberChecked,
            "prevEmail": email,
            "prevUrl": homepage,
            "prevName": name,
            "prevTopicId": topic_id,
            "log_in_out": get_log_in_out(siteroot + "post")
        }

        # validate captcha and other values
        errclass = None
        if not validCaptcha or (captcha != (num1 + num2)):
            errclass = 'captcha_class'
        if not message: errclass = "message_class"
        if not name: errclass = "name_class"
        if not valid_email(email): errclass = "email_class"
        # first post must have subject
        if not topic_id and not subject: errclass = "subject_class"

        # sha.new() doesn't accept Unicode strings, so convert to utf8 first
        message_utf8 = message.encode('UTF-8')
        s = sha.new(message_utf8)
        sha1_digest = s.hexdigest()

        duppost = Post.gql("WHERE sha1_digest = :1", sha1_digest).get()
        if duppost: errclass = "message_class"

        if errclass:
            tvals[errclass] = "error"
            tmpl = os.path.join(tmpldir, "post.html")
            return self.template_out(tmpl, tvals)

        # get user either by google user id or cookie. Create user objects if don't
        # already exist
        existing_user = False
        user_id = users.get_current_user()
        if user_id:
            user = FofouUser.gql("WHERE user = :1", user_id).get()
            if not user:
                #logging.info("Creating new user for '%s'" % str(user_id))
                user = FofouUser(user=user_id,
                                 remember_me=remember_me,
                                 email=email,
                                 name=name,
                                 homepage=homepage)
                user.put()
            else:
                existing_user = True
                #logging.info("Found existing user for '%s'" % str(user_id))
        else:
            cookie = self.get_cookie_val()
            user = FofouUser.gql("WHERE cookie = :1", cookie).get()
            if not user:
                #logging.info("Creating new user for cookie '%s'" % cookie)
                user = FofouUser(cookie=cookie,
                                 remember_me=remember_me,
                                 email=email,
                                 name=name,
                                 homepage=homepage)
                user.put()
            else:
                existing_user = True
                #logging.info("Found existing user for cookie '%s'" % cookie)

        if existing_user:
            need_update = False
            if user.remember_me != remember_me:
                user.remember_me = remember_me
                need_update = True
            if user.email != email:
                user.email = email
                need_update = True
            if user.name != name:
                user.name = name
                need_update = True
            if user.homepage != homepage:
                user.homepage = homepage
                need_update = True
            if need_update:
                #logging.info("User needed an update")
                user.put()

        if not topic_id:
            topic = Topic(forum=forum, subject=subject, created_by=name)
            topic.put()
        else:
            topic = db.get(db.Key.from_path('Topic', int(topic_id)))
            #assert forum.key() == topic.forum.key()
            topic.ncomments += 1
            topic.put()

        user_ip_str = get_remote_ip()
        p = Post(topic=topic,
                 forum=forum,
                 user=user,
                 user_ip=0,
                 user_ip_str=user_ip_str,
                 message=message,
                 sha1_digest=sha1_digest,
                 user_name=name,
                 user_email=email,
                 user_homepage=homepage)
        p.put()
        memcache.delete(rss_memcache_key(forum))
        clear_topics_memcache(forum)
        if topic_id:
            self.redirect(siteroot + "topic?id=" + str(topic_id))
        else:
            self.redirect(siteroot)
Пример #49
0
 def fetch_password(username):
     return sha.new('test').hexdigest()
Пример #50
0
def challenge_response(email, passwd, challenge):
    return sha.new(challenge + passwd).hexdigest()
Пример #51
0
 def sha_password_encrypter(password):
     return sha.new(password).hexdigest()
Пример #52
0
def user_register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(form.cleaned_data['username'],
                                            form.cleaned_data['email'],
                                            form.cleaned_data['password'])
            user.first_name = form.cleaned_data['firstname']
            user.last_name = form.cleaned_data['lastname']
            user.is_active = False
            user.save()

            # create a key
            random.seed()
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_key = sha.new(salt + form.cleaned_data['username']
                                     ).hexdigest()  # yes, i'm paranoiac
            key_expires = datetime.datetime.today() + datetime.timedelta(2)

            profile = Profile(user=user)
            profile.homepage = form.cleaned_data['homepage']
            profile.birthday = form.cleaned_data['birthday']
            profile.city = form.cleaned_data['city']
            profile.contributes_summary = form.cleaned_data[
                'contributes_summary']
            profile.activation_key = activation_key
            profile.show_email = form.cleaned_data['show_email']
            profile.key_expires = key_expires
            profile.avatar = Avatar.objects.get(id=1)
            profile.jabber = form.cleaned_data['jabber']
            profile.msn = form.cleaned_data['msn']
            profile.icq = form.cleaned_data['icq']
            if form.cleaned_data['pardus_version'] != 0:
                profile.pardus_version = form.cleaned_data['pardus_version']
            profile.save()

            for number in form.cleaned_data[
                    'contributes']:  # it's ManyToManyField's unique id
                user.get_profile().contributes.add(number)

            now = datetime.datetime.now()
            (date, hour) = now.isoformat()[:16].split("T")

            email_dict = {
                'date':
                date,
                'hour':
                hour,
                'ip_addr':
                request.META['REMOTE_ADDR'],
                'user':
                user.username,
                'link':
                '%s/kullanici/onay/%s/%s' %
                (WEB_URL, form.cleaned_data['username'], activation_key)
            }

            email_subject = u"Özgürlükİçin.com Kullanıcı Hesabı, %(user)s"
            email_body = u"""Merhaba!
%(date)s %(hour)s tarihinde %(ip_addr)s IP adresli bilgisayardan yaptığınız Özgurlukİçin kullanıcı hesabınızı onaylamak için lutfen asağıdaki bağlantıyı 48 saat içerisinde ziyaret ediniz.

%(link)s

Teşekkürler,
Özgurlukİçin"""

            email_to = form.cleaned_data['email']

            send_mail(email_subject % email_dict,
                      email_body % email_dict,
                      DEFAULT_FROM_EMAIL, [email_to],
                      fail_silently=True)

            return render_response(request, 'user/register_done.html', {
                'form': form,
                'user': form.cleaned_data['username']
            })
        else:
            return render_response(request, 'user/register.html',
                                   {'form': form})
    else:
        form = RegisterForm()
        return render_response(request, 'user/register.html', {'form': form})
Пример #53
0
def request_digest(url):
    return sha.new(url).hexdigest()
Пример #54
0
def entry_digest(d):
    return sha.new(repr(d)).hexdigest()
Пример #55
0
		if key is not None: 
			raise asyncore.ExitNow(key.group(2))
		return

def login():
	print "logging in"
	r = urlopen(Request('%slogin.php?action=in' % url, data="form_sent=1&req_username=%s&req_password=%s" % (user, pwd), headers={"User-agent": ua}))
	try:
		t = r.info()['set-cookie'].split(';')[0]
		return (t.split('=')[1].split('%7C')[0], t)
	except:
		sys.exit('unable to login, check user/pass')

uid, cookie = login()

email_domain = urlopen(Request('http://www.example1.com')).read()
print "using domain: %s" % email_domain

#this will change your password to your password :)
stage1('%s\'/**/where/**/id=%s# () %s' % (sha.new(pwd).hexdigest(), uid, email_domain))

#this will change admin's (uid=2) password "123456"
#stage1('%s\'/**/where/**/id=%s# () %s' % (sha.new("123456").hexdigest(), 2, email_domain))

try:
	print "2nd stage: waiting for mail"
	server = stage2_smtp((bindip, 25), None)
	asyncore.loop()
except asyncore.ExitNow, key:
	stage3(key)
Пример #56
0
 def _hashPassword(self, password):
     import sha
     hasher = sha.new()
     hasher.update(password)
     return hasher.hexdigest()
Пример #57
0
    except:
        traceback.print_exc()
        return None
    return signal


cur_files = set(
    [fn.split('.')[0] for fn in os.listdir('clips') if fn.endswith('.wav')])
data = []
for line in open('clips.jsons'):
    try:
        data.append(json.loads(line.strip()))
    except:
        print(line)
for d in data:
    d['hash'] = sha.new(d['url']).hexdigest()
data.sort(key=lambda d: (1 - int(d['hash'] in cur_files), d['hash']))

f = open('clips_analyzed_2.jsons', 'w')
lu2c = {}  # (lang, user) to count
urls = set()
fs = 22050
trim_s = 2.0
n_freqs = 500
df = []

for l in data:
    if l['url'] in urls:
        continue
    urls.add(l['url'])
    print l
Пример #58
0
 def __digest(self, aValue):
   value  = struct.pack("%ds" % len(aValue), aValue)
   h = sha.new()
   h.update(value)
   dg = h.hexdigest()
   return dg
Пример #59
0
    return result


def AddHyphens(code):
    """Insert hyphens into given license id or activation request to
    make it easier to read"""
    return code[:5] + '-' + code[5:10] + '-' + code[10:15] + '-' + code[15:]


#LicenseID='CNYKD-KALJK-JKKFV-WPHXT'
#Copy the Request Code from the dialog
#RequestCode='RW51P-L6ANX-223N6-TQMDL'
#RequestCode='RW51P-L6ANX-223N6-TQMDL'
LicenseID = 'CNYKD-KALJK-JKKFV-WPHXT'
RequestCode = 'RW711-RGGV3-T966R-HVNPA'
hasher = sha.new()
hasher.update(RequestCode)
hasher.update(LicenseID)
digest = hasher.hexdigest().upper()
lichash = RequestCode[:3] + SHAToBase30(digest)
lichash = AddHyphens(lichash)

#Calculate the Activation Code
data = [7, 123, 23, 87]
tmp = 0
realcode = ''

for i in data:
    for j in lichash:
        tmp = (tmp * i + ord(j)) & 0xFFFFF
    realcode += format(tmp, '=05X')
Пример #60
0
 def sha1_digest(bytes):
     return sha.new(bytes).hexdigest()