filter enabled items

This commit is contained in:
deflax 2017-06-26 17:31:30 +03:00
parent 1757a9b618
commit 500b12dd28
6 changed files with 77 additions and 117 deletions

View file

@ -75,32 +75,29 @@ def charge(user_pid=0):
@admin_required @admin_required
def dashboard(user_pid=0): def dashboard(user_pid=0):
cuser = User.query.filter_by(pid=user_pid).first() cuser = User.query.filter_by(pid=user_pid).first()
inv_deployments = cuser.inv_deployments.filter_by(enabled=True).order_by(Deployment.date_created.desc())
deployments = cuser.inv_deployments.order_by(Deployment.date_created.desc()).all()
inv_deploycubeids = [] inv_deploycubeids = []
inv_deploynames = [] inv_deployments_list = []
for invcls in deployments: for invcls in inv_deployments:
if invcls.user_id == cuser.pid and invcls.enabled == True: inv_deploycubeids.extend([invcls.machine_id])
inv_deploycubeids.extend([invcls.machine_id]) inv_deployments_list.extend([invcls.machine_alias])
inv_deploynames.extend([invcls.machine_alias])
services = cuser.inv_services.order_by(Service.date_created.desc()).all() inv_services = cuser.inv_services.filter_by(enabled=True).order_by(Service.date_last_charge.asc())
inv_services = [] inv_services_list = []
for invcls in services: for invcls in inv_services:
if invcls.user_id == cuser.pid and invcls.enabled == True: inv_services_list.extend([invcls.description])
inv_services.extend([invcls.description])
domains = cuser.inv_domains.order_by(Domain.date_created.desc()).all() inv_domains = cuser.inv_domains.filter_by(enabled=True).order_by(Domain.date_created.desc())
inv_domains = [] inv_domains_list = []
for invcls in domains: for invcls in inv_domains:
if invcls.user_id == cuser.pid and invcls.enabled == True: if invcls.user_id == cuser.pid and invcls.enabled == True:
inv_domains.extend([invcls.fqdn]) inv_domains_list.extend([invcls.fqdn])
addresses = cuser.inv_addresses.order_by(Address.ip.asc()).all() inv_addresses = cuser.inv_addresses.filter_by(enabled=True).order_by(Address.ip.asc())
inv_addresses = [] inv_addresses_list = []
for invcls in addresses: for invcls in inv_addresses:
if invcls.user_id == cuser.pid and invcls.enabled == True: if invcls.user_id == cuser.pid and invcls.enabled == True:
inv_addresses.extend([invcls.ip]) inv_addresses_list.extend([invcls.ip])
#extract rrd and status from the deployments #extract rrd and status from the deployments
rrd = {} rrd = {}
@ -124,8 +121,8 @@ def dashboard(user_pid=0):
flash('Deploy #{} unreachable. Support is notified'.format(str(cubeid))) flash('Deploy #{} unreachable. Support is notified'.format(str(cubeid)))
send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid), send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid),
'vmanager/email/adm_unreachable', user=cuser, cubeid=cubeid ) 'vmanager/email/adm_unreachable', user=cuser, cubeid=cubeid )
current_app.logger.info('[{}] deployments: {}, services: {}, domains: {}, services: {}'.format(cuser.email, inv_deploynames, inv_services, inv_domains, inv_addresses )) current_app.logger.info('[ADMIN] {} deployments: {}, services: {}, domains: {}, services: {}'.format(cuser.email, inv_deployments_list, inv_services_list, inv_domains_list, inv_addresses_list ))
return render_template('vmanager/dashboard.html', rrd=rrd, status=statuses, inv_deployments=deployments, inv_services=services, inv_domains=domains, inv_addresses=addresses) return render_template('vmanager/dashboard.html', rrd=rrd, status=statuses, inv_deployments=inv_deployments, inv_services=inv_services, inv_domains=inv_domains, inv_addresses=inv_addresses)
@admin.route("/listtransactions", methods=['GET']) @admin.route("/listtransactions", methods=['GET'])
@login_required @login_required

View file

@ -232,7 +232,7 @@ class Service(db.Model):
date_created = db.Column(db.DateTime, index=True, default=datetime.utcnow) date_created = db.Column(db.DateTime, index=True, default=datetime.utcnow)
date_last_charge = db.Column(db.DateTime) date_last_charge = db.Column(db.DateTime)
period = db.Column(db.Integer) period = db.Column(db.Integer)
enabled = db.Column(db.Boolean) enabled = db.Column(db.Boolean, default=False)
category = db.Column(db.String(64)) category = db.Column(db.String(64))
description = db.Column(db.Unicode(128)) description = db.Column(db.Unicode(128))
@ -320,7 +320,7 @@ class Address(db.Model):
class Domain(db.Model): class Domain(db.Model):
__tablename__ = 'domains' __tablename__ = 'domains'
pid = db.Column(db.Integer, primary_key=True) pid = db.Column(db.Integer, primary_key=True)
enabled = db.Column(db.Boolean) enabled = db.Column(db.Boolean, default=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.pid')) #FK user_id = db.Column(db.Integer, db.ForeignKey('users.pid')) #FK
date_created = db.Column(db.DateTime, index=True, default=datetime.utcnow) date_created = db.Column(db.DateTime, index=True, default=datetime.utcnow)

View file

@ -2,9 +2,9 @@
<div class="panel panel-warning" id="prxadmin"> <div class="panel panel-warning" id="prxadmin">
<div class="panel-heading">Admin Pages</div> <div class="panel-heading">Admin Pages</div>
<div class="panel-body"> <div class="panel-body">
<button class="btn btn-default" onclick="window.open('{{ url_for('admin.list_users') }}','_self')"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Users List</button> <button class="btn btn-default" onclick="window.open('{{ url_for('admin.list_users') }}','_self')"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Users</button>
<button class="btn btn-default" onclick="window.open('{{ url_for('admin.list_items') }}','_self')"><span class="glyphicon glyphicon-list" aria-hidden="true"></span> Items List</button> <button class="btn btn-default" onclick="window.open('{{ url_for('admin.list_items') }}','_self')"><span class="glyphicon glyphicon-list" aria-hidden="true"></span> Items</button>
<button class="btn btn-default" onclick="window.open('{{ url_for('admin.list_transactions') }}','_self')"><span class="glyphicon glyphicon-usd" aria-hidden="true"></span> Transaction List</button> <button class="btn btn-default" onclick="window.open('{{ url_for('admin.list_transactions') }}','_self')"><span class="glyphicon glyphicon-usd" aria-hidden="true"></span> Transactions</button>
</div> </div>
</div> </div>
</div> </div>

View file

@ -1,12 +1,17 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block page_content %} {% block page_content %}
<h1>Правила и Условия</h1>
<center>
<div class="row"> <div class="row">
<img src="../../static/images/datapoint.png" class="img-responsive"></img>
</div> <div class="col-md-12">
</center> <div class="panel panel-info" id="deployments">
<div class="panel-heading">Terms of Service</div>
<div class="panel-body"><p>
<center>
<img src="../../static/images/datapoint.png" class="img-responsive"></img>
</center>
<h1>Правила и Условия</h1>
<h3 class="h3_paa" style="text-align: left;"> I. ОСНОВНИ ДЕФИНИЦИИ:</h3> <h3 class="h3_paa" style="text-align: left;"> I. ОСНОВНИ ДЕФИНИЦИИ:</h3>
<p>Чл.1 (1) Информация съгласно Закона за електронната търговия и Закона за защита на потребителите:</p> <p>Чл.1 (1) Информация съгласно Закона за електронната търговия и Закона за защита на потребителите:</p>
@ -70,6 +75,10 @@
<p style="text-align: left;">Забранено е разпространението, съхранението или излагането на данни, материали или информация, които нарушават законите на Република България и/или законите на други държави. Това включва, но не се изчерпва с: материали, защитени от законите за авторски права; материали, които са заплашителни или нецензурни; материали, които са предназначени за лица над 18 години (&#8222;само за възрастни&#8220;); материали, защитени като фирмена тайна или с друг статут ограничаващ тяхното публично разпространение.</p> <p style="text-align: left;">Забранено е разпространението, съхранението или излагането на данни, материали или информация, които нарушават законите на Република България и/или законите на други държави. Това включва, но не се изчерпва с: материали, защитени от законите за авторски права; материали, които са заплашителни или нецензурни; материали, които са предназначени за лица над 18 години (&#8222;само за възрастни&#8220;); материали, защитени като фирмена тайна или с друг статут ограничаващ тяхното публично разпространение.</p>
<p style="text-align: left;">Потребителя се задължава да плати обезщетение и поеме вината при използване на услугите.</p> <p style="text-align: left;">Потребителя се задължава да плати обезщетение и поеме вината при използване на услугите.</p>
<p style="text-align: left;">Използването на услугите за нарушаване на защитени материали и търговски марки е забранено. Това включва, но не се изчерпва с неоторизирано копиране на музика, книги, снимки и всякакви други защитени продукти. Използването на акаунта за продаване на фалшификати на регистрирани търговски марки ще доведе до незабавното изтриване на потребителския акаунт. Ако се установи, че акаунта на потребителя нарушава други запазени права то достъпа до защитените материали ще бъде преустановен. Всеки потребителски акаунт хванат в повторно нарушение ще бъде спрян и/или изтрит от сървърите на доставчика. Ако смятате, че Вашите запазени права са нарушени може да пишете до доставчика на адрес с необходимата информация.</p> <p style="text-align: left;">Използването на услугите за нарушаване на защитени материали и търговски марки е забранено. Това включва, но не се изчерпва с неоторизирано копиране на музика, книги, снимки и всякакви други защитени продукти. Използването на акаунта за продаване на фалшификати на регистрирани търговски марки ще доведе до незабавното изтриване на потребителския акаунт. Ако се установи, че акаунта на потребителя нарушава други запазени права то достъпа до защитените материали ще бъде преустановен. Всеки потребителски акаунт хванат в повторно нарушение ще бъде спрян и/или изтрит от сървърите на доставчика. Ако смятате, че Вашите запазени права са нарушени може да пишете до доставчика на адрес с необходимата информация.</p>
</div>
</div>
</div>
</div> </div>
{% endblock %} {% endblock %}

View file

@ -123,31 +123,30 @@ def deploy(product_id=None):
@login_required @login_required
def dashboard(): def dashboard():
cuser = current_user cuser = current_user
deployments = cuser.inv_deployments.order_by(Deployment.date_created.desc()).all()
inv_deployments = cuser.inv_deployments.filter_by(enabled=True).order_by(Deployment.date_created.desc())
inv_deploycubeids = [] inv_deploycubeids = []
inv_deploynames = [] inv_deployments_list = []
for invcls in deployments: for invcls in inv_deployments:
if invcls.user_id == cuser.pid and invcls.enabled == True: inv_deploycubeids.extend([invcls.machine_id])
inv_deploycubeids.extend([invcls.machine_id]) inv_deployments_list.extend([invcls.machine_alias])
inv_deploynames.extend([invcls.machine_alias])
services = cuser.inv_services.order_by(Service.date_last_charge.asc()).all() inv_services = cuser.inv_services.filter_by(enabled=True).order_by(Service.date_last_charge.asc())
inv_services = [] inv_services_list = []
for invcls in services: for invcls in inv_services:
if invcls.user_id == cuser.pid and invcls.enabled == True: inv_services_list.extend([invcls.description])
inv_services.extend([invcls.description])
domains = cuser.inv_domains.order_by(Domain.date_created.desc()).all() inv_domains = cuser.inv_domains.filter_by(enabled=True).order_by(Domain.date_created.desc())
inv_domains = [] inv_domains_list = []
for invcls in domains: for invcls in inv_domains:
if invcls.user_id == cuser.pid and invcls.enabled == True: if invcls.user_id == cuser.pid and invcls.enabled == True:
inv_domains.extend([invcls.fqdn]) inv_domains_list.extend([invcls.fqdn])
addresses = cuser.inv_addresses.order_by(Address.ip.asc()).all() inv_addresses = cuser.inv_addresses.filter_by(enabled=True).order_by(Address.ip.asc())
inv_addresses = [] inv_addresses_list = []
for invcls in addresses: for invcls in inv_addresses:
if invcls.user_id == cuser.pid and invcls.enabled == True: if invcls.user_id == cuser.pid and invcls.enabled == True:
inv_addresses.extend([invcls.ip]) inv_addresses_list.extend([invcls.ip])
#extract rrd and status from the deployments #extract rrd and status from the deployments
rrd = {} rrd = {}
@ -174,41 +173,15 @@ def dashboard():
send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid), send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid),
'vmanager/email/adm_unreachable', user=current_user, cubeid=cubeid ) 'vmanager/email/adm_unreachable', user=current_user, cubeid=cubeid )
#current_app.logger.info('[{}] deployments: {}, services: {}, domains: {}, addresses: {}'.format(current_user.email, inv_deploynames, inv_services, inv_domains, inv_addresses )) current_app.logger.info('[{}] deployments: {}, services: {}, domains: {}, addresses: {}'.format(current_user.email, inv_deployments_list, inv_services_list, inv_domains_list, inv_addresses_list ))
current_app.logger.info('[{}] dashboard loaded.'.format(current_user.email)) return render_template('vmanager/dashboard.html', rrd=rrd, status=statuses, inv_deployments=inv_deployments, inv_services=inv_services, inv_domains=inv_domains, inv_addresses=inv_addresses)
return render_template('vmanager/dashboard.html', rrd=rrd, status=statuses, inv_deployments=deployments, inv_services=services, inv_domains=domains, inv_addresses=addresses)
@vmanager.route('/vmvnc/<int:vmid>')
@login_required
def vnc(vmid=0):
result = current_user.inv_deployments.order_by(Deployment.date_created.desc()).all()
inventory = []
for invcls in result:
if invcls.enabled == True:
inventory.extend([invcls.machine_id])
#checks if current user owns this vmid
if not vmid in inventory:
current_app.logger.warning('User does not own cube id: {}'.format(str(vmid)))
#TODO: log ips
else:
db_result = contact_proxmaster({}, 'vmvnc', vmid)
#return render_template('vmanager/vnc.html', url=db_result['url'])
return redirect(db_result['url'])
#admin override
if current_user.is_administrator():
current_app.logger.warning('Admin override for cube id: {}'.format(str(vmid)))
db_result = contact_proxmaster({}, 'vmvnc', vmid)
return redirect(db_result['url'])
abort(404)
valid_commands = ['vmstatus', 'vmstart', 'vmshutdown', 'vmstop']
@vmanager.route('/<cmd>/<int:vmid>') @vmanager.route('/<cmd>/<int:vmid>')
@login_required @login_required
def command(cmd=None, vmid=0): def command(cmd=None, vmid=0):
valid_commands = ['vmstatus', 'vmstart', 'vmshutdown', 'vmstop', 'vmvnc']
#checks whether this is a valid command #checks whether this is a valid command
if not cmd in valid_commands: if not cmd in valid_commands:
current_app.logger.warning(cmd + ' is not a valid command!') current_app.logger.warning(cmd + ' is not a valid command!')
@ -217,16 +190,14 @@ def command(cmd=None, vmid=0):
# flash('Недостатъчно средства в сметката за тази операция') # flash('Недостатъчно средства в сметката за тази операция')
# return redirect(url_for('uinvoice.addfunds')) # return redirect(url_for('uinvoice.addfunds'))
result = current_user.inv_deployments.order_by(Deployment.date_created.desc()).all() result = current_user.inv_deployments.filter_by(enabled=True).order_by(Deployment.date_created.desc())
inventory = [] inventory = []
for invcls in result: for invcls in result:
if invcls.enabled == True: inventory.extend([invcls.machine_id])
inventory.extend([invcls.machine_id])
#checks if current user owns this vmid #checks if current user owns this vmid
if not vmid in inventory: if not vmid in inventory:
current_app.logger.warning('user id: {} does not own cube id:{}'.format(current_user.pid, vmid)) current_app.logger.warning('[{}] Access violation with cube id: {}'.format(current_user.pid, vmid))
#TODO: log ips #TODO: log ips
else: else:
db_result = contact_proxmaster({}, cmd, vmid) db_result = contact_proxmaster({}, cmd, vmid)
@ -234,8 +205,11 @@ def command(cmd=None, vmid=0):
#admin override #admin override
if current_user.is_administrator(): if current_user.is_administrator():
current_app.logger.warning('Admin override for cube id:{}'.format(vmid)) current_app.logger.info('[ADMIN] Access override for cube id:{}'.format(vmid))
db_result = contact_proxmaster({}, cmd, vmid) db_result = contact_proxmaster({}, cmd, vmid)
if cmd == 'vmvnc':
return redirect(db_result['url'])
abort(404) abort(404)

View file

@ -33,35 +33,15 @@ def deploy():
Role.insert_roles() Role.insert_roles()
@manager.command @manager.command
def sampledata(): def charge():
"""Deploy Sample Data""" print('charge')
pass from app.models import Deployment, Service, Domain
#Deployment.charge()
def run_scheduler(): #Service.charge()
command_line = 'python3 /home/proxadmin/appserver/proxmaster-panel/schedulerd.py' #Domain.charge()
args = shlex.split(command_line)
p = subprocess.Popen(args)
@manager.command
def charge_deployments():
from app.models import Product, Deployment, User
Deployment.charge()
@manager.command
def charge_contracts():
from app.models import Service, Contract, User
Contract.charge()
@manager.command
def charge_domains():
from app.models import Domain, User
Domain.charge()
@manager.command @manager.command
def runserver(): def runserver():
#print('Starting Scheduler...')
#run_scheduler()
print('Starting Flask...') print('Starting Flask...')
app.run() app.run()