def admin(**args): t=args['t'] connection=args['connection'] user_admin=UserAdmin(connection) user_admin.fields['privileges'].name_form=SelectForm user_admin.create_forms(['username', 'password', 'email', 'privileges', 'lang']) user_admin.forms['privileges'].arr_select={0: I18n.lang('admin', 'without_privileges', 'Without privileges'), 1: I18n.lang('admin', 'selected_privileges', 'Selected privileges'), 2: I18n.lang('admin', 'administrator', 'Administrator')} user_admin.fields['password'].protected=False url=make_url('admin/ausers', {}) admin=GenerateAdminClass(user_admin, url, t) admin.list.fields_showed=['username', 'privileges'] admin.list.search_fields=['username'] admin.arr_fields_edit=['username', 'password', 'repeat_password', 'email', 'privileges', 'lang'] #admin.list.limit_pages=5 form_admin=admin.show() return form_admin
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} s=get_session() s['csrf_token']=create_key_encrypt() s.save() return {'token': 'Error: token is not valid', 'error': 1, 'csrf_token': s['csrf_token']}
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: s=get_session() s['csrf_token']=create_key_encrypt() s.save() return {'email': user_admin.fields['email'].txt_error, 'error': 1, 'csrf_token': s['csrf_token']} 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} return {'email': '', 'error': 0}
def register(): getpostfiles=GetPostFiles() connection=WebModel.connection() user_admin=UserAdmin(connection) user_admin.conditions=['WHERE privileges=%s', [2]] c=user_admin.select_count() if c==0: getpostfiles.obtain_post() getpostfiles.post['privileges']=2 user_admin.valid_fields=['username', 'email', 'password', 'privileges'] user_admin.create_forms() if user_admin.insert(getpostfiles.post, False): error= {'error': 0} return error else: user_admin.check_all_fields(getpostfiles.post, False) pass_values_to_form(getpostfiles.post, user_admin.forms, yes_error=True) s=get_session() s['csrf_token']=create_key_encrypt() error={'error': 1, 'csrf_token': s['csrf_token']} for field in user_admin.valid_fields: error[field]=user_admin.forms[field].txt_error error['repeat_password']=user_admin.forms['repeat_password'].txt_error #error['password_repeat']=I18n.lang('common', 'password_no_match', 'Passwords doesn\'t match') s.save() return error else: return {'error': 1}
def recovery_password(): t=PTemplate(env) connection=WebModel.connection() user_admin=UserAdmin(connection) post={} 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)
def home(module='', submodule=''): # A simple boolean used for show or not the code of admin module in standard template connection=WebModel.connection() #Fix, make local variable t=PTemplate(env) t.add_filter(make_admin_url) t.show_basic_template=True if submodule!='': module+='/'+submodule #t.clean_header_cache() #check if login user_admin=UserAdmin(connection) s=get_session() if check_login(): s['id']=s.get('id', 0) lang_selected=get_language(s) user_admin.set_conditions('WHERE id=%s', [s['id']]) # Check if user id exists in session c=user_admin.select_count() if c>0: if s['privileges']==2: #pass if module in menu: #Load module try: #new_module=import_module(menu[module][1]) #t.inject_folder=path.dirname(new_module.__file__).replace('/admin', '') #t.env=t.env_theme(path.dirname(__file__)) t.env.directories.insert(1, path.dirname(module_imported[module].__file__).replace('/admin', '')+'/templates') #print(t.env.directories) #if config.reloader: #reload(new_module) except ImportError: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) return "No exists admin module" #args={'t': t, 'connection': connection} content_index=module_imported[module].admin(t=t, connection=connection) if t.show_basic_template==True: return t.load_template('admin/content.html', title=menu[module][0], content_index=content_index, menu=menu, lang_selected=lang_selected, arr_i18n=I18n.dict_i18n) else: return content_index else: return t.load_template('admin/index.html', title=I18n.lang('admin', 'welcome_to_paramecio', 'Welcome to Paramecio Admin!!!'), menu=menu, lang_selected=lang_selected, arr_i18n=I18n.dict_i18n) else: logout() else: user_admin.conditions=['WHERE privileges=%s', [2]] c=user_admin.select_count() if c>0: if request.get_cookie("remember_login", secret=key_encrypt): #check login token_login=request.get_cookie("remember_login", secret=key_encrypt) user_admin.conditions=['WHERE token_login=%s', [token_login]] arr_user=user_admin.select_a_row_where(['id', 'privileges']) if arr_user==False: # delete cookioe response.delete_cookie("remember_login") else: s=get_session() s['id']=arr_user['id'] s['login']=1 s['privileges']=arr_user['privileges'] s.save() redirect(make_url(config.admin_folder)) else: post={} user_admin.yes_repeat_password=False user_admin.fields['password'].required=True user_admin.create_forms(['username', 'password']) forms=show_form(post, user_admin.forms, t, yes_error=False) #connection.close() return t.load_template('admin/login.phtml', forms=forms, yes_recovery_login=yes_recovery_login) else: post={} set_extra_forms_user(user_admin) forms=show_form(post, user_admin.forms, t, yes_error=False) return t.load_template('admin/register.phtml', forms=forms)
def login(): connection=WebModel.connection() user_admin=UserAdmin(connection) getpostfiles=GetPostFiles() getpostfiles.obtain_post() getpostfiles.post['username']=getpostfiles.post.get('username', '') getpostfiles.post['password']=getpostfiles.post.get('password', '') username=user_admin.fields['username'].check(getpostfiles.post['username']) password=getpostfiles.post['password'].strip() user_admin.conditions=['WHERE username=%s', [username]] arr_user=user_admin.select_a_row_where(['id', 'password', 'privileges', 'lang', 'num_tries']) if arr_user==False: s=get_session() s['csrf_token']=create_key_encrypt() s.save() return {'error': 1, 'csrf_token': s['csrf_token']} 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() s=get_session() s['id']=arr_user['id'] s['login']=1 s['privileges']=arr_user['privileges'] s['lang']=arr_user['lang'] if s['lang']=='': s['lang']=I18n.default_lang remember_login=getpostfiles.post.get('remember_login', '0') if remember_login=='1': timestamp=time()+315360000 random_text=create_key_encrypt() #Update user with autologin token user_admin.check_user=False user_admin.conditions=['WHERE username=%s', [username]] user_admin.valid_fields=['token_login'] user_admin.reset_require() if user_admin.update({'token_login': random_text}): response.set_cookie('remember_login', random_text, path="/", expires=timestamp, secret=key_encrypt) #else: #print(user_admin.query_error) s.save() 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}) s=get_session() s['csrf_token']=create_key_encrypt() s.save() return {'error': 1, 'csrf_token': s['csrf_token']} else: s=get_session() s['csrf_token']=create_key_encrypt() s.save() return {'error': 1, 'csrf_token': s['csrf_token']}
def start(): parser=argparse.ArgumentParser(prog='paramecio', description='A tool for create new paramecio sites') parser.add_argument('--path', help='The path where the paramecio site is located', required=True) parser.add_argument('--modules', help='A list separated by commas with the git repos for download modules for this site', required=False) parser.add_argument('--symlink', help='Set if create direct symlink to paramecio in new site', action='store_true') parser.add_argument('--tests', help='Create a symlink to tests for check into paramecio site', action='store_true') # Options for deploy parser.add_argument('--domain', help='The base domain for this site', required=True) parser.add_argument('--folder', help='If you deploy in a subdirectory, set it, without beggining and ending slashes', required=False) parser.add_argument('--port', help='If you deploy for production, set it to 80 value', required=False) parser.add_argument('--ssl', help='If the site use ssl, set it', action='store_true') args=parser.parse_args() #print(args) #exit(0) workdir=os.path.dirname(os.path.abspath(__file__)) # Create directory path=Path(args.path) try: path.mkdir(0o755, True) except: print('Error: cannot create the directory. Check if exists and if you have permissions') exit() # Create folder settings and copy index.py, admin.py path_settings=args.path+'/settings' try: os.mkdir(path_settings, 0o755) except: print('Error: cannot create the directory. Check if exists and if you have permissions') # Copy the files. Need optimization, use an array for save the filenames and a simple for loop. try: shutil.copy(workdir+'/settings/config.py.sample', path_settings+'/config.py') except: print('Error: cannot copy the file config.py. Check if exists and if you have permissions for this task') try: shutil.copy(workdir+'/frontend/index.py', args.path+'/index.py') except: print('Error: cannot copy the file index.py. Check if exists and if you have permissions for this task') try: shutil.copy(workdir+'/frontend/padmin.py', args.path+'/padmin.py') except: print('Error: cannot copy the file padmin.py. Check if exists and if you have permissions for this task') try: shutil.copy(workdir+'/frontend/i18nadmin.py', args.path+'/i18nadmin.py') except: print('Error: cannot copy the file i18nadmin.py. Check if exists and if you have permissions for this task') try: shutil.copy(workdir+'/frontend/regenerate.py', args.path+'/regenerate.py') except: print('Error: cannot copy the file regenerate.py. Check if exists and if you have permissions for this task') try: shutil.copy(workdir+'/frontend/create_module.py', args.path+'/create_module.py') except: print('Error: cannot copy the file create_module.py. Check if exists and if you have permissions for this task') try: shutil.copy(workdir+'/settings/modules.py', path_settings+'/modules.py') except: print('Error: cannot copy the file modules.py. Check if exists and if you have permissions for this task') if args.symlink==True: try: os.symlink(workdir, args.path+'/paramecio', True) except: print('Error: cannot symlink paramecio in new site') if args.tests==True: try: os.symlink(workdir, args.path+'/paramecio/', True) except: print('Error: cannot symlink paramecio in new site') with open(path_settings+'/config.py', 'r') as f: conf=f.read() random_bytes = os.urandom(24) secret_key_session = b64encode(random_bytes).decode('utf-8').strip() conf=conf.replace('im smoking fool', secret_key_session) #domain='localhost' conf=conf.replace("domain='localhost'", "domain='"+args.domain+"'") if args.port==None: args.port=':8080' elif args.port=='80': args.port='' else: args.port=':'+args.port if args.folder==None: args.folder='' else: args.folder='/'+args.folder arg_ssl='http' if args.ssl==True: arg_ssl='https' domain_url=arg_ssl+'://'+args.domain+args.port+args.folder conf=conf.replace("domain_url='http://localhost:8080'", "domain_url='"+domain_url+"'") #domain_url='http://localhost:8080' with open(path_settings+'/config.py', 'w') as f: f.write(conf) # Question about mysql configuration? If yes, install configuration s=input('Do you want use paramecio with MySQL database? y/n: ') if s=='y' or s=='Y': host_db=input('MySQL database server host, by default localhost: ').strip() db=input('MySQL database name, by default paramecio_db: ').strip() user_db=input('MySQL database user, by default root: ').strip() pass_db=getpass.getpass('MySQL database password, by default "": ').strip() if host_db=='': host_db='localhost' if user_db=='': user_db='root' #user=UserAdmin() #Create db if db=="": db='paramecio_db' WebModel.connections={'default': {'name': 'default', 'host': host_db, 'user': user_db, 'password': pass_db, 'db': '', 'charset': 'utf8mb4', 'set_connection': False} } connection_code="WebModel.connections={'default': {'name': 'default', 'host': '"+host_db+"', 'user': '******', 'password': '******', 'db': '"+db+"', 'charset': 'utf8mb4', 'set_connection': False} }" with open(path_settings+'/config.py', 'a') as f: f.write("\n\n"+connection_code) f.close() sql='create database '+db conn=WebModel.connection() useradmin=UserAdmin(conn) # Check if db exists c=0 with useradmin.query('SHOW DATABASES LIKE "%s"' % db) as cur: c=cur.rowcount if c==0: useradmin.query(sql) #print('Error: cannot create database or db doesn\'t exists, check database permissions for this user') #if not useradmin.query(sql): #print('Error: cannot create database, check the data of database') #else: useradmin.query('use '+db) admin=input('Do you want create admin site? y/n: ') if admin=='y' or admin=='Y': try: shutil.copy(workdir+'/settings/modules.py.admin', path_settings+'/modules.py') shutil.copy(workdir+'/settings/config_admin.py.sample', path_settings+'/config_admin.py') sql=useradmin.create_table() if not useradmin.query(sql): print('Error: cannot create table admin, you can create this table with padmin.py') else: # Add admin module to config with open(path_settings+'/config.py', 'r') as f: config_text=f.read() f.close() config_text=config_text.replace("modules=['paramecio.modules.welcome']", "modules=['paramecio.modules.welcome', 'paramecio.modules.admin', 'paramecio.modules.lang']") with open(path_settings+'/config.py', 'w') as f: f.write(config_text) f.close() try: shutil.copy(workdir+'/settings/modules.py.admin', path_settings+'/modules.py') except: print('Error: cannot copy the file modules.py. Check if exists and if you have permissions for this task') print('Created admin site...') except: print('Error: cannot create the database. Check if tables exists in it and if you have permissions for this task') exit(1) pass # Install modules if args.modules!=None: if args.modules.strip()!='': arr_modules=args.modules.split(',') final_modules=[] final_modules_models=[] if len(arr_modules)>0: for k, module in enumerate(arr_modules): module=module.strip() try: u=urlparse(module) module_path=os.path.basename(u.path) except: print('Error: not valid url for repository') exit(1) if call("git clone %s %s/modules/%s" % (module, path, module_path), shell=True) > 0: print('Error, cannot install the module %s' % module_path) exit(1) else: print('Added module %s' % module_path) final_modules.append(("modules/%s" % (module_path)).replace('/', '.')) final_modules_models.append("modules/%s" % (module_path)) # Edit config.py with open(path_settings+'/config.py') as f: modules_final='\''+'\', \''.join(final_modules)+'\'' p=re.compile(r"^modules=\[(.*)\]$") #config_file=p.sub(r"modules=[\1, "+modules_final+"]", "modules=['paramecio.modules.welcome', 'paramecio.modules.admin', 'paramecio.modules.lang', 'modules.pastafari', 'modules.monit', 'modules.example']") final_config='' for line in f: if p.match(line): line=p.sub(r"modules=[\1, "+modules_final+"]", line) final_config+=line with open(path_settings+'/config.py', 'w') as f: f.write(final_config) print('Updated configuration for add new modules...') #Change workdir real_dir=os.getcwd() os.chdir(args.path) #Regenerating modules.py regenerate='regenerate.py' os.chmod(regenerate, 0o755) if call('./regenerate.py', shell=True) > 0: print('Error, cannot regenerate the modules.py script') exit(1) else: print('Regeneration of modules.py finished') # Installing models padmin='padmin.py' os.chmod(padmin, 0o755) for mod_path in final_modules_models: models_path=mod_path+'/models' if os.path.isdir(models_path): models_files=os.listdir(models_path) m=re.compile(".*\.py$") underscore=re.compile("^__.*") for f in models_files: if m.match(f) and not underscore.match(f): if call('./padmin.py --model '+models_path+'/'+f, shell=True) > 0: print('Error, cannot create the modules of '+models_path+'/'+f) else: print('Models from '+models_path+'/'+f+' created') # Execute two times the loop because i can need good installed models for postscript script # Execute postscript print('Executing postscripts') for mod_path in final_modules_models: postscript=mod_path+"/install/postinstall.py" os.chmod(padmin, 0o755) if os.path.isfile(postscript): os.chmod(postscript, 0o755) if call('./'+postscript, shell=True) > 0: print('Error, cannot execute the postinstall script') exit(1) else: print('Postinstall script finished')