Commit 0cf61ed1 authored by Marc Duez's avatar Marc Duez
Browse files

server : default controller, add comment/security and improve return mesage

parent de2952dc
......@@ -15,7 +15,8 @@ if request.env.http_origin:
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers['Access-Control-Max-Age'] = 86400
#########################################################################
##return the default index page for vidjil (empty)
def index():
"""
example action using the internationalization operator T and flash
......@@ -27,11 +28,15 @@ def index():
response.flash = T("Welcome to Vidjil!")
return dict(message=T('hello world'))
#########################################################################
##return the view default/help.html
def help():
return dict(message=T('help i\'m lost'))
#########################################################################
## add a scheduller task to run vidjil on a specific sequence file
# need sequence_file_id, config_id
# need patient admin permission
def run_request():
error = ""
......@@ -44,7 +49,7 @@ def run_request():
id_patient = db.sequence_file[request.vars["sequence_file_id"]].patient_id
if not auth.has_permission('admin', 'patient', id_patient) :
error += "you don't have permission to run request for this patient ("+str(id_patient)+")"
error += "you don't have permission to run request for this patient ("+str(id_patient)+"), "
row2 = db( ( db.scheduler_task.args == '["'+request.vars["sequence_file_id"]+'", "'+request.vars["config_id"]+'"]' )
& ( db.scheduler_task.status != "FAILED" )
......@@ -86,20 +91,28 @@ def run_request():
##add task to scheduller
scheduler.queue_task('run', [request.vars["sequence_file_id"],request.vars["config_id"], data_id, fuse_id]
, repeats = 1, timeout = 6000)
(filename, str) = db.sequence_file.data_file.retrieve(db.sequence_file[request.vars["sequence_file_id"]].data_file)
config_name = db.config[request.vars["config_id"]].name
patient_name = db.patient[id_patient].first_name + " " + db.patient[id_patient].last_name
res = {"redirect": "patient/info",
"args" : { "id" : id_patient,
"config_id" : request.vars["config_id"]},
"message": "request added"}
"message": "default/run_request : request added to run config " + config_name + " on " + filename + " for " + patient_name }
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
else :
res = {"success" : "false",
"message" : error}
"message" : "default/run_request : " + error}
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
#########################################################################
## return .data file
# need patient_id, config_id
# need patient admin or read permission
def get_data():
import time
from subprocess import Popen, PIPE, STDOUT
......@@ -128,10 +141,15 @@ def get_data():
return output
res = {"success" : "false", "msg" : "connect error"}
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
else :
res = {"success" : "false",
"message" : "default/get_data : " + error}
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
#########################################################################
## return .analysis file
# need patient_id, config_id
# need patient admin or read permission
def get_analysis():
error = ""
......@@ -139,6 +157,9 @@ def get_analysis():
error += "id patient file needed, "
if not "config_id" in request.vars:
error += "id config needed, "
if not auth.has_permission('admin', 'patient', request.vars["patient_id"]) and \
not auth.has_permission('read', 'patient', request.vars["patient_id"]):
error += "you don't have permission to consult this patient ("+id_patient+")"
## empty analysis file
res = {"custom": [],
......@@ -149,39 +170,48 @@ def get_analysis():
"time_order": []
}
## récupération des infos stockées sur la base de données
query = db( ( db.patient.id == db.sequence_file.patient_id )
& ( db.data_file.sequence_file_id == db.sequence_file.id )
& ( db.patient.id == request.vars["patient_id"] )
& ( db.data_file.config_id == request.vars["config_id"] )
).select( orderby=db.sequence_file.sampling_date )
order = 0
for row in query :
(filename, str) = db.sequence_file.data_file.retrieve(row.sequence_file.data_file)
res["time"].append(filename)
res["time_order"].append(order)
res["info_sequence_file"].append(row.sequence_file.info)
order = order+1
if error == "" :
## récupération des infos stockées sur la base de données
query = db( ( db.patient.id == db.sequence_file.patient_id )
& ( db.data_file.sequence_file_id == db.sequence_file.id )
& ( db.patient.id == request.vars["patient_id"] )
& ( db.data_file.config_id == request.vars["config_id"] )
).select( orderby=db.sequence_file.sampling_date )
order = 0
for row in query :
(filename, str) = db.sequence_file.data_file.retrieve(row.sequence_file.data_file)
res["time"].append(filename)
res["time_order"].append(order)
res["info_sequence_file"].append(row.sequence_file.info)
order = order+1
res["info_patient"] = db.patient[request.vars["patient_id"]].info
## récupération des infos se trouvant dans le fichier .analysis
analysis_query = db( (db.analysis_file.patient_id == request.vars["patient_id"])
& (db.analysis_file.config_id == request.vars["config_id"] ) )
res["info_patient"] = db.patient[request.vars["patient_id"]].info
## récupération des infos se trouvant dans le fichier .analysis
analysis_query = db( (db.analysis_file.patient_id == request.vars["patient_id"])
& (db.analysis_file.config_id == request.vars["config_id"] ) )
if not analysis_query.isempty() :
row = analysis_query.select().first()
f = open('applications/vidjil/uploads/'+row.analysis_file, "r")
analysis = gluon.contrib.simplejson.loads(f.read())
f.close()
res["custom"] = analysis["custom"]
res["cluster"] = analysis["cluster"]
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
if not analysis_query.isempty() :
row = analysis_query.select().first()
f = open('applications/vidjil/uploads/'+row.analysis_file, "r")
analysis = gluon.contrib.simplejson.loads(f.read())
f.close()
res["custom"] = analysis["custom"]
res["cluster"] = analysis["cluster"]
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
else :
res = {"success" : "false",
"message" : "default/get_analysis : " + error}
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
#########################################################################
## upload .analysis file and store it on the database
# need patient_id, config_id, fileToUpload
# need patient admin permission
def save_analysis():
error = ""
......@@ -189,6 +219,8 @@ def save_analysis():
error += "id patient file needed, "
if not "config_id" in request.vars:
error += "id config needed, "
if not auth.has_permission('admin', 'patient', request.vars['patient_id']) :
error += "you don't have permission to make change on this patient, "
if error == "" :
analysis_query = db( (db.analysis_file.patient_id == 1)
......@@ -205,18 +237,20 @@ def save_analysis():
patient_id = request.vars['patient_id'],
)
patient_name = db.patient[request.vars['patient_id']].first_name + " " + db.patient[request.vars['patient_id']].last_name
res = {"success" : "true", "msg" : "analysis saved"}
res = {"success" : "true",
"message" : "default/save_analysis : analysis saved ("+patient_name+")"}
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
else :
res = {"success" : "false", "msg" : error}
res = {"success" : "false",
"message" : error}
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
def test_upload():
response.title = ""
return dict(message=T('test upload'))
#########################################################################
## TODO make custom download for .data et .analysis
@cache.action()
def download():
"""
......@@ -226,6 +260,74 @@ def download():
return response.download(request, db, download_filename=request.vars.filename)
#########################################################################
##
def create_self_signed_cert(cert_dir):
"""
create a new self-signed cert and key and write them to disk
"""
from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
from os.path import exists, join
CERT_FILE = "ssl_certificate.crt"
KEY_FILE = "ssl_self_signed.key"
ssl_created = False
if not exists(join(cert_dir, CERT_FILE)) \
or not exists(join(cert_dir, KEY_FILE)):
ssl_created = True
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "AQ"
cert.get_subject().ST = "State"
cert.get_subject().L = "City"
cert.get_subject().O = "Company"
cert.get_subject().OU = "Organization"
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
open(join(cert_dir, CERT_FILE), "wt").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(join(cert_dir, KEY_FILE), "wt").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
create_self_signed_cert('.')
return(ssl_created, cert_dir, CERT_FILE, KEY_FILE)
#########################################################################
##just visit the view default/generate_ssl_key and restart web2py with the displayed command
def generate_ssl_key():
ssl_created, cert_dir, CERT_FILE, KEY_FILE = create_self_signed_cert(request.folder + "private/")
return(dict(ssl_created=ssl_created, cert_dir=cert_dir, CERT_FILE=CERT_FILE, KEY_FILE=KEY_FILE))
#########################################################################
##TODO remove useless function ( maybe used by web2py internally )
#########################################################################
##not used
def call():
"""
exposes services. for example:
......@@ -235,7 +337,8 @@ def call():
"""
return service()
#########################################################################
##not used
@auth.requires_signature()
def data():
"""
......@@ -253,7 +356,8 @@ def data():
"""
return dict(form=crud())
#########################################################################
## not used
@auth.requires_login()
@auth.requires_membership('admin')
def add_membership():
......@@ -274,6 +378,8 @@ def add_membership():
return dict(form=form)
#########################################################################
## not used
def upload_file():
import shutil, os.path
......@@ -311,7 +417,8 @@ def upload_file():
res = dict(files=[{"name": "kuik", "size": 0, "error": "fail!!" }])
return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
#########################################################################
## not used
def delete_file():
try:
id = request.args[0]
......@@ -324,7 +431,8 @@ def delete_file():
redirect( URL(f='patient', args=[patient_id]) )
#########################################################################
## not used
def upload():
return dict()
......@@ -344,52 +452,3 @@ def user():
to decorate functions that need access control
"""
return dict(form=auth())
def create_self_signed_cert(cert_dir):
"""
create a new self-signed cert and key and write them to disk
"""
from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
from os.path import exists, join
CERT_FILE = "ssl_certificate.crt"
KEY_FILE = "ssl_self_signed.key"
ssl_created = False
if not exists(join(cert_dir, CERT_FILE)) \
or not exists(join(cert_dir, KEY_FILE)):
ssl_created = True
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "AQ"
cert.get_subject().ST = "State"
cert.get_subject().L = "City"
cert.get_subject().O = "Company"
cert.get_subject().OU = "Organization"
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
open(join(cert_dir, CERT_FILE), "wt").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(join(cert_dir, KEY_FILE), "wt").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
create_self_signed_cert('.')
return(ssl_created, cert_dir, CERT_FILE, KEY_FILE)
def generate_ssl_key():
ssl_created, cert_dir, CERT_FILE, KEY_FILE = create_self_signed_cert(request.folder + "private/")
return(dict(ssl_created=ssl_created, cert_dir=cert_dir, CERT_FILE=CERT_FILE, KEY_FILE=KEY_FILE))
......@@ -145,7 +145,7 @@ def edit_form():
## return a flash error message if fail
@cache.action()
def download():
if (auth.has_permission('read', 'patient', request.vars["id"]) ):
if (auth.has_permission('read', 'patient', request.vars["id"]) ) or (auth.has_permission('admin', 'patient', request.vars["id"]) ):
return response.download(request, db)
else :
res = {"message": "acces denied"}
......
......@@ -146,9 +146,6 @@ db.define_table('analysis_file',
Field('analysis_file', 'upload', length=1000000000000))
if db(db.auth_user.id > 0).count() == 0:
id_first_user=""
......
......@@ -97,7 +97,7 @@ analysis_file = analysis.select()
<tr>
<td id="sequence_file_{{=row.sequence_file.id}}"> {{=filename}}</td>
<td> {{if filename != '':}}<a href="{{=URL('download', scheme='https', args=row.sequence_file.data_file)}}" >dl</a>{{pass}}</td>
<td> {{if filename != '':}}<a href="{{=URL('patient','download', scheme='https', args=row.sequence_file.data_file)}}" >dl</a>{{pass}}</td>
<td> {{=row.sequence_file.sampling_date}} </td>
<td> {{=row.sequence_file.info}} </td>
<td onclick="db.call('file/edit', {'id' :'{{=row.sequence_file.id}}', 'patient_id' :'{{=request.vars['id']}}'} )" > e </td>
......
Markdown is supported
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