Beispiel #1
0
def toggle_prefs():
    # if re.search(r'^\d+$', request.form['user_id']) and \
    #        re.search(r'^[ft]$', request.form['pref_value']):
    if re.search(r'^[ft]$', request.form['pref_value']) and \
            re.search(r'^(email_pref|lovd_export)$', request.form['field']):
        # mobiuser_id = request.form['user_id']
        pref = request.form['pref_value']
        field = request.form['field']
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "UPDATE mobiuser SET {0} = '{1}' WHERE id = '{2}'".format(field, pref, g.user['id'])
        )
        db.commit()
        return 'ok'

    md_utilities.send_error_email(
        md_utilities.prepare_email_html(
            'MobiDetails error',
            '<p>MD failed to modify a user prefs for {0}. User id: {1} to {2}</p>'.format(
                request.form['field'],
                g.user['id'],
                request.form['pref_value']
            )
        ),
        '[MobiDetails - User prefs Error]'
    )
    return md_utilities.danger_panel('', 'Sorry, something went wrong when trying to update your preferences.\
                                              An admin has been warned. Please try again later.')
Beispiel #2
0
def test_modif_class(client, app, auth, vf_id, acmg, acmg_com, return_value,
                     status_code2):
    assert client.get('/modif_class').status_code == 405
    with app.app_context():
        response = client.post('/modif_class',
                               data=dict(variant_id=vf_id,
                                         acmg_select=acmg,
                                         acmg_comment=acmg_com),
                               follow_redirects=True)
        assert b'check_login_form' in response.get_data(
        )  # means we are in the login page
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT password FROM mobiuser WHERE email = '*****@*****.**'"
        )
        res = curs.fetchone()
        # login(client, '*****@*****.**', res['password'])
        auth.login('*****@*****.**', res['password'])
        response = client.post('/modif_class',
                               data=dict(variant_id=vf_id,
                                         acmg_select=acmg,
                                         acmg_comment=acmg_com),
                               follow_redirects=True)
        assert response.status_code == status_code2
Beispiel #3
0
def remove_class():
    if re.search(r'^\d+$', request.form['variant_id']) and \
            re.search(r'^\d+$', request.form['acmg_class']):
        variant_id = request.form['variant_id']
        acmg_class = request.form['acmg_class']
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        try:
            curs.execute(
                "DELETE FROM class_history WHERE \
                    variant_feature_id = %s AND acmg_class = %s \
                    AND mobiuser_id = %s",
                (variant_id, acmg_class, g.user['id'])
            )
            db.commit()
            return 'ok'
        except Exception as e:
            md_utilities.send_error_email(
                md_utilities.prepare_email_html(
                    'MobiDetails error',
                    '<p>Variant class deletion failed for {0} with args: {1}</p>'.format(variant_id, e.args)
                ),
                '[MobiDetails - MD variant class Error]'
            )
    return md_utilities.danger_panel('', 'Sorry, something went wrong with the deletion of this annotation. An admin has been warned.')
Beispiel #4
0
def index():
    # print(app.config['RUN_MODE'])
    # check vv
    md_api_url = '{0}{1}'.format(request.host_url[:-1],
                                 url_for('api.check_vv_instance'))
    vv_instance = json.loads(
        http.request('GET', md_api_url).data.decode('utf-8'))
    # count genes
    db = get_db()
    curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    curs.execute("""
        SELECT COUNT(DISTINCT(gene_symbol)) AS gene, COUNT(refseq) AS transcript
        FROM gene
        WHERE variant_creation = 'ok'
        """)
    res = curs.fetchone()
    if res is None:
        close_db()
        error = 'There is a problem with the number of genes.'
        flash(error, 'w3-pale-red')
        md_utilities.send_error_email(
            md_utilities.prepare_email_html(
                'MobiDetails PostGreSQL error',
                '<p>There is a problem with the number of genes.\
<br /> in {}</p>'.format(os.path.basename(__file__))),
            '[MobiDetails - PostGreSQL Error]')
    else:
        close_db()
        return render_template('md/index.html',
                               run_mode=md_utilities.get_running_mode(),
                               nb_genes=res['gene'],
                               nb_isoforms=res['transcript'],
                               vv_instance=vv_instance)
Beispiel #5
0
def favourite():
    if re.search(r'^\d+$', request.form['vf_id']):
        vf_id = request.form['vf_id']
        if vf_id is None:
            flash('Cannot mark a variant without id! Please contact us.', 'w3-pale-red')
            return 'notok'
        # print(vf_id)
        # g.user['id']
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        if request.form['marker'] == 'mark':
            curs.execute(
                "INSERT INTO mobiuser_favourite (mobiuser_id, feature_id) VALUES (%s, %s)",
                (g.user['id'], vf_id)
            )
        else:
            curs.execute(
                "DELETE FROM mobiuser_favourite WHERE mobiuser_id = %s AND feature_id = %s",
                (g.user['id'], vf_id)
            )
        db.commit()
        close_db()
        return 'ok'
    else:
        flash('Cannot mark a variant without id! Please contact us.', 'w3-pale-red')
        return 'notok'
Beispiel #6
0
def api_variant_exists(variant_ghgvs=None):
    if variant_ghgvs is None:
        return jsonify(mobidetails_error='No variant submitted')
    match_object = re.search(r'^([Nn][Cc]_0000\d{2}\.\d{1,2}):g\.(.+)', urllib.parse.unquote(variant_ghgvs))
    if match_object:
        db = get_db()
        # match_object = re.search(r'^([Nn][Cc]_0000\d{2}\.\d{1,2}):g\.(.+)', variant_ghgvs)
        # res_common = md_utilities.get_common_chr_name(db, match_object.group(1))
        chrom, genome_version = md_utilities.get_common_chr_name(db, match_object.group(1).upper())
        pattern = match_object.group(2)
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT feature_id FROM variant WHERE chr = %s AND g_name = %s AND genome_version = %s",
            (chrom, pattern, genome_version)
        )
        res = curs.fetchone()
        if res is not None:
            return jsonify(mobidetails_id=res['feature_id'], url='{0}{1}'.format(
                request.host_url[:-1], url_for('md.variant', variant_id=res['feature_id'])
            ))
            # return jsonify(mobidetails_id=res['feature_id'])
        else:
            # return jsonify("SELECT feature_id FROM variant WHERE g_name = 'chr{0}:g.{1}' AND genome_version = '{2}'".format(chrom, pattern, genome_version))
            return jsonify(mobidetails_warning='The variant {} does not exist yet in MD'.format(variant_ghgvs))
    else:
        return jsonify(mobidetails_error='Malformed query {}'.format(variant_ghgvs))
Beispiel #7
0
def variant_list(list_name):
    if len(list_name) < 31 and \
            re.search(r'^[\w]+$', list_name):
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            """
            SELECT a.variant_ids, b.username, a.creation_date, a.list_name
            FROM variants_groups a, mobiuser b
            WHERE a.mobiuser_id = b.id AND list_name = %s
            """, (list_name, ))
        res = curs.fetchone()
        # we've got an ARRAY of variants_ids and want to query on them...
        if res:
            res_ids_string = "("
            for id in res['variant_ids']:
                res_ids_string += "{}, ".format(id)
            res_ids_string = res_ids_string[:-2]
            res_ids_string += ")"
            # print(res_ids_string)
            curs.execute("""
                SELECT a.id, a.c_name, a.p_name, a.gene_symbol, a.refseq, a.creation_user, a.creation_date, b.username
                FROM variant_feature a, mobiuser b
                WHERE  a.creation_user = b.id AND a.id IN {0}
                """.format(res_ids_string))
            variants = curs.fetchall()
            close_db()
            return render_template('md/variant_multiple.html',
                                   variants=variants,
                                   unique_url_info=res)
        else:
            close_db()
            return render_template('errors/404.html'), 404
    else:
        return render_template('errors/404.html'), 404
Beispiel #8
0
def test_send_var_message(client, app, auth, receiver_id, message_object,
                          message, status_code):
    assert client.get('/send_var_message').status_code == 405
    with app.app_context():
        response = client.post('/send_var_message',
                               data=dict(receiver_id=receiver_id,
                                         message_object=message_object,
                                         message=message),
                               follow_redirects=True)
        assert b'check_login_form' in response.get_data(
        )  # means we are in the login page
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT password FROM mobiuser WHERE email = '*****@*****.**'"
        )
        res = curs.fetchone()
        # login(client, '*****@*****.**', res['password'])
        auth.login('*****@*****.**', res['password'])
        response = client.post('/send_var_message',
                               data=dict(receiver_id=receiver_id,
                                         message_object=message_object,
                                         message=message),
                               follow_redirects=True)
        assert response.status_code == status_code
Beispiel #9
0
def activate(mobiuser_id, api_key):
    if isinstance(mobiuser_id, int) and \
            isinstance(api_key, str):
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT id, api_key, activated FROM mobiuser WHERE id = %s AND api_key = %s",
            (mobiuser_id, api_key))
        user = curs.fetchone()
        if user is None:
            message_body = '<p>Account activation exception</p><p>Recived API key: {0} and\
                       mobiuser_id: {1} from {2}'.format(
                api_key, mobiuser_id, request.remote_addr)
            md_utilities.send_error_email(
                md_utilities.prepare_email_html('MobiDetails error',
                                                message_body),
                '[MobiDetails - Activation Error]')
            flash(
                'API key and user id do not seem to fit. An admin has been warned',
                'w3-pale-red')
            return render_template('md/index.html')
        else:
            if user['activated'] is False and \
                    user['api_key'] == api_key and \
                    user['id'] == mobiuser_id:
                curs.execute(
                    "UPDATE mobiuser SET activated = 't' WHERE id = %s AND api_key = %s",
                    (user['id'], user['api_key']))
                db.commit()
                flash(
                    'Your account has been activated, you may now log in using your email address.',
                    'w3-pale-green')
                return render_template('auth/login.html')
    return render_template('md/unknown.html')
Beispiel #10
0
def test_intervar(client, app):
    assert client.get('/intervar').status_code == 405
    with app.app_context():
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT a.genome_version, a.chr, a.pos, a.pos_ref, a.pos_alt, b.gene_name[1] as gene FROM variant a, variant_feature b WHERE \
            a.feature_id = b.id AND a.genome_version = 'hg19' AND b.dna_type = 'substitution' AND \
            b.start_segment_type = 'exon' AND c_name !~ '^[\*-]' AND p_name !~ '\?' ORDER BY random() LIMIT 5"
        )
        res = curs.fetchall()
        for values in res:
            data_dict = dict(genome=values['genome_version'],
                             chrom=values['chr'],
                             pos=values['pos'],
                             ref=values['pos_ref'],
                             alt=values['pos_alt'],
                             gene=values['gene'])
            response = client.post('/intervar', data=data_dict)
            assert response.status_code == 200
            possible = [
                b'athogenic', b'lassified', b'enign', b'ncertain',
                b'wintervar looks down'
            ]
            # https://stackoverflow.com/questions/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python/6531704#6531704
            print(res)
            print(response.get_data())
            assert any(test in response.get_data() for test in possible)
Beispiel #11
0
def autocomplete_var():
    query = request.form['query_engine']
    gene = request.form['gene']
    # match_object = re.search(r'^c\.([\w\d>_\*-]+)', query)
    variant_regexp = md_utilities.regexp['variant']
    match_object = re.search(rf'^c\.({variant_regexp})', query)
    if match_object:
        md_query = match_object.group(1)
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT c_name FROM variant_feature WHERE gene_name[1] = '{0}' AND c_name LIKE '{1}%' ORDER BY c_name LIMIT 10".format(
                gene, md_query
            )
        )
        res = curs.fetchall()
        result = []
        for var in res:
            result.append('c.{}'.format(var[0]))
        # print(json.dumps(result))
        # print("SELECT c_name FROM variant_feature WHERE gene_name[1] = '{0}' AND c_name LIKE '{1}%' ORDER BY c_name LIMIT 10".format(gene, md_query))
        if result is not None:
            return json.dumps(result)
        else:
            return ('', 204)
    return ('', 204)
Beispiel #12
0
def test_gene_page(client, app):
    with app.app_context():
        db = get_db()
        curs = db.cursor()
        curs.execute("SELECT name[1] FROM gene LIMIT 50", )
        res = curs.fetchall()
        for name in res:
            assert client.get('/gene/{}'.format(name[0])).status_code == 200
Beispiel #13
0
def test_create_var_vv(client, app):
    with app.app_context():
        g = fake_g_obj()
        error_dict = md_utilities.create_var_vv('NM_206933.2:c.100_101delinsA',
                                                'USH2A', 'NM_206933',
                                                'c.100_101delinsA',
                                                'c.100_101delinsA', '2',
                                                vv_dict, 'test', get_db(), g)
        assert isinstance(error_dict['mobidetails_id'], int)
Beispiel #14
0
def api_gene(gene_hgnc=None):
    if gene_hgnc is None:
        return jsonify(mobidetails_error='No gene submitted')
    if re.search(r'[^\w\.-]', gene_hgnc):
        return jsonify(
            mobidetails_error='Invalid gene submitted ({})'.format(gene_hgnc))
    research = gene_hgnc
    search_id = 1
    match_obj = re.search(r'(NM_\d+)\.?\d?', gene_hgnc)
    if match_obj:
        # we have a RefSeq accession number
        research = match_obj.group(1)
        search_id = 2
    db = get_db()
    curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if re.search(r'^\d+$', research):
        curs.execute("SELECT * FROM gene WHERE hgnc_id = %s", (research, ))
    else:
        curs.execute("SELECT * FROM gene WHERE name[%s] = %s",
                     (search_id, research))
    res = curs.fetchall()
    d_gene = {}
    if res:
        for transcript in res:
            if 'HGNC Name' not in d_gene:
                d_gene['HGNC Name'] = transcript['name'][0]
            if 'HGNC ID' not in d_gene:
                d_gene['HGNC ID'] = transcript['hgnc_id']
            if 'chr' not in d_gene:
                d_gene['Chr'] = transcript['chr']
            if 'strand' not in d_gene:
                d_gene['Strand'] = transcript['strand']
            if 'ng' not in d_gene:
                if transcript['ng'] == 'NG_000000.0':
                    d_gene['RefGene'] = 'No RefGene in MobiDetails'
                else:
                    d_gene['RefGene'] = transcript['ng']
            refseq = '{0}.{1}'.format(transcript['name'][1],
                                      transcript['nm_version'])
            d_gene[refseq] = {
                'canonical': transcript['canonical'],
            }
            if 'RefProtein' not in d_gene[refseq]:
                if transcript['np'] == 'NP_000000.0':
                    d_gene[refseq][
                        'RefProtein'] = 'No RefProtein in MobiDetails'
                else:
                    d_gene[refseq]['RefProtein'] = transcript['np']
            if 'UNIPROT' not in d_gene[refseq]:
                d_gene[refseq]['UNIPROT'] = transcript['uniprot_id']
            if 'variantCreationTag' not in d_gene[refseq]:
                d_gene[refseq]['variantCreationTag'] = transcript[
                    'variant_creation']
        return jsonify(d_gene)
    else:
        return jsonify(
            mobidetails_warning='Unknown gene ({})'.format(gene_hgnc))
Beispiel #15
0
def get_generic_api_key():
    db = get_db()
    curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    curs.execute(
        "SELECT api_key FROM mobiuser WHERE email = '*****@*****.**'"
    )
    res = curs.fetchone()
    if res is not None:
        return res['api_key']
Beispiel #16
0
def autocomplete():
    query = request.form['query_engine']
    db = get_db()
    curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    # match_object = re.search(r'^c\.([\w\d>_\*-]+)', query)
    match_obj = re.search(rf'^rs(\d+)$', query)
    if match_obj:
        md_query = match_obj.group(1)
        curs.execute(
            "SELECT dbsnp_id FROM variant_feature WHERE dbsnp_id LIKE '{}%' ORDER BY dbsnp_id LIMIT 10".format(md_query)
        )
        res = curs.fetchall()
        result = []
        for var in res:
            result.append('rs{}'.format(var[0]))
        if result is not None:
            return json.dumps(result)
        else:
            return ('', 204)
    variant_regexp = md_utilities.regexp['variant']
    match_object = re.search(rf'^c\.({variant_regexp})', query)
    if match_object:
        md_query = match_object.group(1)
        curs.execute(
            "SELECT DISTINCT(c_name) FROM variant_feature WHERE c_name LIKE '{}%' ORDER BY c_name LIMIT 10".format(md_query)
        )
        res = curs.fetchall()
        result = []
        for var in res:
            result.append('c.{}'.format(var[0]))
        # print(json.dumps(result))
        # print("SELECT c_name FROM variant_feature WHERE gene_name[1] = '{0}' AND c_name LIKE '{1}%' ORDER BY c_name LIMIT 10".format(gene, md_query))
        if result is not None:
            return json.dumps(result)
        else:
            return ('', 204)
    i = 1
    if re.search(r'^[Nn][Mm]_.+', query):
        i = 2
        query = query.upper()
    elif not re.search(r'orf', query):
        query = query.upper()
    curs.execute(
        "SELECT DISTINCT name[1] FROM gene WHERE name[{0}] LIKE '%{1}%' ORDER BY name[1] LIMIT 5".format(i, query)
    )
    res = curs.fetchall()
    result = []
    for gene in res:
        result.append(gene[0])
    # print("SELECT DISTINCT name[1] FROM gene WHERE name[{0}] LIKE '%{1}%' ORDER BY name[1] LIMIT 5".format(i, query))
    if result is not None:
        return json.dumps(result)
    else:
        return ('', 204)
Beispiel #17
0
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute("SELECT * FROM mobiuser WHERE id = %s", (user_id, ))
        g.user = curs.fetchone()
    close_db()
Beispiel #18
0
def test_variant_page(client, app):
    with app.app_context():
        db = get_db()
        curs = db.cursor()
        curs.execute(
            "SELECT id FROM variant_feature WHERE c_name <> 'c.1A>T' ORDER BY random() LIMIT 100"  # WHERE prot_type = 'missense'",  #  ORDER BY random() LIMIT 500
        )
        res = curs.fetchall()
        for variant_id in res:
            print(variant_id)
            assert client.get('/variant/{}'.format(
                variant_id[0])).status_code == 200
Beispiel #19
0
def forgot_pass():
    if (md_utilities.get_running_mode() == 'maintenance'):
        return render_template('md/index.html',
                               run_mode=md_utilities.get_running_mode())
    if request.method == 'GET':
        return render_template('auth/forgot_pass.html')
    elif request.method == 'POST':
        error = None
        email = request.form['email']
        if not re.search(r'^[a-zA-Z0-9\._%\+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
                         email):
            error = 'The email address does not look valid.'
            flash(error, 'w3-pale-red')
            return render_template('auth/forgot_pass.html')
        else:
            db = get_db()
            curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
            curs.execute("SELECT * FROM mobiuser WHERE email = %s", (email, ))
            user = curs.fetchone()
            if user is None:
                close_db()
                error = """
                Your email address {} seems to be unknown by the system.
                """.format(email)
                flash(error, 'w3-pale-red')
                return render_template('auth/forgot_pass.html')
            # message, mail_object, receiver
            md_utilities.send_email(
                md_utilities.prepare_email_html(
                    'MobiDetails - Reset your password', """
                    Dear {0},
                    <p>please follow the link below to reset your MobiDetails password:</p>
                    <p><a href="{1}{2}" title="Reset your MD password">
                    Reset your MD password</a></p>
                    <p>If you do not know why you receive this email,
                    do not follow the link and please alert
                    [email protected].</p><br />
                    """.format(
                        user['username'], request.host_url.rstrip('/'),
                        url_for('auth.reset_password',
                                mobiuser_id=user['id'],
                                api_key=user['api_key'],
                                ts=datetime.timestamp(datetime.now()))),
                    False), '[MobiDetails - Password reset]', [email])
            flash(
                """
                Please check your e-mail inbox.
                You should have received a message with a link
                to reset your password
                """, 'w3-pale-green')
            close_db()
            return render_template('auth/forgot_pass.html')
    return render_template('md/unknown.html')
Beispiel #20
0
def test_lovd(client, app):
    assert client.get('/lovd').status_code == 405
    with app.app_context():
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT a.genome_version, a.chr, a.g_name, b.c_name FROM variant a, variant_feature b WHERE \
            a.feature_id = b.id AND a.genome_version = 'hg19' ORDER BY random() LIMIT 5"
        )
        res = curs.fetchall()
        for values in res:
            data_dict = dict(genome=values['genome_version'], chrom=values['chr'], g_name=values['g_name'], c_name='c.{}'.format(values['c_name']))
            assert client.post('/lovd', data=data_dict).status_code == 200
Beispiel #21
0
def test_defgen(client, app):
    assert client.get('/defgen').status_code == 405
    with app.app_context():
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT feature_id, genome_version FROM variant OFFSET RANDOM() * (SELECT COUNT(*) FROM variant) LIMIT 50"
        )
        res = curs.fetchall()
        for values in res:
            data_dict = dict(vfid=values['feature_id'], genome=values['genome_version'])
            response = client.post('/defgen', data=data_dict)
            assert response.status_code == 200
            assert b'Export Variant data to DEFGEN' in response.get_data()
Beispiel #22
0
def test_favourite(client, app, auth, vf_id, status_code):
    assert client.get('/favourite').status_code == 405
    with app.app_context():
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT password FROM mobiuser WHERE email = '*****@*****.**'"
        )
        res = curs.fetchone()
        response = client.post('/favourite', data=dict(vf_id=vf_id), follow_redirects=True)
        print(response.get_data())
        assert b'check_login_form' in response.get_data()  # means we are in the login page
        auth.login('*****@*****.**', res['password'])
        assert client.post('/favourite', data=dict(vf_id=vf_id), follow_redirects=True).status_code == status_code
Beispiel #23
0
def genes():
    db = get_db()
    curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    curs.execute("""
        SELECT DISTINCT(gene_symbol)
        FROM gene
        ORDER BY gene_symbol
        """)
    genes = curs.fetchall()
    close_db()
    if genes:
        return render_template('md/genes.html',
                               run_mode=md_utilities.get_running_mode(),
                               genes=genes)
    else:
        return render_template('md/unknown.html',
                               run_mode=md_utilities.get_running_mode())
Beispiel #24
0
def test_check_api_key(app, api_key, result):
    with app.app_context():
        db = get_db()
        if api_key == '':
            curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
            curs.execute(
                "SELECT api_key FROM mobiuser WHERE email = '*****@*****.**'"
            )
            res = curs.fetchone()
            if res is not None:
                api_key = res['api_key']
        check = md_utilities.check_api_key(db, api_key)
        if 'mobidetails_error' in check:
            assert result == check['mobidetails_error']
        else:
            print(check['mobiuser'])
            assert result == check['mobiuser'][4]
Beispiel #25
0
def send_var_message():
    if re.search(r'^\d+$', request.form['receiver_id']):
        if request.form['message'] != '' and \
                re.search(r'Query\svia\sMobiDetails\sfrom', request.form['message_object']):
            # sender = {}
            receiver = {}
            # variant = request.form['variant_mes']
            # sender['id'] = request.form['sender_id']
            receiver['id'] = request.form['receiver_id']
            message = request.form['message']
            message_object = request.form['message_object']
            db = get_db()
            curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
            # get username and email
            curs.execute(
                "SELECT id, username, email FROM mobiuser WHERE id = %s",
                (receiver['id'])
            )
            # res = curs.fetchall()
            receiver = curs.fetchone()
            message.replace("\n", "<br />")
            message += "<br /><br /><p>You can contact user {0} directly at {1}</p>".format(
                    g.user['username'],
                    g.user['email']
                )
            md_utilities.send_email(
                md_utilities.prepare_email_html(message_object, message, False),
                message_object,
                [receiver['email']]
            )
            return md_utilities.info_panel('Your email has just been sent.', '', '', 'w3-pale-green')
        else:
            return md_utilities.danger_panel('', 'Please complete the message part of the form.')
    md_utilities.send_error_email(
        md_utilities.prepare_email_html(
            'MobiDetails error',
            '<p>An email was not sent from {0} to {1}<br />Variant was {2}<br />Message was:<br />{3}</p>'.format(
                g.user['sender_id'],
                request.form['receiver_id'],
                request.form['variant_mes'],
                request.form['message'])
        ),
        '[MobiDetails - Email Error]'
    )
    return md_utilities.danger_panel('', 'Sorry, something went wrong with this message. An admin has been warned.')
Beispiel #26
0
def test_register(client, app):
    # test register returns no error
    assert client.get('/auth/register').status_code == 200
    response = client.post(
        '/auth/register', data={
            'username': '******', 'password': '******',
            'country': 'a', 'institute': 'a', 'email': '*****@*****.**'
        }
    )
    assert response.status_code == 200

    # test db returns a value
    with app.app_context():
        db = get_db()
        curs = db.cursor()
        curs.execute(
            "SELECT * FROM mobiuser WHERE username = '******'",
        )
        res = curs.fetchone()
        assert res is not None
Beispiel #27
0
def defgen():
    genome_regexp = md_utilities.regexp['genome']
    if re.search(r'^\d+$', request.form['vfid']) and \
            re.search(rf'^{genome_regexp}$', request.form['genome']):
        variant_id = request.form['vfid']
        genome = request.form['genome']
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        # get all variant_features and gene info
        curs.execute(
            "SELECT * FROM variant_feature a, variant b, gene c WHERE \
            a.id = b.feature_id AND a.gene_name = c.name AND a.id = '{0}'\
            AND b.genome_version = '{1}'".format(variant_id, genome)
        )
        vf = curs.fetchone()
        file_content = "GENE;VARIANT;A_ENREGISTRER;ETAT;RESULTAT;VARIANT_P;VARIANT_C;ENST;NM;POSITION_GENOMIQUE;CLASSESUR5;CLASSESUR3;COSMIC;RS;REFERENCES;CONSEQUENCES;COMMENTAIRE;CHROMOSOME;GENOME_REFERENCE;NOMENCLATURE_HGVS;LOCALISATION;SEQUENCE_REF;LOCUS;ALLELE1;ALLELE2\r\n"

        file_content += "{0};{1}.{2}:c.{3};;;;p.{4};c.{3};{5};{1}.{2};{6};;;;rs{7};;{8};;chr{9};{10};chr{9}:g.{11};{12} {13};;;;\r\n".format(
            vf['gene_name'][0], vf['gene_name'][1], vf['nm_version'], vf['c_name'], vf['p_name'], vf['enst'], vf['pos'],
            vf['dbsnp_id'], vf['prot_type'], vf['chr'], genome, vf['g_name'], vf['start_segment_type'], vf['start_segment_number']
        )
        # print(file_content)
        app_path = os.path.dirname(os.path.realpath(__file__))
        file_loc = "defgen/{0}-{1}-{2}{3}-{4}.csv".format(genome, vf['chr'], vf['pos'], vf['pos_ref'], vf['pos_alt'])
        defgen_file = open("{0}/static/{1}".format(app_path, file_loc), "w")
        defgen_file.write(file_content)
        close_db()
        return render_template('ajax/defgen.html', variant="{0}.{1}:c.{2}".format(
            vf['gene_name'][1], vf['nm_version'], vf['c_name']), defgen_file=file_loc, genome=genome)
    else:
        # close_db()
        md_utilities.send_error_email(
            md_utilities.prepare_email_html(
                'MobiDetails Ajax error',
                '<p>DefGen file generation failed in {} (no variant_id)</p>'.format(
                    os.path.basename(__file__)
                )
            ),
            '[MobiDetails - Ajax Error]'
        )
        return '<div class="w3-blue w3-ripple w3-padding-16 w3-large w3-center" style="width:100%">Impossible to create DEFGEN file</div>'
Beispiel #28
0
def test_litvar(client, app):
    assert client.get('/litVar').status_code == 405
    with app.app_context():
        db = get_db()
        curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute(
            "SELECT dbsnp_id FROM variant_feature WHERE dbsnp_id IS NOT NULL ORDER BY random() LIMIT 5"
        )
        # https://stackoverflow.com/questions/5297396/quick-random-row-selection-in-postgres
        # discussion on how to select random rows in postgresql
        res = curs.fetchall()
        for values in res:
            response = client.post('/litVar', data=dict(rsid='rs{0}'.format(values['dbsnp_id'])))
            assert response.status_code == 200
            possible = [
                b'<div class="w3-blue w3-ripple w3-padding-16 w3-large w3-center" style="width:100%;">No match in Pubmed using LitVar API</div>',
                b'PubMed links of articles citing this variant'
            ]
            # https://stackoverflow.com/questions/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python/6531704#6531704
            print(values['dbsnp_id'])
            print(response.get_data())
            assert any(test in response.get_data() for test in possible)
Beispiel #29
0
def check_api_key(api_key=None):
    api_key = md_utilities.get_post_param(request, 'api_key')
    # if request.args.get('api_key'):
    #     api_key = request.args.get('api_key', type=str)
    # elif 'api_key' in request.form:
    #     api_key = request.form['api_key']
    if not api_key:
        return jsonify(mobidetails_error='I cannot fetch the right parameters',
                       api_key_pass_check=False,
                       api_key_status='irrelevant')
    db = get_db()
    response = md_utilities.check_api_key(db, api_key)
    if 'mobiuser' in response:
        if response['mobiuser']['activated'] is True:
            return jsonify(api_key_submitted=api_key,
                           api_key_pass_check=True,
                           api_key_status='active')
        return jsonify(api_key_submitted=api_key,
                       api_key_pass_check=True,
                       api_key_status='inactive')
    return jsonify(api_key_submitted=api_key,
                   api_key_pass_check=False,
                   api_key_status='irrelevant')
Beispiel #30
0
def reset_password():
    if request.method == 'GET':
        if re.search(r'^\d+$', request.args.get('mobiuser_id')) and \
                re.search(r'^[\d\.]+$', request.args.get('ts')):
            mobiuser_id = request.args.get('mobiuser_id')
            api_key = request.args.get('api_key')
            original_timestamp = request.args.get('ts')
            # we will keep the link alive for 30 minutes i.e. 1800 s
            if float(float(datetime.timestamp(datetime.now())) - float(original_timestamp)) > 1800 or \
               float(float(datetime.timestamp(datetime.now())) - float(original_timestamp)) < 0:
                flash('This link is outdated. Please try again the procedure.',
                      'w3-pale-red')
                return render_template('auth/login.html')
            db = get_db()
            curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
            curs.execute(
                "SELECT id, api_key, activated FROM mobiuser WHERE id = %s AND api_key = %s",
                (mobiuser_id, api_key))
            user = curs.fetchone()
            if user is None:
                message_body = '<p>Password reset exception</p><p>Received API key: {0} and\
                           mobiuser_id: {1} from {2}'.format(
                    api_key, mobiuser_id, request.remote_addr)
                md_utilities.send_error_email(
                    md_utilities.prepare_email_html('MobiDetails error',
                                                    message_body),
                    '[MobiDetails - Password reset Error]')
                flash(
                    'API key and user id do not seem to fit. An admin has been warned',
                    'w3-pale-red')
                return render_template('auth/forgot_pass.html')
            else:
                return render_template('auth/reset_pass.html',
                                       mobiuser_id=mobiuser_id,
                                       api_key=api_key)
        else:
            message_body = '<p>Password reset exception</p><p>Received timestamp: {0} and\
                        mobiuser_id: {1} from {2}'.format(
                request.args.get('ts'), request.args.get('mobiuser_id'),
                request.remote_addr)
            md_utilities.send_error_email(
                md_utilities.prepare_email_html('MobiDetails error',
                                                message_body),
                '[MobiDetails - Password reset Error]')
            flash('Some parameters are not legal. An admin has been warned',
                  'w3-pale-red')
            return render_template('auth/forgot_pass.html')
    elif request.method == 'POST':
        mobiuser_id = request.form['mobiuser_id']
        api_key = request.form['api_key']
        password = request.form['password']
        error = None
        if len(password) < 8 or not re.match('[a-zA-Z0-9]+', password):
            error = 'Password should be at least 8 characters and mix at least letters (upper and lower case) and numbers.'
        else:
            db = get_db()
            curs = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
            curs.execute(
                "UPDATE mobiuser SET password= %s WHERE id = %s AND api_key = %s",
                (generate_password_hash(password), mobiuser_id, api_key))
            db.commit()
            flash('Your password has just been reset.', 'w3-pale-green')
            return render_template('auth/login.html')
        if error is not None:
            flash(error, 'w3-pale-red')
            return render_template('auth/reset_pass.html',
                                   mobiuser_id=mobiuser_id,
                                   api_key=api_key)
    return render_template('md/unknown.html')