Commit 7dcc292e authored by Vladislav Rykov's avatar Vladislav Rykov
Browse files

implementing privilege system

parent 05dcf3a5
...@@ -46,6 +46,18 @@ def update_password(cur, name, password): ...@@ -46,6 +46,18 @@ def update_password(cur, name, password):
cur.execute(query, (bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf-8'), name)) cur.execute(query, (bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf-8'), name))
return (True,) return (True,)
@with_psql
def update_role(cur, name, role):
query = """
UPDATE users SET
role = %s
WHERE
name = %s
"""
cur.execute(query, (role,name))
return (True,)
@with_psql @with_psql
def get(cur, name): def get(cur, name):
query = """ query = """
......
...@@ -107,7 +107,6 @@ def mpack_test(cur): ...@@ -107,7 +107,6 @@ def mpack_test(cur):
query = """ query = """
INSERT INTO dev_3b56f3d8_3 VALUES ({}, '{}', {}) INSERT INTO dev_3b56f3d8_3 VALUES ({}, '{}', {})
""".format(misc.get_utc(), datetime.now().strftime('%H:%M:%S'), Binary(m)) """.format(misc.get_utc(), datetime.now().strftime('%H:%M:%S'), Binary(m))
print (query)
cur.execute(query) cur.execute(query)
return (True,) return (True,)
......
...@@ -11,6 +11,27 @@ import collections ...@@ -11,6 +11,27 @@ import collections
import json import json
USER_LEVELS = {
# user can only see applications and devices as interface.
'interface' : 0,
# user has the control over all user aspects. CRUD:applications+devices+alarms+automation + device configuration and data download
'user' : 40,
# + CRUD:user expect admins
'admin' : 80,
# total control (1 superuser per platform)
'superuser' : 100
}
@app.context_processor
def get_user_levels():
return dict(user_levels=USER_LEVELS)
@app.context_processor
def grant_view():
def check(require, wants):
return USER_LEVELS[require] <= USER_LEVELS[wants]
return dict(grant=check)
def rand_str(length): def rand_str(length):
if length % 2 == 0: if length % 2 == 0:
return hexlify(os.urandom(length//2)) return hexlify(os.urandom(length//2))
...@@ -86,25 +107,16 @@ def restricted(access_level): ...@@ -86,25 +107,16 @@ def restricted(access_level):
def user_control(f): def user_control(f):
@wraps(f) @wraps(f)
def decorated_function(*args, **kwargs): def decorated_function(*args, **kwargs):
if 'role' in session and session['role'] != access_level: if 'role' in session:
flash('Access denied.', 'danger') if USER_LEVELS[access_level] > USER_LEVELS[session['role']]:
return redirect(url_for('index')) flash('Access denied.', 'danger')
return f(*args, **kwargs) return redirect(url_for('index'))
return f(*args, **kwargs)
return redirect(url_for('login'))
return decorated_function return decorated_function
return user_control return user_control
def required_privilege(privilege):
def privilege_control(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'privilege' in session and session['privilege'] < privilege:
flash('Access denied.', 'danger')
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
return privilege_control
def clean_data_folder(): def clean_data_folder():
try: try:
filelist = [f for f in os.listdir(app.config['DATA_DOWNLOAD_DIR_OS'])] filelist = [f for f in os.listdir(app.config['DATA_DOWNLOAD_DIR_OS'])]
......
...@@ -92,7 +92,7 @@ ...@@ -92,7 +92,7 @@
<i class="ni ni-air-baloon text-yellow"></i> Applications <i class="ni ni-air-baloon text-yellow"></i> Applications
</a> </a>
</li> </li>
{% if session['role'] == 'admin' %} {% if get_user_levels() %}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link " href="/administration"> <a class="nav-link " href="/administration">
<i class="ni ni-briefcase-24 text-pink"></i> Administration <i class="ni ni-briefcase-24 text-pink"></i> Administration
......
...@@ -22,24 +22,26 @@ ...@@ -22,24 +22,26 @@
<form action="/administration/users/new-user" method="post"> <form action="/administration/users/new-user" method="post">
<div class="form-group"> <div class="form-group">
<label>Name:</label><br> <label>Name:</label><br>
<input type="text" maxlength="30" class="form-control" id="username" name="username" required><br> <input type="text" maxlength="30" class="form-control" id="username" name="username" required>
</div> </div>
<div class="form-group">
<label>Password:</label><br>
<input class="form-control" placeholder="Password" type="password" minlength="8" id="password" name="password" onkeyup="return validate_password();">
<br>
<input class="form-control" placeholder="Repeat password" type="password" minlength="8" id="rpassword" name="rpassword" onkeyup="return validate_password();">
</div>
<div class="text-muted font-italic"><small>Required password strength: <span class="text-success font-weight-700">At least 8 characters.</span></small></div>
<div class="text-muted font-italic"><small id="passvalidation"></small></div>
<br> <br>
<div class="form-group"> <div class="form-group">
<label for="role"> Role: </label> <label for="role"> Role: </label>
<select class="form-control" id="role" name="role"> <select class="form-control" id="role" name="role">
<option> interface </option>
<option> user </option> <option> user </option>
<option> admin </option> <option> admin </option>
</select> </select>
</div> </div>
<br>
<div class="form-group">
<label>Password:</label><br>
<input class="form-control" placeholder="Password" type="password" minlength="8" id="password" name="password" onkeyup="return validate_password();">
<br>
<input class="form-control" placeholder="Repeat password" type="password" minlength="8" id="rpassword" name="rpassword" onkeyup="return validate_password();">
</div>
<div class="text-muted font-italic"><small>Required password strength: <span class="text-success font-weight-700">At least 8 characters.</span></small></div>
<div class="text-muted font-italic"><small id="passvalidation"></small></div>
<br><br> <br><br>
<div class="form-group"> <div class="form-group">
<button type="submit" class="btn btn-primary">Create User</button> <button type="submit" class="btn btn-primary">Create User</button>
......
...@@ -81,10 +81,10 @@ ...@@ -81,10 +81,10 @@
</div> </div>
</div> </div>
</div> </div>
{% if data %} {% if total > 0 %}
<div> <div>
<ul class="nav nav-pills" id="pills-tab" role="tablist"> <ul class="nav nav-pills" id="pills-tab" role="tablist">
{% for k in data[0][2] %} {% for k in dev[3]['format'] %}
<li class="nav-item col-lg-3 col-md-6" role="presentation"> <li class="nav-item col-lg-3 col-md-6" role="presentation">
<a class="nav-link" id="tab_{{ k }}" data-toggle="pill" href="#{{ k }}" role="tab" aria-controls="{{ k }}" aria-selected="true" onclick="display_data('{{ k }}')">{{ k }}</a> <a class="nav-link" id="tab_{{ k }}" data-toggle="pill" href="#{{ k }}" role="tab" aria-controls="{{ k }}" aria-selected="true" onclick="display_data('{{ k }}')">{{ k }}</a>
</li> </li>
...@@ -92,7 +92,7 @@ ...@@ -92,7 +92,7 @@
</ul> </ul>
<div class="tab-content" id="pills-tabContent"> <div class="tab-content" id="pills-tabContent">
{% for k in data[0][2] %} {% for k in dev[3]['format'] %}
<div class="tab-pane fade card" id="{{ k }}" style="margin-top: 30px;" role="tabpanel" aria-labelledby="tab_{{ k }}"> <div class="tab-pane fade card" id="{{ k }}" style="margin-top: 30px;" role="tabpanel" aria-labelledby="tab_{{ k }}">
<div class="card-body"> <div class="card-body">
<h3 class="mb-0 card-header">Last 24 hours data</h3> <h3 class="mb-0 card-header">Last 24 hours data</h3>
...@@ -108,7 +108,9 @@ ...@@ -108,7 +108,9 @@
<tbody id="table_{{ k }}_body"> <tbody id="table_{{ k }}_body">
</tbody> </tbody>
</table> </table>
<center><a href="javascript:void(0);" onclick="return table_load_more('{{ k }}');">Load more</a></center> {% if total > table_max %}
<center><a href="javascript:void(0);" id="table_load_more" onclick="return table_load_more('{{ k }}');">Load more</a></center>
{% endif %}
</div> </div>
</div> </div>
{% endfor %} {% endfor %}
...@@ -139,7 +141,7 @@ ...@@ -139,7 +141,7 @@
{% endblock %} {% endblock %}
{% block script %} {% block script %}
{% if data %} {% if total > 0 %}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
google.charts.load('current', {'packages':['corechart']}); google.charts.load('current', {'packages':['corechart']});
...@@ -147,7 +149,7 @@ ...@@ -147,7 +149,7 @@
function init_scroll() { function init_scroll() {
var ts = { var ts = {
{% for k in data[0][2] %} {% for k in dev[3]['format'] %}
{{ k }} : 1, {{ k }} : 1,
{% endfor %} {% endfor %}
}; };
...@@ -163,7 +165,7 @@ ...@@ -163,7 +165,7 @@
title: '{{ dev[0] }} > '+dname, title: '{{ dev[0] }} > '+dname,
curveType: 'function', curveType: 'function',
hAxis: { hAxis: {
format: 'dd/MM hh:mm' format: 'dd/MM HH:mm'
}, },
vAxis: { vAxis: {
format: 'decimal', format: 'decimal',
...@@ -193,13 +195,20 @@ ...@@ -193,13 +195,20 @@
} }
function show_first_page() { function show_first_page() {
document.getElementById("tab_{{ data[0][2] | first }}").click(); document.getElementById("tab_{{ dev[3]['format'] | first }}").click();
} }
function table_load_more(dname) { function table_load_more(dname) {
tscroll[dname] += 1; tscroll[dname] += 1;
fetch('/administration/users/{{ user }}/application/{{ app[1] }}/device/{{ dev[1] }}/data/'+dname+'/table/'+tscroll[dname]).then(res => res.text()).then(data => $('#table_'+dname+'_body').append(data)); fetch('/administration/users/{{ user }}/application/{{ app[1] }}/device/{{ dev[1] }}/data/'+dname+'/table/'+tscroll[dname]).then(res => res.text()).then(function(data)
fetch('/administration/users/{{ user }}/application/{{ app[1] }}/device/{{ dev[1] }}/data/'+dname+'/table/'+tscroll[dname]).then(res => res.text()).then(data => console.log(data)); {
if (data.length > 0) {
$("#table_"+dname+"_body").append(data);
} else {
$("#table_load_more").remove();
}
}
);
} }
</script> </script>
{% endif %} {% endif %}
......
...@@ -26,10 +26,25 @@ ...@@ -26,10 +26,25 @@
<form action="/administration/users/{{ user }}/settings" method="post" id="settings"> <form action="/administration/users/{{ user }}/settings" method="post" id="settings">
<div class="form-group"> <div class="form-group">
<label>Name:</label><br> <label>Name:</label><br>
<input type="text" maxlength="30" class="form-control" id="name" name="name" value="{{ user }}" style="pointer-events: none;"><br> <input type="text" maxlength="30" class="form-control" id="name" name="name" value="{{ user }}" style="pointer-events: none;">
</div> </div>
<br> <br>
<div class="form-group"> <div class="form-group">
<label for="role"> Role: </label>
<select class="form-control" id="role" name="role">
{% set roles = ['interface', 'user', 'admin'] %}
{% for r in roles %}
{% if r == user_role %}
<option selected="selected"> {{ r }} </option>
{% else %}
<option> {{ r }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<br>
<div class="form-group">
<label> Change password: </label>
<div class="input-group input-group-alternative"> <div class="input-group input-group-alternative">
<div class="input-group-prepend"> <div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-lock-circle-open"></i></span> <span class="input-group-text"><i class="ni ni-lock-circle-open"></i></span>
......
...@@ -82,19 +82,19 @@ ...@@ -82,19 +82,19 @@
<thead> <thead>
<th> Name </th> <th> Name </th>
<th> Role </th> <th> Role </th>
<th> Privilege Level </th>
</thead> </thead>
<tbody id="users_body"> <tbody id="users_body">
{% for u in users %} {% for u in users %}
<tr onclick="window.location='/administration/users/{{ u[0] }}';"> <tr onclick="window.location='/administration/users/{{ u[0] }}';">
<th> {{ u[0] }} </th> <th> {{ u[0] }} </th>
<th> {{ u[2] }} </th> <th> {{ u[2] }} </th>
<th> {{ u[3] }} </th>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
<center><a href="javascript:void(0);" onclick="return table_load_more();">Load more</a></center> {% if users|length > 10 %}
<center><a href="javascript:void(0);" id="table_load_more" onclick="return table_load_more();">Load more</a></center>
{% endif %}
{% endif %} {% endif %}
</div> </div>
<div class="card-body"> <div class="card-body">
...@@ -131,12 +131,16 @@ ...@@ -131,12 +131,16 @@
url:"/administration/users/table/"+next_page+"?name="+$("#filter_name").val(), url:"/administration/users/table/"+next_page+"?name="+$("#filter_name").val(),
type:"get", type:"get",
success: function(data) { success: function(data) {
data = eval(data); if (data.length == 0) {
data.forEach(function (entry) { $("#table_load_more").remove();
str = "<tr onclick=window.location=\"/administration/users/"+entry[0]+"\"><th>"+entry[0]+"</th>"+"<th>"+entry[1]+"</th></tr>"; else {
$("#users_body").append(unescape(str)); data = eval(data);
}); data.forEach(function (entry) {
next_page++; str = "<tr onclick=window.location=\"/administration/users/"+entry[0]+"\"><th>"+entry[0]+"</th>"+"<th>"+entry[1]+"</th></tr>";
$("#users_body").append(unescape(str));
});
next_page++;
}
} }
}); });
} }
......
...@@ -28,18 +28,16 @@ MAX_PG_ENTRIES_DATA = 10 ...@@ -28,18 +28,16 @@ MAX_PG_ENTRIES_DATA = 10
MAX_PG_ENTRIES_GRAPH_HOURS = 24 MAX_PG_ENTRIES_GRAPH_HOURS = 24
@misc.restricted('interface')
@app.route('/') @app.route('/')
def index(): def index():
if 'name' in session and len(session['name']) > 0: created_apps = ad.get_count_by_user(session['name'])[1][0]
created_apps = ad.get_count_by_user(session['name'])[1][0] active_devices = dd.get_count_by_user(session['name'])
active_devices = dd.get_count_by_user(session['name']) total_activity = md.get_user_data_count(session['name'])[1][0]
total_activity = md.get_user_data_count(session['name'])[1][0] last_activity = md.get_user_data_count_per_day(session['name'])[1][0]
last_activity = md.get_user_data_count_per_day(session['name'])[1][0] info = [created_apps, active_devices, total_activity, last_activity]
info = [created_apps, active_devices, total_activity, last_activity]
return render_template('new/public/dashboard.html', info=info)
return render_template('new/public/dashboard.html', info=info)
else:
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST']) @app.route('/register', methods=['GET', 'POST'])
...@@ -89,7 +87,6 @@ def login(): ...@@ -89,7 +87,6 @@ def login():
else: else:
session['name'] = username session['name'] = username
session['role'] = res[1][2] session['role'] = res[1][2]
session['privilege'] = res[1][3]
return redirect(url_for('index')) return redirect(url_for('index'))
...@@ -100,328 +97,287 @@ def logout(): ...@@ -100,328 +97,287 @@ def logout():
return redirect(url_for('login')) return redirect(url_for('login'))
@misc.restricted('interface')
@app.route('/applications') @app.route('/applications')
def applications(): def applications():
if 'name' in session: apps = ad.get_list(session['name'])
apps = ad.get_list(session['name'])
return render_template('new/public/applications.html', apps=apps[1])
return render_template('new/public/applications.html', apps=apps[1])
else:
return redirect(url_for('login'))
@misc.restricted('interface')
@app.route('/application/<appkey>') @app.route('/application/<appkey>')
def application(appkey): def application(appkey):
if 'name' in session: ap = list(ad.get(appkey)[1])
ap = list(ad.get(appkey)[1]) ap[5] = misc.skey_b64_to_hex(ap[5])
ap[5] = misc.skey_b64_to_hex(ap[5]) devs = dd.get_list(ap[1])[1]
devs = dd.get_list(ap[1])[1]
return render_template('new/public/application.html', app=ap, devs=devs) return render_template('new/public/application.html', app=ap, devs=devs)
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/new-application', methods=['GET', 'POST']) @app.route('/new-application', methods=['GET', 'POST'])
def application_create(): def application_create():
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': return render_template('new/public/new-application.html')
return render_template('new/public/new-application.html') elif request.method == 'POST':
if request.form['appname'] == '':
flash('Application name cannot be empty.', 'danger')
return render_template(request.url)
elif request.method == 'POST': elif request.method == 'POST':
if request.form['appname'] == '': appkey = misc.rand_str(app.config['APPKEY_LENGTH']).decode('utf-8')
flash('Application name cannot be empty.', 'danger') secure_key = misc.gen_skey_b64(16)
return render_template(request.url) secure = False
elif request.method == 'POST':
appkey = misc.rand_str(app.config['APPKEY_LENGTH']).decode('utf-8')
secure_key = misc.gen_skey_b64(16)
secure = False
if request.form.getlist('secure') and request.form.getlist('secure')[0] == 'on': if request.form.getlist('secure') and request.form.getlist('secure')[0] == 'on':
secure = True secure = True
res = ad.create(request.form['appname'], appkey, session['name'], request.form['appdesc'], secure, secure_key) res = ad.create(request.form['appname'], appkey, session['name'], request.form['appdesc'], secure, secure_key)
if not res[0]: if not res[0]:
flash('Error: {}'.format(res[1]), 'danger') flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url) return render_template(request.url)
res = dd.create_table_ddm(appkey) res = dd.create_table_ddm(appkey)
if not res[0]: if not res[0]:
ad.delete(appkey) ad.delete(appkey)
flash('Error: {}'.format(res[1]), 'danger') flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url) return render_template(request.url)
return redirect(url_for('applications')) return redirect(url_for('applications'))
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/delete') @app.route('/application/<appkey>/delete')
def application_delete(appkey): def application_delete(appkey):
if 'name' in session: devs = dd.get_list(appkey)
devs = dd.get_list(appkey)
for dev in devs[1]:
for dev in devs[1]: data.delete_table(appkey, dev[1])
data.delete_table(appkey, dev[1]) # delete notifications
# delete notifications nq.delete_per_device(appkey, dev[1])
nq.delete_per_device(appkey, dev[1]) nfss = nfs.get_per_device(appkey, dev[1])
nfss = nfs.get_per_device(appkey, dev[1]) for nf in nfss[1]:
for nf in nfss[1]: tr.delete(appkey, dev[1], nf[0])
tr.delete(appkey, dev[1], nf[0]) tr.delete_function(appkey, dev[1], nf[0])
tr.delete_function(appkey, dev[1], nf[0]) nfs.delete(appkey, dev[1], nf[0])
nfs.delete(appkey, dev[1], nf[0])
dd.delete_table(appkey)
dd.delete_table(appkey)
res = ad.delete(appkey)
res = ad.delete(appkey)
if not res[0]:
if not res[0]: flash('Error deleting application: {}'.format(res[1]), 'danger')
flash('Error deleting application: {}'.format(res[1]), 'danger') return redirect(url_for('application', appkey=appkey))
return redirect(url_for('application', appkey=appkey))
else:
flash('Application deleted.', 'success')
return redirect(url_for('applications'))
else: else:
return redirect(url_for('login')) flash('Application deleted.', 'success')
return redirect(url_for('applications'))
@misc.required_privilege(20) @misc.restricted('interface')
@app.route('/application/<appkey>/device/<devid>') @app.route('/application/<appkey>/device/<devid>')
def application_device(appkey, devid): def application_device(appkey, devid):
if 'name' in session: ap = ad.get(appkey)
ap = ad.get(appkey) if session['name'] == ap[1][2]:
if session['name'] == ap[1][2]: dev = dd.get(appkey, devid)
dev = dd.get(appkey, devid)
ld = data.get_last_range(appkey, devid, [MAX_PG_ENTRIES_DATA, 0]) ld = data.get_last_n(appkey, devid, 1)
cnt = data.get_count(appkey, devid) cnt = data.get_count(appkey, devid)
ltup = 'Device have not any sent data yet' ltup = 'Device have not any sent data yet'
if ld[0] and ld[1][0] != []: if ld[0] and ld[1][0] != []:
ltup = ld[1][0][1] ltup = ld[1][0][1]
if ld[0]: return render_template('new/public/device.html', dev=dev[1], app=ap[1], ltup=ltup, total=cnt[1][0], table_max=MAX_PG_ENTRIES_DATA)
return render_template('new/public/device.html', dev=dev[1], app=ap[1], ltup=ltup, total=cnt[1][0], table_max=MAX_PG_ENTRIES_DATA)
else:
return render_template('new/public/device.html', dev=dev[1], app=ap[1], ltup=ltup, total=cnt[1][0])
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/add-device', methods=['GET', 'POST']) @app.route('/application/<appkey>/add-device', methods=['GET', 'POST'])
def application_add_device(appkey): def application_add_device(appkey):
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': ap = ad.get(appkey)
ap = ad.get(appkey) dev_list = dd.get_list(appkey)
dev_list = dd.get_list(appkey) return render_template('new/public/add-device.html', app=ap[1], free_ids=misc.prep_id_range(dev_list[1]), models=ddm.MODELS)
return render_template('new/public/add-device.html', app=ap[1], free_ids=misc.prep_id_range(dev_list[1]), models=ddm.MODELS) elif request.method == 'POST':
elif request.method == 'POST': ddmin = ddm.extract(request)
ddmin = ddm.extract(request)
res = dd.create_ddm(request.form['devname'], request.form['devid'], appkey, request.form['devdesc'], ddmin)
res = dd.create_ddm(request.form['devname'], request.form['devid'], appkey, request.form['devdesc'], ddmin) if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url)
else:
res = data.create_table_ddm(appkey, request.form['devid'])
if not res[0]: if not res[0]:
dd.delete(session['appkey'], request.form['devid'])
flash('Error: {}'.format(res[1]), 'danger') flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url) return render_template(request.url)
else: else:
res = data.create_table_ddm(appkey, request.form['devid']) return redirect(url_for('application', appkey=appkey))
if not res[0]:
dd.delete(session['appkey'], request.form['devid'])
flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url)
else:
return redirect(url_for('application', appkey=appkey))
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/device/<devid>/delete') @app.route('/application/<appkey>/device/<devid>/delete')
def application_device_delete(appkey, devid): def application_device_delete(appkey, devid):
if 'name' in session: nq.delete_per_device(appkey, devid)
nq.delete_per_device(appkey, devid) nfss = nfs.get_per_device(appkey, devid)
nfss = nfs.get_per_device(appkey, devid) for nf in nfss[1]:
for nf in nfss[1]: tr.delete(appkey, devid, nf[0])
tr.delete(appkey, devid, nf[0]) tr.delete_function(appkey, devid, nf[0])
tr.delete_function(appkey, devid, nf[0]) nfs.delete(appkey, devid, nf[0])
nfs.delete(appkey, devid, nf[0])
data.delete_table(appkey, devid) data.delete_table(appkey, devid)
res = dd.delete(appkey, devid) res = dd.delete(appkey, devid)
flash('Device removed.', 'success') flash('Device removed.', 'success')
return redirect(url_for('application', appkey=appkey)) return redirect(url_for('application', appkey=appkey))
else:
return redirect(utl_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/device/<devid>/configure', methods=['GET', 'POST']) @app.route('/application/<appkey>/device/<devid>/configure', methods=['GET', 'POST'])
def application_device_configuration(appkey, devid): def application_device_configuration(appkey, devid):
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': pend_msgs = pend.get_list(appkey, devid)
pend_msgs = pend.get_list(appkey, devid) ap = ad.get(appkey)[1]
ap = ad.get(appkey)[1] dev = dd.get(appkey, devid)[1]
dev = dd.get(appkey, devid)[1] if pend_msgs[0]:
if pend_msgs[0]: config_list = []
config_list = []
for pm in pend_msgs[1]:
for pm in pend_msgs[1]: cntt = binascii.a2b_base64(pm[2])
cntt = binascii.a2b_base64(pm[2]) config_id = int(cntt[0])
config_id = int(cntt[0]) config_args = cntt[2:(len(cntt)-1)].decode('utf-8')
config_args = cntt[2:(len(cntt)-1)].decode('utf-8') ack = pm[3]
ack = pm[3] config_list.append((config_id, config_args, ack, pm[2]))
config_list.append((config_id, config_args, ack, pm[2]))
return render_template('new/public/device-configuration.html', dev=dev, app=ap, config_list=config_list)
return render_template('new/public/device-configuration.html', dev=dev, app=ap, config_list=config_list) elif request.method == 'POST':
elif request.method == 'POST': base64_args = misc.pend_base64_encode(request.form['arg'], request.form['confid'])
base64_args = misc.pend_base64_encode(request.form['arg'], request.form['confid']) pend.create(appkey, devid, base64_args)
pend.create(appkey, devid, base64_args)
flash('Message enqueued', 'success')
flash('Message enqueued', 'success') return '', 201
return '', 201
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('interface')
@app.route('/application/<appkey>/device/<devid>/download-csv') @app.route('/application/<appkey>/device/<devid>/download-csv')
def application_device_download_csv(appkey, devid): def application_device_download_csv(appkey, devid):
if 'name' in session: dumpd = data.get_all(appkey, devid)
dumpd = data.get_all(appkey, devid) ap = ad.get(appkey)[1]
ap = ad.get(appkey)[1] dev = dd.get(appkey, devid)[1]
dev = dd.get(appkey, devid)[1]
fn = ap[0]+ '-' +dev[0]+ '-data.csv' fn = ap[0]+ '-' +dev[0]+ '-data.csv'
with open(app.config['DATA_DOWNLOAD_DIR_OS']+'/'+fn, 'w+') as f: with open(app.config['DATA_DOWNLOAD_DIR_OS']+'/'+fn, 'w+') as f:
f.write('utc,timestamp,') f.write('utc,timestamp,')
for d in dumpd[1][0][2]: for d in dumpd[1][0][2]:
f.write(d) f.write(d)
f.write(',')
f.write('\n')
for row in dumpd[1]:
f.write('{},{},'.format(row[0],row[1]))
for v in row[2]:
f.write(str(row[2][v]))
f.write(',') f.write(',')
f.write('\n') f.write('\n')
for row in dumpd[1]: return send_from_directory(app.config['DATA_DOWNLOAD_DIR'], fn, as_attachment=True)
f.write('{},{},'.format(row[0],row[1]))
for v in row[2]:
f.write(str(row[2][v]))
f.write(',')
f.write('\n')
return send_from_directory(app.config['DATA_DOWNLOAD_DIR'], fn, as_attachment=True)
else:
return redirect(utl_for('login'))
@misc.restricted('interface')
@app.route('/chart-update') @app.route('/chart-update')
def chart_update(): def chart_update():
if 'name' in session: day_chart_values = md.get_user_data_count_per_hour_period(session['name'], 11)[1]
day_chart_values = md.get_user_data_count_per_hour_period(session['name'], 11)[1] day_chart_values = [x[0] for x in day_chart_values]
day_chart_values = [x[0] for x in day_chart_values] day_chart_labels = [misc.local_hour(x) for x in range(11,-1,-1)]
day_chart_labels = [misc.local_hour(x) for x in range(11,-1,-1)] day_chart = [day_chart_labels, day_chart_values]
day_chart = [day_chart_labels, day_chart_values]
week_chart_values = md.get_user_data_count_per_day_period(session['name'], 6)[1]
week_chart_values = md.get_user_data_count_per_day_period(session['name'], 6)[1] week_chart_values = [x[0] for x in week_chart_values]
week_chart_values = [x[0] for x in week_chart_values] week_chart_labels = [misc.local_weekday(x) for x in range(6,-1,-1)]
week_chart_labels = [misc.local_weekday(x) for x in range(6,-1,-1)] week_chart = [week_chart_labels, week_chart_values]
week_chart = [week_chart_labels, week_chart_values]
return "[{}, {}]".format(day_chart, week_chart), 200
return "[{}, {}]".format(day_chart, week_chart)
else:
return '', 401
@misc.restricted('interface')
@app.route('/recent-activity') @app.route('/recent-activity')
def recent_activity(): def recent_activity():
if 'name' in session: recent_activity = md.get_recent_activity(session['name'])[1]
recent_activity = md.get_recent_activity(session['name'])[1]
ra = '' ra = ''
for r in recent_activity: for r in recent_activity:
dev = dd.get(r[5], r[6])[1] dev = dd.get(r[5], r[6])[1]
ra += '<tr><th scope="row">'+r[1]+'</th><th>'+r[2]+'</th><th>'+r[0]+'</th><th>'+str(ddm.read_data(r[3], dev[3]))+'</th></tr>' ra += '<tr><th scope="row">'+r[1]+'</th><th>'+r[2]+'</th><th>'+r[0]+'</th><th>'+str(ddm.read_data(r[3], dev[3]))+'</th></tr>'
return ra, 200 return ra, 200
else:
return '', 401
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/device/<devid>/remove-configuration') @app.route('/application/<appkey>/device/<devid>/remove-configuration')
def application_device_configuration_remove(appkey, devid): def application_device_configuration_remove(appkey, devid):
if 'name' in session: res = pend.delete(appkey, devid, request.args.get('conf')+'_')
res = pend.delete(appkey, devid, request.args.get('conf')+'_')
if res[0]: if res[0]:
flash('Configuration message successfully removed.','success') flash('Configuration message successfully removed.','success')
else:
flash('Error removing configuration message: {}'.format(res[1]), 'danger')
return '', 200
else: else:
return redirect(url_for('login')) flash('Error removing configuration message: {}'.format(res[1]), 'danger')
return '', 200
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/device/<devid>/variables') @app.route('/application/<appkey>/device/<devid>/variables')
def application_device_variables(appkey, devid): def application_device_variables(appkey, devid):
if 'name' in session: dmodel = dd.get(appkey, devid)
dmodel = dd.get(appkey, devid) if dmodel[0]:
if dmodel[0]: select = '<select class="form-control" id="varname" name="varname" onchange="validate_form();" required>'
select = '<select class="form-control" id="varname" name="varname" onchange="validate_form();" required>' select += '<option value="-">Select Variable</option>'
select += '<option value="-">Select Variable</option>' for k in dmodel[1][3]['format']:
for k in dmodel[1][3]['format']: select += '<option>'+k+'</option>'
select += '<option>'+k+'</option>' select += '</select>'
select += '</select>' return select
return select
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/delete-account') @app.route('/delete-account')
def delete_account(): def delete_account():
user = ud.get(request.args.get('name')) user = ud.get(request.args.get('name'))
if user[0] and user[1][2] != 'admin': app_list = ad.get_list(user[1][0])
app_list = ad.get_list(user[1][0])
res = (True,)
res = (True,) if app_list[0]:
if app_list[0]: for app in app_list[1]:
for app in app_list[1]: devs = dd.get_list(app[1])
devs = dd.get_list(app[1]) for dev in devs[1]:
for dev in devs[1]: res = data.delete_table(app[1], dev[1])
res = data.delete_table(app[1], dev[1])
if not res[0]:
break
if res[0]:
res = dd.delete_table(app[1])
if res[0]:
res = ad.delete(app[1])
if not res[0]: if not res[0]:
break break
if res[0]: if res[0]:
res = ud.delete(user[1][0]) res = dd.delete_table(app[1])
if res[0]:
res = ad.delete(app[1])
if not res[0]: if not res[0]:
flash('Error: {}'.format(res[1]), 'danger') break
return render_template('new/public/settings.html', user=session['name'])
else: if res[0]:
flash('User {} was successfully deleted'.format(request.args.get('name')), 'success') res = ud.delete(user[1][0])
return redirect(url_for('login'))
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return render_template('new/public/settings.html', user=session['name'])
else: else:
flash('Warning: the user is admin or does not exist.' ,'danger') flash('User {} was successfully deleted'.format(request.args.get('name')), 'success')
return redirect(url_for('settings')) return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/settings', methods=['GET', 'POST']) @app.route('/settings', methods=['GET', 'POST'])
def settings(): def settings():
if request.method == 'GET': if request.method == 'GET':
...@@ -444,7 +400,7 @@ def settings(): ...@@ -444,7 +400,7 @@ def settings():
return redirect(request.url) return redirect(request.url)
@misc.required_privilege(20) @misc.restricted('interface')
@app.route('/application/<appkey>/device/<devid>/data/<var>/<dest>/<page>') @app.route('/application/<appkey>/device/<devid>/data/<var>/<dest>/<page>')
def application_device_data(appkey, devid, var, dest, page): def application_device_data(appkey, devid, var, dest, page):
dev = dd.get(appkey, devid)[1] dev = dd.get(appkey, devid)[1]
...@@ -469,162 +425,141 @@ def application_device_data(appkey, devid, var, dest, page): ...@@ -469,162 +425,141 @@ def application_device_data(appkey, devid, var, dest, page):
return t return t
@misc.required_privilege(20) @misc.restricted('interface')
@app.route('/application/<appkey>/alerts') @app.route('/application/<appkey>/alerts')
def application_alerts(appkey): def application_alerts(appkey):
if 'name' in session: ap = ad.get(appkey)
ap = ad.get(appkey) alerts = nfs.get_alerts_list(appkey)
alerts = nfs.get_alerts_list(appkey) return render_template('new/public/alerts.html', alert_list=alerts[1], app=ap[1])
return render_template('new/public/alerts.html', alert_list=alerts[1], app=ap[1])
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/new-alert', methods=['GET', 'POST']) @app.route('/application/<appkey>/new-alert', methods=['GET', 'POST'])
def application_new_alert(appkey): def application_new_alert(appkey):
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': ap = ad.get(appkey)
ap = ad.get(appkey) devs = dd.get_list(appkey)
devs = dd.get_list(appkey)
return render_template('new/public/new-alert.html', devs=devs[1], app=ap[1])
return render_template('new/public/new-alert.html', devs=devs[1], app=ap[1]) elif request.method == 'POST':
elif request.method == 'POST': # create new notification
# create new notification nid = misc.rand_str(app.config['NID_LENGTH']).decode('utf-8')
nid = misc.rand_str(app.config['NID_LENGTH']).decode('utf-8') dev = dd.get(appkey, request.form['devid'])
dev = dd.get(appkey, request.form['devid'])
try:
try: desc = dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue']
desc = dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue'] res = nfs.create(nid, appkey, request.form['devid'], request.form['alertname'], desc, 'alert', request.form['alertemail'])
res = nfs.create(nid, appkey, request.form['devid'], request.form['alertname'], desc, 'alert', request.form['alertemail']) if res[0]:
if res[0]: # create new function and trigger
# create new function and trigger t = tr.create_function_rt(appkey, request.form['devid'], nid, [request.form['varname'],request.form['operation'],request.form['avalue']],'alert',request.form['alertemail'])
t = tr.create_function_rt(appkey, request.form['devid'], nid, [request.form['varname'],request.form['operation'],request.form['avalue']],'alert',request.form['alertemail']) tr.create(appkey, request.form['devid'], nid)
tr.create(appkey, request.form['devid'], nid) flash('Alert created', 'success')
flash('Alert created', 'success') return redirect(url_for('application_alerts', appkey=appkey))
return redirect(url_for('application_alerts', appkey=appkey)) else:
else: flash('Error creating new alert: {}'.format(res[1]), 'danger')
flash('Error creating new alert: {}'.format(res[1]), 'danger')
return redirect(request.url)
except Exception as e:
flash('Error creating new alert: {}. Make sure you have filled all form fields.'.format(e), 'danger')
return redirect(request.url) return redirect(request.url)
else: except Exception as e:
return redirect(url_for('login')) flash('Error creating new alert: {}. Make sure you have filled all form fields.'.format(e), 'danger')
return redirect(request.url)
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/delete-<ntype>') @app.route('/application/<appkey>/delete-<ntype>')
def application_notification_remove(appkey, ntype): def application_notification_remove(appkey, ntype):
if 'name' in session: nq.delete(appkey, request.args.get('devid'), request.args.get('id'))
nq.delete(appkey, request.args.get('devid'), request.args.get('id')) tr.delete(appkey, request.args.get('devid'), request.args.get('id'))
tr.delete(appkey, request.args.get('devid'), request.args.get('id')) tr.delete_function(appkey, request.args.get('devid'), request.args.get('id'))
tr.delete_function(appkey, request.args.get('devid'), request.args.get('id')) res = nfs.delete(appkey, request.args.get('devid'), request.args.get('id'))
res = nfs.delete(appkey, request.args.get('devid'), request.args.get('id'))
if res[0]:
if res[0]: flash('{} removed'.format(ntype.capitalize()), 'success')
flash('{} removed'.format(ntype.capitalize()), 'success') return '', 200
return '', 200
else:
flash('{} cannot be removed : {}'.format(ntype.capitalize(), res[1]), 'danger')
return '', 500
else: else:
return redirect(url_for('login')) flash('{} cannot be removed : {}'.format(ntype.capitalize(), res[1]), 'danger')
return '', 500
@misc.required_privilege(20) @misc.restricted('interface')
@app.route('/application/<appkey>/automation') @app.route('/application/<appkey>/automation')
def application_automation(appkey): def application_automation(appkey):
if 'name' in session: ap = ad.get(appkey)
ap = ad.get(appkey) ats = nfs.get_automation_list(appkey)
ats = nfs.get_automation_list(appkey)
return render_template('new/public/automation.html', automations=ats[1], app=ap[1])
return render_template('new/public/automation.html', automations=ats[1], app=ap[1])
else:
return redirect(url_for('login'))
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/new-automation', methods=['GET', 'POST']) @app.route('/application/<appkey>/new-automation', methods=['GET', 'POST'])
def application_new_automation(appkey): def application_new_automation(appkey):
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': ap = ad.get(appkey)
ap = ad.get(appkey) devs = dd.get_list(appkey)
devs = dd.get_list(appkey)
return render_template('new/public/new-automation.html', devs=devs[1], app=ap[1])
return render_template('new/public/new-automation.html', devs=devs[1], app=ap[1]) elif request.method == 'POST':
elif request.method == 'POST': # create new notification
# create new notification nid = misc.rand_str(app.config['NID_LENGTH']).decode('utf-8')
nid = misc.rand_str(app.config['NID_LENGTH']).decode('utf-8') dev = dd.get(appkey, request.form['devid'])
dev = dd.get(appkey, request.form['devid']) adev = dd.get(appkey, request.form['adevid'])
adev = dd.get(appkey, request.form['adevid'])
try:
try: desc = 'IF '+dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue']+' THEN '+adev[1][0]+'.confID_'+request.form['confid']+' = '+request.form['arg']
desc = 'IF '+dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue']+' THEN '+adev[1][0]+'.confID_'+request.form['confid']+' = '+request.form['arg'] # action format: '<devid>#<confid>#<arg>'
# action format: '<devid>#<confid>#<arg>' action = request.form['adevid']+'#'+request.form['confid']+'#'+request.form['arg']
action = request.form['adevid']+'#'+request.form['confid']+'#'+request.form['arg'] res = nfs.create(nid, appkey, request.form['devid'], request.form['automationname'], desc, 'automation', action)
res = nfs.create(nid, appkey, request.form['devid'], request.form['automationname'], desc, 'automation', action) if res[0]:
if res[0]: # create new function and trigger
# create new function and trigger t = tr.create_function_rt(appkey, request.form['devid'], nid, [request.form['varname'],request.form['operation'],request.form['avalue']],'automation', action)
t = tr.create_function_rt(appkey, request.form['devid'], nid, [request.form['varname'],request.form['operation'],request.form['avalue']],'automation', action) tr.create(appkey, request.form['devid'], nid)
tr.create(appkey, request.form['devid'], nid) flash('Automation created', 'success')
flash('Automation created', 'success') return redirect(url_for('application_automation', appkey=appkey))
return redirect(url_for('application_automation', appkey=appkey)) else:
else: flash('Error creating new alert: {}'.format(res[1]), 'danger')
flash('Error creating new alert: {}'.format(res[1]), 'danger')
return redirect(request.url)
except Exception as e:
flash('Error creating new alert: {}. Make sure you have filled all form fields.'.format(e), 'danger')
return redirect(request.url) return redirect(request.url)
else: except Exception as e:
return redirect(url_for('login')) flash('Error creating new alert: {}. Make sure you have filled all form fields.'.format(e), 'danger')
return redirect(request.url)
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/settings', methods=['GET', 'POST']) @app.route('/application/<appkey>/settings', methods=['GET', 'POST'])
def application_settings(appkey): def application_settings(appkey):
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': ap = ad.get(appkey)
ap = ad.get(appkey)
return render_template('new/public/application-settings.html', app=ap[1]) return render_template('new/public/application-settings.html', app=ap[1])
elif request.method == 'POST': elif request.method == 'POST':
if request.form.getlist('secure') and request.form.getlist('secure')[0] == 'on': if request.form.getlist('secure') and request.form.getlist('secure')[0] == 'on':
secure = True secure = True
else: else:
secure = False secure = False
res = ad.update(appkey, request.form['appname'], request.form['appdesc'], secure)
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url)
return redirect(request.url) res = ad.update(appkey, request.form['appname'], request.form['appdesc'], secure)
else:
return redirect(url_for('login')) if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return render_template(request.url)
return redirect(request.url)
@misc.required_privilege(20) @misc.restricted('user')
@app.route('/application/<appkey>/device/<devid>/settings', methods=['GET', 'POST']) @app.route('/application/<appkey>/device/<devid>/settings', methods=['GET', 'POST'])
def application_device_settings(appkey, devid): def application_device_settings(appkey, devid):
if 'name' in session: if request.method == 'GET':
if request.method == 'GET': ap = ad.get(appkey)
ap = ad.get(appkey) dev = dd.get(appkey, devid)
dev = dd.get(appkey, devid)
return render_template('new/public/device-settings.html', app=ap[1], dev=dev[1], models=ddm.MODELS) return render_template('new/public/device-settings.html', app=ap[1], dev=dev[1], models=ddm.MODELS)
elif request.method == 'POST': elif request.method == 'POST':
ddmin = ddm.extract(request) ddmin = ddm.extract(request)
res = dd.update_ddm(appkey, devid, request.form['devname'], request.form['devdesc'], ddmin) res = dd.update_ddm(appkey, devid, request.form['devname'], request.form['devdesc'], ddmin)
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url)
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url) return redirect(request.url)
else:
return redirect(url_for('login')) return redirect(request.url)
......
...@@ -13,7 +13,7 @@ import app.dao.notification_queue.notification_queue as nq ...@@ -13,7 +13,7 @@ import app.dao.notification_queue.notification_queue as nq
import app.dao.misc.misc as md import app.dao.misc.misc as md
#import app.helpers.misc as misc #import app.helpers.misc as misc
from app.helpers.misc import restricted, required_privilege from app.helpers.misc import restricted
import app.helpers.device_data_model as ddm import app.helpers.device_data_model as ddm
import app.helpers.misc as misc import app.helpers.misc as misc
...@@ -27,9 +27,8 @@ MAX_PG_ENTRIES_DATA = 10 ...@@ -27,9 +27,8 @@ MAX_PG_ENTRIES_DATA = 10
MAX_PG_ENTRIES_GRAPH_HOURS = 24 MAX_PG_ENTRIES_GRAPH_HOURS = 24
@required_privilege(40)
@app.route('/administration', methods=['GET', 'POST']) @app.route('/administration', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted('admin')
def administration(): def administration():
if request.method == 'GET': if request.method == 'GET':
user_cnt = ud.get_count()[1][0] user_cnt = ud.get_count()[1][0]
...@@ -47,7 +46,6 @@ def administration(): ...@@ -47,7 +46,6 @@ def administration():
return redirect(request.url) return redirect(request.url)
@required_privilege(40)
@app.route('/administration/users') @app.route('/administration/users')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users(): def administration_users():
...@@ -62,20 +60,22 @@ def administration_users(): ...@@ -62,20 +60,22 @@ def administration_users():
return render_template('new/admin/users.html', users=users, info=info) return render_template('new/admin/users.html', users=users, info=info)
@required_privilege(40)
@app.route('/administration/users/<name>') @app.route('/administration/users/<name>')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user(name): def administration_users_user(name):
created_apps = ad.get_count_by_user(name)[1][0] user = ud.get(name)
active_devices = dd.get_count_by_user(name) if user[0]:
total_activity = md.get_user_data_count(name)[1][0] created_apps = ad.get_count_by_user(name)[1][0]
last_activity = md.get_user_data_count_per_day(name)[1][0] active_devices = dd.get_count_by_user(name)
info = [created_apps, active_devices, total_activity, last_activity] total_activity = md.get_user_data_count(name)[1][0]
last_activity = md.get_user_data_count_per_day(name)[1][0]
return render_template('new/admin/user-dashboard.html', info=info, user=name) info = [created_apps, active_devices, total_activity, last_activity]
return render_template('new/admin/user-dashboard.html', info=info, user=name)
else:
flash('Access denied', 'danger')
return redirect(url_for('administration_users'))
@required_privilege(40)
@app.route('/administration/users/<name>/applications') @app.route('/administration/users/<name>/applications')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_applications(name): def administration_users_user_applications(name):
...@@ -83,7 +83,6 @@ def administration_users_user_applications(name): ...@@ -83,7 +83,6 @@ def administration_users_user_applications(name):
return render_template('new/admin/user-applications.html', apps=apps, user=name) return render_template('new/admin/user-applications.html', apps=apps, user=name)
@required_privilege(40)
@app.route('/administration/users/<name>/new-application', methods=['GET', 'POST']) @app.route('/administration/users/<name>/new-application', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_create(name): def administration_users_user_application_create(name):
...@@ -117,7 +116,6 @@ def administration_users_user_application_create(name): ...@@ -117,7 +116,6 @@ def administration_users_user_application_create(name):
return redirect(url_for('administration_users_user_applications', name=name)) return redirect(url_for('administration_users_user_applications', name=name))
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>') @app.route('/administration/users/<name>/application/<appkey>')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application(name, appkey): def administration_users_user_application(name, appkey):
...@@ -128,7 +126,6 @@ def administration_users_user_application(name, appkey): ...@@ -128,7 +126,6 @@ def administration_users_user_application(name, appkey):
return render_template('new/admin/user-application.html', app=ap, devs=devs, user=name) return render_template('new/admin/user-application.html', app=ap, devs=devs, user=name)
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/add-device', methods=['GET', 'POST']) @app.route('/administration/users/<name>/application/<appkey>/add-device', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_add_device(name, appkey): def administration_users_user_application_add_device(name, appkey):
...@@ -154,14 +151,13 @@ def administration_users_user_application_add_device(name, appkey): ...@@ -154,14 +151,13 @@ def administration_users_user_application_add_device(name, appkey):
return redirect(url_for('administration_users_user_application', name=name, appkey=appkey)) return redirect(url_for('administration_users_user_application', name=name, appkey=appkey))
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>') @app.route('/administration/users/<name>/application/<appkey>/device/<devid>')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device(name, appkey, devid): def administration_users_user_application_device(name, appkey, devid):
ap = ad.get(appkey) ap = ad.get(appkey)
dev = dd.get(appkey, devid) dev = dd.get(appkey, devid)
ld = data.get_last_range(appkey, devid, [MAX_PG_ENTRIES_DATA, 0]) ld = data.get_last_n(appkey, devid, 1)
cnt = data.get_count(appkey, devid) cnt = data.get_count(appkey, devid)
ltup = 'Device has not any sent data yet' ltup = 'Device has not any sent data yet'
...@@ -169,13 +165,9 @@ def administration_users_user_application_device(name, appkey, devid): ...@@ -169,13 +165,9 @@ def administration_users_user_application_device(name, appkey, devid):
if ld[0] and ld[1][0] != []: if ld[0] and ld[1][0] != []:
ltup = ld[1][0][1] ltup = ld[1][0][1]
if ld[0]: return render_template('new/admin/user-device.html', dev=dev[1], app=ap[1], ltup=ltup, total=cnt[1][0], user=name, table_max=MAX_PG_ENTRIES_DATA)
return render_template('new/admin/user-device.html', dev=dev[1], app=ap[1], ltup=ltup, data=ld[1], total=cnt[1][0], user=name)
else:
return render_template('new/admin/user-device.html', dev=dev[1], app=ap[1], ltup=ltup, data=[], total=cnt[1][0], user=name)
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/settings', methods=['GET', 'POST']) @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/settings', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_settings(name, appkey, devid): def administration_users_user_application_device_settings(name, appkey, devid):
...@@ -195,7 +187,6 @@ def administration_users_user_application_device_settings(name, appkey, devid): ...@@ -195,7 +187,6 @@ def administration_users_user_application_device_settings(name, appkey, devid):
return redirect(request.url) return redirect(request.url)
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/delete') @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/delete')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_delete(name, appkey, devid): def administration_users_user_application_device_delete(name, appkey, devid):
...@@ -212,7 +203,6 @@ def administration_users_user_application_device_delete(name, appkey, devid): ...@@ -212,7 +203,6 @@ def administration_users_user_application_device_delete(name, appkey, devid):
return redirect(url_for('administration_users_user_application', name=name, appkey=appkey)) return redirect(url_for('administration_users_user_application', name=name, appkey=appkey))
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/alerts') @app.route('/administration/users/<name>/application/<appkey>/alerts')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_alerts(name, appkey): def administration_users_user_application_alerts(name, appkey):
...@@ -221,7 +211,6 @@ def administration_users_user_application_alerts(name, appkey): ...@@ -221,7 +211,6 @@ def administration_users_user_application_alerts(name, appkey):
return render_template('new/admin/user-application-alerts.html', alert_list=alerts[1], app=ap[1], user=name) return render_template('new/admin/user-application-alerts.html', alert_list=alerts[1], app=ap[1], user=name)
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/new-alert', methods=['GET', 'POST']) @app.route('/administration/users/<name>/application/<appkey>/new-alert', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_new_alert(name, appkey): def administration_users_user_application_new_alert(name, appkey):
...@@ -252,7 +241,6 @@ def administration_users_user_application_new_alert(name, appkey): ...@@ -252,7 +241,6 @@ def administration_users_user_application_new_alert(name, appkey):
return redirect(request.url) return redirect(request.url)
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/automation') @app.route('/administration/users/<name>/application/<appkey>/automation')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_automation(name, appkey): def administration_users_user_application_automation(name, appkey):
...@@ -262,7 +250,6 @@ def administration_users_user_application_automation(name, appkey): ...@@ -262,7 +250,6 @@ def administration_users_user_application_automation(name, appkey):
return render_template('new/admin/user-application-automation.html', automations=ats[1], app=ap[1], user=name) return render_template('new/admin/user-application-automation.html', automations=ats[1], app=ap[1], user=name)
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/new-automation', methods=['GET', 'POST']) @app.route('/administration/users/<name>/application/<appkey>/new-automation', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_new_automation(name, appkey): def administration_users_user_application_new_automation(name, appkey):
...@@ -296,7 +283,6 @@ def administration_users_user_application_new_automation(name, appkey): ...@@ -296,7 +283,6 @@ def administration_users_user_application_new_automation(name, appkey):
return redirect(request.url) return redirect(request.url)
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/delete') @app.route('/administration/users/<name>/application/<appkey>/delete')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_delete(name, appkey): def administration_users_user_application_delete(name, appkey):
...@@ -324,7 +310,6 @@ def administration_users_user_application_delete(name, appkey): ...@@ -324,7 +310,6 @@ def administration_users_user_application_delete(name, appkey):
return redirect(url_for('administration_users_user_applications', name=name)) return redirect(url_for('administration_users_user_applications', name=name))
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/settings', methods=['GET', 'POST']) @app.route('/administration/users/<name>/application/<appkey>/settings', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_settings(name, appkey): def administration_users_user_application_settings(name, appkey):
...@@ -347,7 +332,6 @@ def administration_users_user_application_settings(name, appkey): ...@@ -347,7 +332,6 @@ def administration_users_user_application_settings(name, appkey):
return redirect(request.url) return redirect(request.url)
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/delete-<ntype>') @app.route('/administration/users/<name>/application/<appkey>/delete-<ntype>')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_notification_remove(name, appkey, ntype): def administration_users_user_application_notification_remove(name, appkey, ntype):
...@@ -364,29 +348,28 @@ def administration_users_user_application_notification_remove(name, appkey, ntyp ...@@ -364,29 +348,28 @@ def administration_users_user_application_notification_remove(name, appkey, ntyp
return '', 500 return '', 500
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/variables') @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/variables')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_variables(name, appkey, devid): def administration_users_user_application_device_variables(name, appkey, devid):
last = data.get_last_n(appkey, devid, 1) dev = dd.get(appkey, devid)[1]
if last[0]: select = '<select class="form-control" id="varname" name="varname" onchange="validate_form();" required>'
select = '<select class="form-control" id="varname" name="varname" onchange="validate_form();" required>' select += '<option value="-">Select Variable</option>'
select += '<option value="-">Select Variable</option>' for k in dev[3]['format']:
for k in last[1][0][2]: select += '<option>'+k+'</option>'
select += '<option>'+k+'</option>' select += '</select>'
select += '</select>' return select
return select
@required_privilege(40)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/data/<var>/<dest>/<page>') @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/data/<var>/<dest>/<page>')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_data(name, appkey, devid, var, dest, page): def administration_users_user_application_device_data(name, appkey, devid, var, dest, page):
dev = dd.get(appkey, devid)[1]
if dest == 'graph': if dest == 'graph':
last = data.get_last_hours(appkey, devid, MAX_PG_ENTRIES_GRAPH_HOURS, int(page)) last = data.get_last_hours(appkey, devid, MAX_PG_ENTRIES_GRAPH_HOURS, int(page))
arr = '[["Time", "{}"],'.format(var)
if last[0]: if last[0]:
for d in last[1]: arr = '[["Time", "{}"],'.format(var)
last = [ddm.decode_datum(d, dev[3]) for d in last[1]]
for d in last:
arr += '[new Date('+str(d[0])+'*1000),'+str(d[2][var])+'],' arr += '[new Date('+str(d[0])+'*1000),'+str(d[2][var])+'],'
arr += ']' arr += ']'
return arr return arr
...@@ -395,12 +378,12 @@ def administration_users_user_application_device_data(name, appkey, devid, var, ...@@ -395,12 +378,12 @@ def administration_users_user_application_device_data(name, appkey, devid, var,
last = data.get_last_range(appkey, devid, [MAX_PG_ENTRIES_DATA, (int(page)-1)*MAX_PG_ENTRIES_DATA]) last = data.get_last_range(appkey, devid, [MAX_PG_ENTRIES_DATA, (int(page)-1)*MAX_PG_ENTRIES_DATA])
t = '' t = ''
if last[0]: if last[0]:
for d in last[1]: last = [ddm.decode_datum(d, dev[3]) for d in last[1]]
for d in last:
t += '<tr><th>'+d[1]+'</th><th>'+str(d[2][var])+'</th></tr>' t += '<tr><th>'+d[1]+'</th><th>'+str(d[2][var])+'</th></tr>'
return t return t
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/configure', methods=['GET', 'POST']) @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/configure', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_configuration(name, appkey, devid): def administration_users_user_application_device_configuration(name, appkey, devid):
...@@ -427,7 +410,6 @@ def administration_users_user_application_device_configuration(name, appkey, dev ...@@ -427,7 +410,6 @@ def administration_users_user_application_device_configuration(name, appkey, dev
return '', 201 return '', 201
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/remove-configuration') @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/remove-configuration')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_configuration_remove(name, appkey, devid): def administration_users_user_application_device_configuration_remove(name, appkey, devid):
...@@ -441,7 +423,6 @@ def administration_users_user_application_device_configuration_remove(name, appk ...@@ -441,7 +423,6 @@ def administration_users_user_application_device_configuration_remove(name, appk
return '', 200 return '', 200
@required_privilege(60)
@app.route('/administration/users/<name>/application/<appkey>/device/<devid>/download-csv') @app.route('/administration/users/<name>/application/<appkey>/device/<devid>/download-csv')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_application_device_download_csv(name, appkey, devid): def administration_users_user_application_device_download_csv(name, appkey, devid):
...@@ -477,7 +458,6 @@ def administration_users_user_application_device_download_csv(name, appkey, devi ...@@ -477,7 +458,6 @@ def administration_users_user_application_device_download_csv(name, appkey, devi
return send_from_directory(app.config['DATA_DOWNLOAD_DIR'], fn, as_attachment=True) return send_from_directory(app.config['DATA_DOWNLOAD_DIR'], fn, as_attachment=True)
@required_privilege(40)
@app.route('/administration/users/<name>/chart-update') @app.route('/administration/users/<name>/chart-update')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_chart_update(name): def administration_users_user_chart_update(name):
...@@ -494,23 +474,19 @@ def administration_users_user_chart_update(name): ...@@ -494,23 +474,19 @@ def administration_users_user_chart_update(name):
return "[{}, {}]".format(day_chart, week_chart) return "[{}, {}]".format(day_chart, week_chart)
@required_privilege(40)
@app.route('/administration/users/<name>/recent-activity') @app.route('/administration/users/<name>/recent-activity')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_recent_activity(name): def administration_users_user_recent_activity(name):
if 'name' in session: recent_activity = md.get_recent_activity(name)[1]
recent_activity = md.get_recent_activity(name)[1] ra = ''
ra = ''
for r in recent_activity:
for r in recent_activity: dev = dd.get(r[5], r[6])[1]
ra += '<tr><th scope="row">'+r[1]+'</th><th>'+r[2]+'</th><th>'+r[0]+'</th><th>'+str(r[3])+'</th></tr>' ra += '<tr><th scope="row">'+r[1]+'</th><th>'+r[2]+'</th><th>'+r[0]+'</th><th>'+str(ddm.read_data(r[3], dev[3]))+'</th></tr>'
return ra, 200 return ra, 200
else:
return '', 401
@required_privilege(40)
@app.route('/administration/users/table/<page>') @app.route('/administration/users/table/<page>')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_table(page): def administration_users_table(page):
...@@ -520,7 +496,6 @@ def administration_users_table(page): ...@@ -520,7 +496,6 @@ def administration_users_table(page):
return str(users), 200 return str(users), 200
@required_privilege(40)
@app.route('/administration/users/new-user', methods=['POST', 'GET']) @app.route('/administration/users/new-user', methods=['POST', 'GET'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_new_user(): def administration_users_new_user():
...@@ -543,37 +518,44 @@ def administration_users_new_user(): ...@@ -543,37 +518,44 @@ def administration_users_new_user():
flash('Error: {}'.format(res[1]), 'danger') flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url) return redirect(request.url)
else: else:
return redirect(url_for('administration/users', name=username)) return redirect(url_for('administration_users_user', name=username))
@required_privilege(40)
@app.route('/administration/users/<name>/settings', methods=['GET', 'POST']) @app.route('/administration/users/<name>/settings', methods=['GET', 'POST'])
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_settings(name): def administration_users_user_settings(name):
if request.method == 'GET': user = ud.get(name)
return render_template('new/admin/user-settings.html', user=name) if user[0] and (misc.USER_LEVELS[user[1][2]] < misc.USER_LEVELS[session['role']]):
if request.method == 'GET':
return render_template('new/admin/user-settings.html', user=name, user_role=user[1][2])
else:
if request.form['name'] != name:
res = ud.update_name(name, request.form['name'])
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url);
if request.form['password'] != '':
res = ud.update_password(name, request.form['password'].encode('utf-8'))
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url)
if request.form['role'] != user[1][2]:
res = ud.update_role(name, request.form['role'])
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url)
flash('Settings successfully saved.', 'success')
return redirect(request.url)
else: else:
if request.form['name'] != name: flash('Access denied' ,'danger')
res = ud.update_name(name, request.form['name']) return redirect(url_for('administration_users_user', name=name))
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url);
if request.form['password'] != '':
res = ud.update_password(name, request.form['password'].encode('utf-8'))
if not res[0]:
flash('Error: {}'.format(res[1]), 'danger')
return redirect(request.url)
flash('Settings successfully saved.', 'success')
return redirect(request.url)
@required_privilege(80)
@app.route('/administration/users/<name>/delete-account') @app.route('/administration/users/<name>/delete-account')
@restricted(access_level='admin') @restricted(access_level='admin')
def administration_users_user_delete_account(name): def administration_users_user_delete_account(name):
user = ud.get(name) user = ud.get(name)
if user[0] and (user[1][2] != 'admin' or user[1][3] > 80): if user[0] and (misc.USER_LEVELS[user[1][2]] < misc.USER_LEVELS[session['role']]):
app_list = ad.get_list(user[1][0]) app_list = ad.get_list(user[1][0])
res = (True,) res = (True,)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment