I need some of your help please,
I'm working with pysftp this is working great but now I'm trying to make it work to my project in Django worked great in console but I want to get the data from a form so I won't need to use the console to do that.
here's my view:
def sftp_form(request):
if request.method == 'POST':
form = sftpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
host = data['host']
usuario = data['usuario']
clave = data['clave']
print host
print usuario
print clave
else:
form=sftpForm()
return render(request, 'sftp.html', {'form':form})
def SFTP_subir():
host = raw_input('ingrese el host: ') # I want form's host here.
usuario = raw_input('ingrese el usuario: ')# I want form's usuario here.
clave = raw_input('ingrese la clave: ')# I want form's clave here.
try:
transferencia = sftp.Connection(host=host, username=usuario, password=clave)
remotepath= 'remotepath'
localpath="mylocalpath"
transferencia.put(localpath,remotepath)
print ('\n' + 'Sucess.')
except Exception, e:
print str(e)
as you can see in my code sftp_subir() it's asking me for host,usuario and clave from console, but I want to make it work with sftp_form() host,usuario and clave.
There seem to be a slight mixup here, you can't use raw_input in a django web app. If you using Django as a CLI you can't use an HTTP request. As #sayse suggested in the comments, if you are using a view in a web app all you need to do is to define your second function to be one that accepts paramers
def sftp_form(request):
if request.method == 'POST':
form = sftpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
host = data['host']
usuario = data['usuario']
clave = data['clave']
SFTP_subir(hosts, usuario,clave)
else:
form=sftpForm()
return render(request, 'sftp.html', {'form':form})
def SFTP_subir(hosts, usuario,clave):
try:
transferencia = sftp.Connection(host=host, username=usuario, password=clave)
remotepath= 'remotepath'
localpath="mylocalpath"
transferencia.put(localpath,remotepath)
print ('\n' + 'Sucess.')
except Exception, e:
print str(e)
Once you make this code you still have a long way to go because your SFTP method doesn't return any usefull response.
In your view:
def sftp_form(request):
if request.method == 'POST':
form = sftpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
host = data['host']
usuario = data['usuario']
clave = data['clave']
print host
print usuario
print clave
SFTP_subir(host, usuario, clave) # here you invoke the function, passing variables as arguments
else:
form=sftpForm()
return render(request, 'sftp.html', {'form':form})
Then refactor your function to receive those params:
def SFTP_subir(host, usuario, clave):
try:
transferencia = sftp.Connection(host=host, username=usuario, password=clave)
remotepath= 'remotepath'
localpath="mylocalpath"
transferencia.put(localpath,remotepath)
print ('\n' + 'Sucess.')
except Exception, e:
print str(e)
you can do the
sftp.connect(...)
...
<4 lines following>
inside the request.method == "POST" block instead of your print statements.
Related
The full stack it's already done, django is running in a server, the views are done,all done, that from is linked in a db, i just uploaded the script.py that will use the variables from that form.I have tried the similar solutions that I found here and nothing worked.
the project repository:
https://github.com/Mayri1/djangoPrimerProyecto.git
My failed attempt:
from django import usuarios
import paramiko
import time
HOST = ''
PORT ='22'
USER = 'xxxxx'
PASS= ''
datos =dict(hostname=HOST, port=PORT, username=USER)"""if __name__ == '__main__':*# try:*client = paramiko.SSHClient()
client.connect(HOST, PORT, USER, PASS, banner_timeout=200)
stdin, stdout, stderr = client.exec_command("ppp secret add name=\"" + {{ usuarios.nombre }} +"\" password=\"" + {{ usuarios.contraseña }} +"\" profile=OVPN service=ovpn")
time.sleep(1)
result = stdout.read().decode()# except paramiko.ssh_exception.AuthenticationException as e:# print('Autenticacion fallida')#export file=flash/prueba_export.backup to=C:\rmikrotikprint(result)
Another failed attempt:
#views
def testing(request):
mydata1 = Usuario.objects.filter(nombre='usuario.nombre').values()
mydata2 = Usuario.objects.filter(contraseña='usuario.contraseña').values()
template = loader.get_template('paginas/usuarios.html')
context = {
'usuario': mydata1,
'contraseña': mydata2
}
return HttpResponse(template.render(context, request))
In urls:
path('testing',views.testing, name='testing'),
Another:in views "create"
if formulario.is_valid():
formulario.save()
mk.recibir(formulario)
return redirect('usuarios')
in mk.py:
def recibir(request):
formulario = UsuarioForm(request.POST or None, request.FILES or None)
for x, y in formulario.items():
user = x
passw = y
print(user, passw)
return (recibir)
I've set up a password recovery system in my application which work pretty well however I'm facing a problem with the token issued which apparently never expire, at least when it gets used multiple time by the user.
The link sent by email to the user remain valid even after changing the password x times with the same link.
I'm using the regular way I've found on internet with token_generator.make_token(user)
utils.py
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class AppTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (text_type(user.is_active), text_type(user.pk), text_type(timestamp))
token_generator = AppTokenGenerator()
api_email.py
def send_email_user_account_password_recover(request, user, language):
try:
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
token = token_generator.make_token(user)
url_base = get_url_base(request)
email_text = emailText["user_account_password_recover"][language]
if language == "fr":
link_text = "Réinitialiser mon mot de passe"
activate_url = url_base + f"/fr/recover-password-authorised/{uidb64}/{token}/"
else:
link_text = "Reset my password"
activate_url = url_base + f"/en/recover-password-authorised/{uidb64}/{token}/"
context = {"title": email_text["title"],
"content": email_text["text"],
"url_base": url_base,
"link": activate_url,
"link_text": link_text,
"language": language}
html_content = render_to_string("email/email-template-extends.html", context)
text_content = strip_tags(html_content)
email = EmailMultiAlternatives(
subject=email_text["title"],
body=text_content,
to=[user.email])
email.attach_alternative(html_content, "text/html")
email.send(fail_silently=False)
logger.info(f"Email user password recover for user ({user.id_code}) sent from {EMAIL_HOST_USER} to {user.email}.")
return True
except:
logger.error(f"Email user password recover for user ({user.id_code}) could not be sent.")
return False
views.py
def AccountVerification(request, language=None, uidb64=None, verification_token=None):
if verification_token:
if not language:
if request.LANGUAGE_CODE == "fr":
return HttpResponseRedirect(f'/fr/verification/email/{uidb64}/{verification_token}/')
else:
return HttpResponseRedirect(f'/en/verification/email/{uidb64}/{verification_token}/')
id = force_text(urlsafe_base64_decode(uidb64))
user = api.charge_user_from_id(id)
try:
if not token_generator.check_token(user, verification_token):
logger.error(f"{get_first_part_log(request)} Link not valid anymore.")
if language == "fr":
messages.error(request, f"Le lien n'est plus valide.")
return HttpResponseRedirect("/fr/se-connecter/")
else:
messages.error(request, f"The link is not valid anymore.")
return HttpResponseRedirect("/en/login/")
if user.is_active:
logger.info(f"{get_first_part_log(request)} User already activated, redirect to login.")
if language == "fr":
return HttpResponseRedirect("/fr/se-connecter/")
else:
return HttpResponseRedirect("/en/login/")
user.is_active = True
user.is_email_validated = True
user.save()
logger.info(f"{get_first_part_log(request)} Charging email verification completed page.")
if language == "fr":
return render(request, "fr/authentication/email-verification-completed.html", {})
else:
return render(request, "en/authentication/email-verification-completed.html", {})
except:
logger.error(f"{get_first_part_log(request)} An error occurred.")
if language == "fr":
messages.error(request, f"Une erreur est survenue, contactez le support (support#linkimo.fr)")
return HttpResponseRedirect("/fr/se-connecter/")
else:
messages.error(request, f"An error occurred, please contact support (support#linkimo.fr)")
return HttpResponseRedirect("/en/login/")
else:
pass
My question is simple, how can I delete the token from record or make it invalid if the user already used it AND changed his password successfully ?
Thank you in advance for your help !
This doesn't fully answer your question as I don't think the tokens can be set as a one use only but you can reduce the number of seconds that the token is valid for in setting.py. The default is 3 days as per the below.
PASSWORD_RESET_TIMEOUT = 259200 # Default: 259200 (3 days, in seconds)
token_generator.check_token(user, verification_token)
if the timeout has elapsed the above would return false
i am making a django website with multiple forms also used foregin key(user_id) to link one form with other in the database but at the last i get value error the error is:Exception Type: ValueError
Exception Value:
The view Capp.views.InsertProduct didn't return an HttpResponse object. It returned None insteated ,
the following is view.py file code(not complete code but only where error can lie)models.py part
def InsertProduct(request):
if request.method == 'POST':
if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'):
saveproduct = ProInsert()
saveproduct.user_id = request.POST.get('user_id')
saveproduct.pname = request.POST.get('pname')
saveproduct.pcategory = request.POST.get('pcategory')
saveproduct.pdetails = request.POST.get('pdetails')
saveproduct.foundedin = request.POST.get('foundedin')
saveproduct.orderoftest = request.POST.get('orderoftest')
saveproduct.t1 = request.POST.get('t1')
saveproduct.t2 = request.POST.get('t2')
saveproduct.t3 = request.POST.get('t3')
saveproduct.f1 = request.POST.get('f1')
saveproduct.f2 = request.POST.get('f2')
saveproduct.f3 = request.POST.get('f3')
saveproduct.f4 = request.POST.get('f4')
saveproduct.f5 = request.POST.get('f5')
checkpname = ProInsert.objects.filter(
pname=saveproduct.pname).first()
return render(request, 'product_details.html')#here I had add what u said sir
if checkpname:
msgpname = messages.success(request, 'The user with Product Name ' +
request.POST['pname']+' already exist...!')
return render(request, 'product_details.html', {'msgpname': msgpname})
saveproduct.save()
messages.success(request, 'Product Added..!')
return render(request, 'product_details.html')
else:
return render(request, 'product_details.html')
I think you got it wrong I have update your code and commented the part i was telling you.
def InsertProduct(request):
if request.method == 'POST':
if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'):
saveproduct = ProInsert()
saveproduct.user_id = request.POST.get('user_id')
saveproduct.pname = request.POST.get('pname')
saveproduct.pcategory = request.POST.get('pcategory')
saveproduct.pdetails = request.POST.get('pdetails')
saveproduct.foundedin = request.POST.get('foundedin')
saveproduct.orderoftest = request.POST.get('orderoftest')
saveproduct.t1 = request.POST.get('t1')
saveproduct.t2 = request.POST.get('t2')
saveproduct.t3 = request.POST.get('t3')
saveproduct.f1 = request.POST.get('f1')
saveproduct.f2 = request.POST.get('f2')
saveproduct.f3 = request.POST.get('f3')
saveproduct.f4 = request.POST.get('f4')
saveproduct.f5 = request.POST.get('f5')
checkpname = ProInsert.objects.filter(
pname=saveproduct.pname).first()
# return render(request, 'product_details.html')# NO need to add here as code below will be dead in this case.
if checkpname:
msgpname = messages.success(request, 'The user with Product Name ' +
request.POST['pname']+' already exist...!')
return render(request, 'product_details.html', {'msgpname': msgpname})
saveproduct.save()
messages.success(request, 'Product Added..!')
return render(request, 'product_details.html')
else:
return render(request, 'product_details.html')# What i meant was to add it here
else:
return render(request, 'product_details.html')
I want to test this view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
#if True:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login /email are taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
And here is my part of my test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add anotheer user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEqual(response.context['code'],4)
And here is the error that I got:
,
in test_valid_credentials
self.assertEqual(response.context['code'],4)
TypeError: 'NoneType' object is not subscriptable
I tried it with get method and it works perfectly. Just with post it don't want to work.What am I doing wrong?Best regards
What is the response status? Redirects doesn't have context. Anyway, printing the response should help.
My guess is
key = register_user(login,email,password,newsletter)
throws an exception on duplicate register attempts and thus the handler does not generate a response.
I am trying to get a login form I have in django to only allow three login attempts before redirecting to a "login help" page. I am currently using the builtin "django.contrib.auth.views.login" view with a custom template. How do I force it to redirect to another page after n failed login attempts?
There's actually a project out there which provides a Django middleware to do just this, called django-axes. Simply install it with the instructions provided and then set AXES_LOGIN_FAILURE_LIMIT to the number of login attempts you want before a record is created for the failed logins. You'll still have to check this record when you want to lock someone out, however.
i use django-brake and memcached
#ratelimit(field='email', method='POST', rate='5/m')
#ratelimit(field='email', method='POST', rate='10/h')
#ratelimit(field='email', method='POST', rate='20/d')
def login_failure(request, login_form):
"""
Increment cache counters, 403 if over limit.
"""
was_limited = getattr(request, 'limited', False)
if was_limited:
limits = getattr(request, 'limits', [])
login_form.full_clean()
login_form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())\
.append('accout locked, try '+ str(limits[0]['period']) + ' seconds later')
return render(request, 'user/login.html', {'form': login_form})
def login(request):
if request.method == 'GET':
next = request.GET.get('next', '')
return render(request, 'user/login.html', {'next': next})
elif request.method == 'POST':
login_form = LoginForm(request.POST)
# check first
from brake.utils import get_limits
limits = get_limits(request, 'login_failure', 'email', [60, 3600, 86400])
if limits:
login_form.full_clean()
login_form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())\
.append('accout locked, try '+ str(limits[0]['period']) + ' seconds later')
return render(request, 'user/login.html', {'form': login_form})
if login_form.is_valid():
email = login_form.cleaned_data['email']
submit_pwd = login_form.cleaned_data['password']
user = authenticate(username=email, password=submit_pwd)
if user is None:
#
res = login_failure(request, login_form)
if res is None:
login_form._errors.setdefault(NON_FIELD_ERRORS, ErrorList()).append('password wrong')
res = render(request, 'user/login.html', {'form': login_form})
return res
...
login etc...
else:
...
You could save a session if the user has failed to login.
request.SESSION['login_tries'] = 1
and if they fail to login again
request.SESSioN['login_tries'] = 2
If the session becomes equal to the amount of login tries you want them tho have, then do something.