Commit 63893c5e authored by Julian Rother's avatar Julian Rother
Browse files

Commit changes to after moving parts to

parent bb104174
from flask import *
from flask import Flask, g, request, url_for, redirect, session, render_template, flash
from functools import wraps
import datetime
import sqlite3
import os
import re
app = Flask(__name__)
config = app.config
config['DB_SCHEMA'] = 'db_schema.sql'
config['DB_DATA'] = 'db_example.sql'
......@@ -17,110 +15,17 @@ config['SQLITE_INIT_SCHEMA'] = True
config['SQLITE_INIT_DATA'] = False
config['DEBUG'] = False
config['VIDEOPREFIX'] = ''
if __name__ == '__main__':
config['SQLITE_INIT_DATA'] = True
config['DEBUG'] = True
config.from_pyfile('', silent=True)
app.jinja_env.globals['videoprefix'] = config['VIDEOPREFIX']
mod_endpoints = []
if config['DB_ENGINE'] == 'sqlite':
created = not os.path.exists(config['SQLITE_DB'])
db = sqlite3.connect(config['SQLITE_DB'])
cur = db.cursor()
if config['SQLITE_INIT_SCHEMA']:
if config['SQLITE_INIT_DATA'] and created:
# Row wrapper for sqlite
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
if type(row[idx]) == str:
d[col[0].split('.')[-1]] = row[idx].replace('\\n','\n').replace('\\r','\r')
d[col[0].split('.')[-1]] = row[idx]
return d
def query(operation, *params):
if config['DB_ENGINE'] == 'mysql':
import mysql.connector
if 'db' not in g or not g.db.is_connected():
g.db = mysql.connector.connect(user=config['MYSQL_USER'], password=config['MYSQL_PASSWD'], host=config['MYSQL_HOST'], database=config['MYSQL_DB'])
if not hasattr(request, 'db'):
request.db = g.db.cursor(dictionary=True)
request.db.execute(operation.replace('?', '%s'), params)
elif config['DB_ENGINE'] == 'sqlite':
if 'db' not in g:
g.db = sqlite3.connect(config['SQLITE_DB'])
g.db.row_factory = dict_factory
g.db.isolation_level = None
if not hasattr(request, 'db'):
request.db = g.db.cursor()
request.db.execute(operation, params)
return []
return request.db.fetchall()
def commit_db(*args):
if hasattr(request, 'db'):
def searchquery(text, columns, match, tables, suffix, *suffixparams):
params = []
subexprs = []
words = text.split(' ')
prio = len(words)+1
for word in words:
if word == '' or word.isspace():
matchexpr = ' OR '.join(['%s LIKE ?'%column for column in match])
subexprs.append('SELECT %s, %s AS _prio FROM %s WHERE %s'%(columns, str(prio), tables, matchexpr))
params += ['%'+word+'%']*len(match)
prio -= 1
if subexprs == []:
return []
expr = 'SELECT *,SUM(_prio) AS _score FROM (%s) AS _tmp %s'%(' UNION '.join(subexprs), suffix)
return query(expr, *params, *suffixparams)
LDAP_USERRE = re.compile(r'[^a-z0-9]')
notldap = {
'videoag':('videoag', ['users','videoag'], {'uid': 'videoag', 'givenName': 'Video', 'sn': 'Geier'}),
'gustav':('passwort', ['users'], {'uid': 'gustav', 'givenName': 'Gustav', 'sn': 'Geier'})
config.from_pyfile('', silent=True)
def ldapauth(user, password):
user = LDAP_USERRE.sub(r'', user.lower())
if 'LDAP_HOST' in config:
import ldap3
conn = ldap3.Connection(config['LDAP_HOST'], 'uid=%s,ou=users,dc=fsmpi,dc=rwth-aachen,dc=de'%user, password, auto_bind=True)
if"ou=groups,dc=fsmpi,dc=rwth-aachen,dc=de", "(&(cn=*)(memberUid=%s))"%user, attributes=['cn']):
groups = [ for e in conn.entries]
return user, groups
except ldap3.core.exceptions.LDAPBindError:
elif config.get('DEBUG') and user in notldap and password == notldap[user][0]:
return user, notldap[user][1]
return None, []
from db import query, searchquery, ldapauth, ldapget
def ldapget(user):
user = LDAP_USERRE.sub(r'', user.lower())
if 'LDAP_HOST' in config:
import ldap3
conn = ldap3.Connection('ldaps://', auto_bind=True)"ou=users,dc=fsmpi,dc=rwth-aachen,dc=de", "(uid=%s)"%user,
e = conn.entries[0]
return {'uid': user, 'givenName': e.givenName.value, 'sn'}
return notldap[user][2]
app.jinja_env.globals['videoprefix'] = config['VIDEOPREFIX']
mod_endpoints = []
def ismod(*args):
return ('user' in session)
......@@ -136,7 +41,6 @@ def mod_required(func):
return redirect(url_for('login', ref=request.url))
return func(*args, **kwargs)
return decorator
app.jinja_env.globals['navbar'] = []
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