<commit_before>from flask import Flask, render_template, session, request, redirect, url_for, abort, json
from flask.ext.sqlalchemy import SQLAlchemy
import os
from config import *
import binascii

app = Flask(__name__)
app.secret_key = str(os.urandom(33))
app.config['SQLALCHEMY_DATABASE_URI'] = SQLDB 
db = SQLAlchemy(app)
from functools import wraps

""" session informtation """

# types of media supported (excluding workflow and workflow run)
# and the actual media name it points to
media_type = {}
media_type["substack"] = "substack"
media_type["tbar-ilp"] = "tbar_ilp"
media_type["boundary-ilp"] = "boundary_ilp"
media_type["boundary-h5"] = "boundary_h5"
media_type["segmentation-substack"] = "segmentation_substack"
media_type["groundtruth-substack"] = "groundtruth_substack"
media_type["synapse-json"] = "synapse_json"
rmedia_type = dict((reversed(item) for item in media_type.items()))


"""
# core media properties (not currently in media table)
media_property = {}
media_property["description"] = "description"
media_property["file-path"] = "file_system_path"
media_property["date"] = "create_date"
media_property["name"] = "name"

rmedia_property = dict((reversed(item) for item in media_property.items()))

# core workflow properties (not currently in media table)
workflow_property = {}
workflow_property["description"] = "description"
workflow_property["owner"] = "owner"
workflow_property["date"] = "create_date"
workflow_property["name"] = "name"

# core workflow_job properties (not current in media table)
workflow_job_property = {}
workflow_job_property["workflow-version"] = "workflow_version"
workflow_job_property["start-time"] = "create_date"
workflow_job_property["description"] = "description"

"""

# general globals
authorization_stored = {}
NORMAL_REQUEST = 200
BAD_REQUEST = 400


""" end session information """



# wrapper for verifying login
def verify_login(f):
    @wraps(f)
    def wrapper_func(*args, **kwargs):
        try:
            auth = request.authorization
            username = auth.username
            password = auth.password
            if username in authorization_stored:
                username_stored, password_stored = authorization_stored[username]
                if password_stored != password:
                    abort(401)
                username = username_stored
            else:
                ## !! UNCOMMENT IN PRODUCTION 
                #conn = ldap.initialize(SERVER)
                #dn_base = ',ou=People,dc=janelia,dc=org'
                #dn = 'cn='+request.form['username']+dn_base
                #pw = request.form['password']
                #r = conn.bind_s(dn, pw, ldap.AUTH_SIMPLE)
            
                # !! COMMENT OUT -- dummy check for now
                if username != "plazas" or password != "password":
                    abort(401)
        except: 
            abort(401)

        if request.method == 'POST' or request.method == 'DELETE' or request.method == 'PUT':
            try:
                results = db.engine.execute('SELECT user_property.value as perm FROM ' +
                        'user_property JOIN user ON user.id = user_property.user_id JOIN ' + 
                        'cv_term ON cv_term.id = user_property.type_id WHERE cv_term.name ' +
                        '= "workflow_run" and user.name = "' + username + '";')

                result =  results.first()
                if result is None or result["perm"] != '1':
                    abort(401)
            except Exception, e:
                abort(401) 

        return f(username, *args, **kwargs)<commit_msg>authentification now working, mysql and ldap access now working<commit_after>from flask import Flask, render_template, session, request, redirect, url_for, abort, json
from flask.ext.sqlalchemy import SQLAlchemy
import os
from config import *
import binascii
import ldap

app = Flask(__name__)
app.secret_key = str(os.urandom(33))
app.config['SQLALCHEMY_DATABASE_URI'] = SQLDB 
db = SQLAlchemy(app)
from functools import wraps

""" session informtation """

# types of media supported (excluding workflow and workflow run)
# and the actual media name it points to
media_type = {}
media_type["substack"] = "substack"
media_type["tbar-ilp"] = "tbar_ilp"
media_type["boundary-ilp"] = "boundary_ilp"
media_type["boundary-h5"] = "boundary_h5"
media_type["segmentation-substack"] = "segmentation_substack"
media_type["groundtruth-substack"] = "groundtruth_substack"
media_type["synapse-json"] = "synapse_json"
rmedia_type = dict((reversed(item) for item in media_type.items()))


"""
# core media properties (not currently in media table)
media_property = {}
media_property["description"] = "description"
media_property["file-path"] = "file_system_path"
media_property["date"] = "create_date"
media_property["name"] = "name"

rmedia_property = dict((reversed(item) for item in media_property.items()))

# core workflow properties (not currently in media table)
workflow_property = {}
workflow_property["description"] = "description"
workflow_property["owner"] = "owner"
workflow_property["date"] = "create_date"
workflow_property["name"] = "name"

# core workflow_job properties (not current in media table)
workflow_job_property = {}
workflow_job_property["workflow-version"] = "workflow_version"
workflow_job_property["start-time"] = "create_date"
workflow_job_property["description"] = "description"

"""

# general globals
authorization_stored = {}
# hard coded authorization. Turning this off since all authorization should go through ldap
#authorization_stored["plazas"] = "password"
NORMAL_REQUEST = 200
BAD_REQUEST = 400


""" end session information """



# wrapper for verifying login
def verify_login(f):
    @wraps(f)
    def wrapper_func(*args, **kwargs):
        try:
            auth = request.authorization
            username = auth.username
            password = auth.password
            if username in authorization_stored:
                password_stored = authorization_stored[username]
                if password_stored != password:
                    print "error, password does not match"
                    abort(401)                
            else:
                # ldap authentification
                try:
                    conn = ldap.initialize(SERVER)
                    dn_base = ',ou=People,dc=janelia,dc=org'
                    dn = 'cn='+username+dn_base
                    pw = password
                    r = conn.bind_s(dn, pw, ldap.AUTH_SIMPLE)
                    # Working Example of how to search Application Roles in Ldap
                    search_base = 'cn=DashboardAdmin,ou=FlyEM,ou=ApplicationRoles,dc=janelia,dc=org'
                    filter = 'cn=*'
                    attr = ['member']
                    search_results = conn.search_s(search_base, ldap.SCOPE_BASE, filter, attr)
                    base, admins = search_results.pop()
                    access = 0
                    for i in admins['member']:
                        #print i #shows dn in ldap group
                        if i == dn:
                            access = 1
                    if access == 1:
                        print "Access allowed to application"
                    else:
                        print "User does not have access to application"
                        abort(401)
                except:
                    error='Error: bad ldap username/password'
                    print error
                    abort(401)
        except Exception, e:
            print "error with authentification. exiting"
            print e
            abort(401)

        if request.method == 'POST' or request.method == 'DELETE' or request.method == 'PUT':
            try:
                sql_query = ('SELECT user_property.value as perm FROM ' +
                             'user_property JOIN user ON user.id = user_property.user_id JOIN ' +
                             'cv_term ON cv_term.id = user_property.type_id WHERE cv_term.name ' +
                             '= "workflow_run" and user.name = "' + username + '";')
                results = db.engine.execute(sql_query);
                result =  results.first()
                #print result
                if result is None or result["perm"] != '1':
                    abort(401)
                print "Access to workflow allowed"
            except Exception, e:
                print e
                abort(401)
                
        return f(username, *args, **kwargs)
{'fraction_non_alphanumeric': 0.1037280959661296, 'fraction_numerical': 0.006821121956956369, 'mean_word_length': 2.422132796780684, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6313963', 'n_tokens_mistral': 2487, 'n_tokens_neox': 2307, 'n_words': 604}