Added support for protect and recovery accounts

This commit is contained in:
Antonio de la Rosa 2016-06-21 04:59:30 +02:00
parent 5c1a8855bb
commit 98e9820161
12 changed files with 366 additions and 57 deletions

View file

@ -22,11 +22,10 @@ class SendMail:
ssl=True
txt_error=''
def __init__(self):
self.smtp=smtplib.SMTP(host=self.host, port=self.port)
self.txt_error=''
def send(self, from_address, to_address, subject, message, content_type='plain', attachments=[]):
@ -168,3 +167,6 @@ class SendMail:
self.smtp.quit()
def __del__(self):
self.quit()

View file

@ -15,7 +15,8 @@ class LangField(CharField):
for lang in I18n.dict_i18n:
select_lang[lang]=lang
self.change_form(coreforms.SelectForm, [select_lang, I18n.default_lang])
self.change_form(coreforms.SelectForm, [select_lang])
self.default_value=I18n.default_lang
def check(self, value):

View file

@ -59,7 +59,7 @@ class CheckForm():
return post, arr_form
def show_form(post, arr_form, t, yes_error=True, modelform_tpl='forms/modelform.phtml'):
def show_form(post, arr_form, t, yes_error=True, pass_values=True, modelform_tpl='forms/modelform.phtml'):
# Create csrf_token in session
@ -67,7 +67,7 @@ def show_form(post, arr_form, t, yes_error=True, modelform_tpl='forms/modelform.
s['csrf_token']=create_key_encrypt()
if yes_error==True:
if pass_values==True:
pass_values_to_form(post, arr_form, yes_error)
return t.load_template(modelform_tpl, forms=arr_form)

View file

@ -144,6 +144,7 @@ class UserModel(WebModel):
self.conditions=original_conditions
if error>0:
self.sql_error+='Error:if is not expected, please, check that you disabled the special checkings of this model'
return False
return fields, values, update_values

View file

@ -7,6 +7,7 @@ from importlib import import_module, reload
from collections import OrderedDict
from paramecio.cromosoma.databases.mysqldb import SqlClass
from paramecio.cromosoma.coreforms import BaseForm, HiddenForm
import traceback
# The most important class for the framework
#
@ -249,6 +250,9 @@ class WebModel:
fields, values, update_values=self.check_all_fields(dict_values, external_agent, True, 'update')
except:
#self.query_error+="\n"+traceback.format_exc()
return False
sql="update `"+self.name+"` SET "+", ".join(update_values)+" "+self.conditions[0]
@ -732,7 +736,7 @@ class WebModel:
value=dict_values[k]
# Need rewrite the error because shitty python don't clean nothing
# Cleaning the error
self.fields[k].error=False

View file

@ -20,13 +20,23 @@ from importlib import import_module, reload
from bottle import redirect
from collections import OrderedDict
from time import time
from paramecio.citoplasma.keyutils import create_key_encrypt
from paramecio.citoplasma.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
from paramecio.citoplasma.sendmail import SendMail
from os import path
import copy
#from citoplasma.login import LoginClass
# Check login
yes_recovery_login=False
email_address='localhost'
if hasattr(config, 'yes_recovery_login'):
yes_recovery_login=config.yes_recovery_login
if hasattr(config, 'email_address'):
email_address=config.email_address
load_lang(['paramecio', 'admin'], ['paramecio', 'common'])
key_encrypt=config.key_encrypt #create_key_encrypt()
@ -175,7 +185,7 @@ def home(module='', submodule=''):
#connection.close()
return t.load_template('admin/login.phtml', forms=forms)
return t.load_template('admin/login.phtml', forms=forms, yes_recovery_login=yes_recovery_login)
else:
@ -207,13 +217,17 @@ def login():
user_admin.conditions=['WHERE username=%s', [username]]
arr_user=user_admin.select_a_row_where(['id', 'password', 'privileges', 'lang'])
arr_user=user_admin.select_a_row_where(['id', 'password', 'privileges', 'lang', 'num_tries'])
if arr_user==False:
return {'error': 1}
else:
num_tries=int(arr_user['num_tries'])
if arr_user['num_tries']<3:
if user_admin.fields['password'].verify(password, arr_user['password']):
generate_session()
@ -255,6 +269,19 @@ def login():
return {'error': 0}
else:
user_admin.check_user=False
user_admin.conditions=['WHERE username=%s', [username]]
user_admin.valid_fields=['num_tries']
user_admin.reset_require()
user_admin.update({'num_tries': arr_user['num_tries']+1})
return {'error': 1}
else:
return {'error': 1}
@ -330,24 +357,127 @@ def logout():
redirect('/'+config.admin_folder)
"""
def set_extra_forms_user(user_admin):
@get('/'+config.admin_folder+'/recovery_password')
def recovery_password():
user_admin.fields['password'].required=True
user_admin.fields['email'].required=True
t=PTemplate(env)
user_admin.create_forms(['username', 'email', 'password'])
connection=WebModel.connection()
user_admin.forms['repeat_password']=PasswordForm('repeat_password', '')
user_admin=UserAdmin(connection)
user_admin.forms['repeat_password'].required=1
post={}
user_admin.forms['repeat_password'].label=I18n.lang('common', 'repeat_password', 'Repeat Password')
"""
user_admin.create_forms(['email'])
forms=show_form(post, user_admin.forms, t, yes_error=False)
#connection.close()
return t.load_template('admin/recovery.phtml', forms=forms)
@post('/'+config.admin_folder+'/recovery_password')
def send_password():
connection=WebModel.connection()
user_admin=UserAdmin(connection)
t=PTemplate(env)
getpost=GetPostFiles()
getpost.obtain_post()
email=getpost.post.get('email', '')
email=user_admin.fields['email'].check(email)
if user_admin.fields['email'].error:
return {'email': user_admin.fields['email'].txt_error, 'error': 1}
else:
user_admin.set_conditions('WHERE email=%s', [email])
user_admin.yes_reset_conditions=False
if user_admin.select_count()==1:
user_admin.reset_require()
user_admin.valid_fields=['token_recovery']
user_admin.check_user=False
token=create_key_encrypt_256()
if user_admin.update({'token_recovery': token}):
send_mail=SendMail()
content_mail=t.load_template('admin/recovery_mail.phtml', token=token)
if not send_mail.send(email_address, [email], I18n.lang('admin', 'send_email', 'Email for recovery your password'), content_mail):
return {'email': 'Error: i cannot send mail', 'error': 1}
"""user_admin.create_forms()
return {'email': '', 'error': 0}
users=user_admin.select()"""
#By default id is not showed
@get('/'+config.admin_folder+'/check_token')
def check_token():
t=PTemplate(env)
return t.load_template('admin/check_token.phtml')
@post('/'+config.admin_folder+'/check_token')
def check_code_token():
t=PTemplate(env)
if yes_recovery_login==True:
getpost=GetPostFiles()
getpost.obtain_post()
connection=WebModel.connection()
user_admin=UserAdmin(connection)
token=getpost.post.get('token', '')
token=user_admin.fields['token_recovery'].check(token)
if token.strip()!='':
user_admin.set_conditions('WHERE token_recovery=%s', [token])
user_admin.yes_reset_conditions=False
arr_user=user_admin.select_a_row_where(['id', 'email'])
if arr_user:
new_password=create_key()
user_admin.valid_fields=['password', 'token_recovery', 'num_tries']
user_admin.reset_require()
user_admin.check_user=False
if user_admin.update({'password': new_password, 'token_recovery': "", 'num_tries': 0}, False):
send_mail=SendMail()
content_mail=t.load_template('admin/recovery_password.phtml', password=new_password)
if not send_mail.send(email_address, [arr_user['email']], I18n.lang('admin', 'send_password_email', 'Your new password'), content_mail):
return {'token': 'Error: i cannot send mail', 'error': 1}
return {'token': 'Error: cannot send the maild with the new password', 'error': 0}
return {'token': 'Error: token is not valid', 'error': 1}

View file

@ -50,6 +50,10 @@ class UserAdmin(UserModel):
self.register(LangField('lang', 20))
self.register(corefields.BooleanField('disabled'))
self.register(corefields.IntegerField('num_tries', 1))
"""
user_admin=WebModel('user_admin')

View file

@ -0,0 +1,75 @@
<%inherit file="login.phtml"/>
<%block name="ajax">
<script language="Javascript">
$(document).ready( function () {
$("#register_submit").click( function () {
$('#loading').show();
$('#result_register').html('Checking the code...');
$.ajax({
url: "${make_url('admin/check_token')}",
method: "POST",
dataType: "json",
data: {'token': $('#token_form').val()}
}).done(function(data) {
//$( this ).addClass( "done" );
//Redirect if register
if(data.error==0)
{
$('#result_register').html('Sucess!!!. Redirecting to login');
setTimeout(function () {
window.location.href="${make_url('admin/login')}";
}, 5000);
//window.location.href="${make_url('admin/login')}";
}
else
{
//alert(JSON.stringify(data));
//$('#result_register').html('Error');
$('#token_error').html(data.token);
$('#loading').hide();
$('#result_register').html('');
}
}).fail(function(data) {
alert(JSON.stringify(data));
});
return false;
});
});
</script>
</%block>
<%block name="title">${lang('common', 'recovery_password', 'Recovery password')}</%block>
<%block name="content">
<form id="login">
<div id="title">
${lang('common', 'recovery_password', 'Recovery password')}
</div>
<div class="form">
<label>Put your email code</label>
<input type="text" name="token" value="" id="token_form"/>
<span class="error" id="token_error"></span>
</div>
<div id="result_register" class="form"></div>
<div id="submit_block">
<input type="submit" value="${lang('common', 'recovery_password', 'Recovery password')}" class="submit" id="register_submit"/>
<span id="loading">&nbsp;</span>
</div>
</form>
</%block>

View file

@ -64,11 +64,17 @@
${lang('admin', 'login', 'Paramecio Login')}
</div>
${forms|n}
<div class="form">${lang('admin', 'remember_login', 'Remember login?')} <input type="checkbox" id="remember_login" name="remember_login" value="1"></div>
<div class="form">
${lang('admin', 'remember_login', 'Remember login?')} <input type="checkbox" id="remember_login" name="remember_login" value="1">
</div>
<div id="submit_block">
<input type="submit" value="${lang('common', 'login', 'Login')}" class="submit" id="login_submit"/>
<span id="loading">&nbsp;</span>
</div>
% if yes_recovery_login:
<div class="form"><a href="${make_url('admin/recovery_password')}">${lang('admin', 'recovery_password', 'Recovery password?')}</a></div>
% endif
<div class="form">${lang('admin', 'remember_tries', 'Remember that only have 3 attempts')}</div>
</form>
</%block>
</body>

View file

@ -0,0 +1,66 @@
<%inherit file="login.phtml"/>
<%block name="ajax">
<script language="Javascript">
$(document).ready( function () {
$("#register_submit").click( function () {
$('#loading').show();
$('#result_register').html('Sending an email to your email account');
$.ajax({
url: "${make_url('admin/recovery_password')}",
method: "POST",
dataType: "json",
data: {'email': $('#email_form').val()}
}).done(function(data) {
//$( this ).addClass( "done" );
//Redirect if register
if(data.error==0)
{
$('#result_register').html('Redirecting to recovery password zone');
setTimeout(function () {
window.location.href="${make_url('admin/check_token')}";
}, 5000);
//window.location.href="${make_url('admin/login')}";
}
else
{
//alert(JSON.stringify(data));
//$('#result_register').html('Error');
$('#email_error').html(data.email);
}
});
return false;
});
});
</script>
</%block>
<%block name="title">${lang('common', 'recovery_password', 'Recovery password')}</%block>
<%block name="content">
<form id="login">
<div id="title">
${lang('common', 'recovery_password', 'Recovery password')}
</div>
${forms|n}
<div id="result_register" class="form"></div>
<div id="submit_block">
<input type="submit" value="${lang('common', 'recovery_password', 'Recovery password')}" class="submit" id="register_submit"/>
<span id="loading">&nbsp;</span>
</div>
</form>
</%block>

View file

@ -0,0 +1,10 @@
Hi User
You send a request for get a new password
Please, copy and paste the next code in your browser for complete the request:
${token}
If you don't send any request for get a new password, ignore this mail.

View file

@ -0,0 +1,10 @@
Hi User
You send a request for get a new password
Your new password is ${password}
Thanks!!!