From 7a3ba90e2ce219a8aadc4942d9c1fc97a4426db3 Mon Sep 17 00:00:00 2001
From: Julian Rother <julianr@fsmpi.rwth-aachen.de>
Date: Tue, 11 Oct 2016 15:55:30 +0200
Subject: [PATCH] Replaced 'auth' with perm to reduce confusion

---
 db_schema.sql         |  11 ++---
 server.py             | 110 +++++++++++++++++++++---------------------
 static/moderator.js   |  44 ++++++++---------
 templates/course.html |   2 +-
 templates/macros.html |   2 +-
 5 files changed, 85 insertions(+), 84 deletions(-)

diff --git a/db_schema.sql b/db_schema.sql
index d798377..06b5c08 100644
--- a/db_schema.sql
+++ b/db_schema.sql
@@ -105,15 +105,15 @@ CREATE TABLE IF NOT EXISTS `places` (
   `campus_room` varchar(20) NOT NULL,
   `campus_name` varchar(30) NOT NULL
 );
-CREATE TABLE IF NOT EXISTS `auth_data` (
-	`auth_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
+CREATE TABLE IF NOT EXISTS `perm` (
+	`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
 	`deleted` INTEGER NOT NULL DEFAULT '0',
 	`course_id` INTEGER,
 	`lecture_id` INTEGER,
 	`video_id` INTEGER,
-	`auth_type` varchar(10),
-	`auth_param` varchar(127),
-	`auth_param2` varchar(127),
+	`type` varchar(10),
+	`param1` varchar(127),
+	`param2` varchar(127),
 	`time_created` datetime NOT NULL,
 	`time_updated` datetime NOT NULL,
 	`created_by` INTEGER DEFAULT NULL
@@ -233,6 +233,5 @@ CREATE TABLE IF NOT EXISTS `sorterrorlog_data` (
 CREATE VIEW IF NOT EXISTS `courses` AS select * from `courses_data` where (not(`courses_data`.`deleted`));
 CREATE VIEW IF NOT EXISTS `lectures` AS select * from `lectures_data` where (not(`lectures_data`.`deleted`));
 CREATE VIEW IF NOT EXISTS `videos` AS select * from `videos_data` where (not(`videos_data`.`deleted`));
-CREATE VIEW IF NOT EXISTS `auth` AS select * from `auth_data` where (not(`auth_data`.`deleted`));
 CREATE VIEW IF NOT EXISTS `sorterrorlog` AS select * from `sorterrorlog_data` where (not(`sorterrorlog_data`.`deleted`));
 COMMIT;
diff --git a/server.py b/server.py
index 067a11d..7af9cda 100644
--- a/server.py
+++ b/server.py
@@ -70,59 +70,59 @@ def mod_required(func):
 			return func(*args, **kwargs)
 	return decorator
 
-def evalauth(auths):
-	cauths = []
-	lauths = []
-	vauths = []
-	for auth in auths:
-		if auth['course_id']:
-			cauths.append(auth)
-		elif auth['lecture_id']:
-			lauths.append(auth)
-		elif auth['video_id']:
-			vauths.append(auth)
-	if vauths:
-		return vauths
-	elif lauths:
-	 	return lauths
-	elif cauths:
-		return cauths
-	return [{'auth_type': 'public'}]
+def evalperm(perms):
+	cperms = []
+	lperms = []
+	vperms = []
+	for perm in perms:
+		if perm['course_id']:
+			cperms.append(perm)
+		elif perm['lecture_id']:
+			lperms.append(perm)
+		elif perm['video_id']:
+			vperms.append(perm)
+	if vperms:
+		return vperms
+	elif lperms:
+	 	return lperms
+	elif cperms:
+		return cperms
+	return [{'type': 'public'}]
 
 @app.template_filter()
-def checkauth(auths, username=None, password=None):
-	auths = evalauth(auths)
-	for auth in auths:
-		if auth['auth_type'] == 'public':
+def checkperm(perms, username=None, password=None):
+	perms = evalperm(perms)
+	for perm in perms:
+		if perm['type'] == 'public':
 			return True
-		elif auth['auth_type'] == 'password':
-			if auth['auth_param'] == username and auth['auth_param2'] == password:
+		elif perm['type'] == 'password':
+			if perm['param1'] == username and perm['param2'] == password:
 				return True
-		elif auth['auth_type'] == 'l2p':
-			if auth['auth_param'] in session.get('l2p_courses', []):
+		elif perm['type'] == 'l2p':
+			if perm['param1'] in session.get('l2p_courses', []):
 				return True
-		elif auth['auth_type'] == 'rwth':
+		elif perm['type'] == 'rwth':
 			if session.get('rwthintern', False):
 				return True
 	return False
 
 @app.template_filter()
-def authdescr(auths):
-	auths = evalauth(auths)
+def permdescr(perms):
+	perms = evalperm(perms)
 	public = False
 	password = False
 	l2p_courses = []
 	rwth_intern = False
-	for auth in auths:
-		if auth['auth_type'] == 'public':
+	for perm in perms:
+		if perm['type'] == 'public':
 			public = True
-		elif auth['auth_type'] == 'password':
+		elif perm['type'] == 'password':
 			password = True
-		elif auth['auth_type'] == 'l2p':
-			l2p_courses.append(auth['auth_param'])
-		elif auth['auth_type'] == 'rwth':
+		elif perm['type'] == 'l2p':
+			l2p_courses.append(perm['param'])
+		elif perm['type'] == 'rwth':
 			rwth_intern = True
-	if public or not auths:
+	if public or not perms:
 		return 'public', 'Öffentlich verfügbar'
 	if rwth_intern:
 		if password:
@@ -269,15 +269,15 @@ def course(id=None, handle=None):
 		course = query('SELECT * FROM courses WHERE id = ? AND (? OR visible)', id, ismod())[0]
 	else:
 		course = query('SELECT * FROM courses WHERE handle = ? AND (? OR visible)', handle, ismod())[0]
-	course['auth'] = query('SELECT * FROM auth WHERE course_id = ? ORDER BY auth_type', course['id'])
-	auths = query('SELECT auth.* FROM auth JOIN lectures ON (auth.lecture_id = lectures.id) WHERE lectures.course_id = ? ORDER BY auth.auth_type', course['id'])
+	course['perm'] = query('SELECT * FROM perm WHERE (NOT perm.deleted) AND course_id = ? ORDER BY type', course['id'])
+	perms = query('SELECT perm.* FROM perm JOIN lectures ON (perm.lecture_id = lectures.id) WHERE (NOT perm.deleted) AND lectures.course_id = ? ORDER BY perm.type', course['id'])
 	lectures = query('SELECT * FROM lectures WHERE course_id = ? AND (? OR visible) ORDER BY time, duration DESC', course['id'], ismod())
 	for lecture in lectures:
-		lecture['auth'] = []
+		lecture['perm'] = []
 		lecture['course'] = course
-		for auth in auths:
-			if auth['lecture_id'] == lecture['id']:
-				lecture['auth'].append(auth)
+		for perm in perms:
+			if perm['lecture_id'] == lecture['id']:
+				lecture['perm'].append(perm)
 	videos = query('''
 			SELECT videos.*, (videos.downloadable AND courses.downloadable) as downloadable, formats.description AS format_description, formats.player_prio, formats.prio
 			FROM videos
@@ -307,7 +307,7 @@ def lecture(id):
 			WHERE videos.lecture_id = ? AND (? OR videos.visible)
 			ORDER BY formats.prio DESC
 			''', lecture['course_id'], lecture['id'], ismod())
-	auths = query('SELECT auth.* FROM auth WHERE (auth.lecture_id = ? OR auth.course_id = ?)',
+	perms = query('SELECT perm.* FROM perm WHERE ((NOT perm.deleted) AND (perm.lecture_id = ? OR perm.course_id = ?))',
 			lecture['id'], lecture['course_id'])
 	if not videos:
 		flash('Zu dieser Vorlesung wurden noch keine Videos veröffentlicht!')
@@ -315,8 +315,8 @@ def lecture(id):
 	if not courses:
 		return render_endpoint('courses', 'Diese Veranstaltung existiert nicht!'), 404
 	chapters = query('SELECT * FROM chapters WHERE lecture_id = ? AND NOT deleted AND (? OR visible) ORDER BY time ASC', id, ismod())
-	if not checkauth(auths):
-		mode, text = authdescr(auths)
+	if not checkperm(perms):
+		mode, text = permdescr(perms)
 		if mode == 'rwth':
 			flash(text+'. <a target="_blank" href="'+url_for('start_rwthauth')+'">Hier authorisieren</a>.')
 		elif mode == 'l2p':
@@ -390,7 +390,7 @@ tabs = {
 			['created_by', 'time_created', 'time_updated']),
 	'featured': ('featured', 'id', ['title', 'text', 'internal', 'visible', 'deleted'],
 			['created_by', 'time_created', 'time_updated']),
-	'auth': ('auth_data', 'auth_id', ['auth_type', 'auth_param', 'auth_param2', 'deleted'],
+	'perm': ('perm', 'id', ['type', 'param1', 'param2', 'deleted'],
 			['course_id', 'lecture_id', 'video_id', 'created_by', 'time_created', 'time_updated']),
 	'sorterrorlog': ('sorterrorlog_data', 'id', ['deleted'],
 			['time_created', 'time_updated'])
@@ -426,6 +426,7 @@ def edit(prefix='', ignore=[]):
 @app.route('/new/<table>', methods=['GET', 'POST'])
 @mod_required
 def create(table):
+	print(table, request.values)
 	assert table in tabs
 	defaults = {'created_by': session['user']['dbid'], 'time_created': datetime.now(), 'time_updated': datetime.now()}
 	columns = []
@@ -444,6 +445,7 @@ def create(table):
 		assert column not in defaults
 		columns.append(column)
 		values.append(val)
+	print(columns, values)
 	id = modify('INSERT INTO %s (%s) VALUES (%s)'%(tabs[table][0],
 				','.join(columns), ','.join(['?']*len(values))), *values)
 	if 'ref' in request.values:
@@ -458,29 +460,29 @@ def auth(): # For use with nginx auth_request
 	ip = request.headers.get('X-Real-IP', '')
 	if url.endswith('jpg'):
 		return "OK", 200
-	videos = query('''SELECT videos.path, videos.id, auth.*
+	perms = query('''SELECT videos.path, videos.id AS vid, perm.*
       FROM videos
       JOIN lectures ON (videos.lecture_id = lectures.id)
       JOIN courses ON (lectures.course_id = courses.id)
-			LEFT JOIN auth ON (videos.id = auth.video_id OR lectures.id = auth.lecture_id OR courses.id = auth.course_id)
+			LEFT JOIN perm ON (videos.id = perm.video_id OR lectures.id = perm.lecture_id OR courses.id = perm.course_id)
       WHERE videos.path = ?
       AND (? OR (courses.visible AND lectures.visible AND videos.visible))
-			ORDER BY auth.video_id DESC, auth.lecture_id DESC, auth.course_id DESC''',
+			ORDER BY perm.video_id DESC, perm.lecture_id DESC, perm.course_id DESC''',
 			url, ismod())
 
-	if not videos:
+	if not perms:
 		return "Not allowed", 403
 	auth = request.authorization
 	username = password = None
 	if auth:
 		username = auth.username
 		password = auth.password
-	if checkauth(videos, username=username, password=password):
+	if checkperm(perms, username=username, password=password):
 		return 'OK', 200
-		modify('INSERT INTO log VALUES (?, "", ?, "video", ?, ?)', ip, datetime.now(), videos[0]['id'], url)
+		modify('INSERT INTO log VALUES (?, "", ?, "video", ?, ?)', ip, datetime.now(), perms[0]['vid'], url)
 	password_auth = False
-	for video in videos:
-		if video['auth_type'] == 'password':
+	for perm in perms:
+		if perm['type'] == 'password':
 			password_auth = True
 			break
 	if password_auth:
diff --git a/static/moderator.js b/static/moderator.js
index 791f1b8..b6907c9 100644
--- a/static/moderator.js
+++ b/static/moderator.js
@@ -100,8 +100,8 @@ var moderator = {
 		setacls: function(value) {
 			var idlist = [];
 			for (i in value) {
-				if (idlist.indexOf(value[i]['auth_id']) == -1) {
-					idlist[idlist.length] = value[i]['auth_id'];
+				if (idlist.indexOf(value[i]['id']) == -1) {
+					idlist[idlist.length] = value[i]['id'];
 					moderator.acleditor.acls[moderator.acleditor.acls.length] = value[i];
 				}
 			}
@@ -109,7 +109,7 @@ var moderator = {
 		init: function () {
 			$('.modmoderator_acleditor').popover(
 				{
-					title: "acls",
+					title: "Zugriffsrechte",
 					html: true,
 					placement: "left",
 					trigger: 'click',
@@ -123,13 +123,13 @@ var moderator = {
 						var idlist = [];
 						for (i in moderator.acleditor.acls) {
 							if ((moderator.acleditor.acls[i][type+'_id'] == id)) {
-								var auth = {};
-								auth.type = moderator.acleditor.acls[i]['auth_type'];
-								auth.param = moderator.acleditor.acls[i]['auth_param'];
-								auth.param2 = moderator.acleditor.acls[i]['auth_param2'];
-								auth.id = moderator.acleditor.acls[i]['auth_id'];
-								idlist[idlist.length] = auth.id;
-								html += '<option data-auth_id="'+auth.id+'">#'+auth.id+' '+auth.type+' '+ ( auth.type == "password" ? ' ("'+auth.param+'":"'+auth.param2+'")' : '' ) +'</option>';
+								var perm = {};
+								perm.type = moderator.acleditor.acls[i]['type'];
+								perm.param1 = moderator.acleditor.acls[i]['param1'];
+								perm.param2 = moderator.acleditor.acls[i]['param2'];
+								perm.id = moderator.acleditor.acls[i]['id'];
+								idlist[idlist.length] = perm.id;
+								html += '<option data-auth_id="'+perm.id+'">#'+perm.id+' '+perm.type+' '+ ( perm.type == "password" ? ' ("'+perm.param1+'":"'+perm.param2+'")' : '' ) +'</option>';
 							}
 						}
 						html += '</select>';
@@ -149,25 +149,25 @@ var moderator = {
 
 		},
 		delbtnclick: function (element) {
-			moderator.api.set("auth."+$(".acllist  option:selected", element.parentElement).data('auth_id')+".deleted",1,true);
+			moderator.api.set("perm."+$(".acllist  option:selected", element.parentElement).data('id')+".deleted",1,true);
 		},
 		addbtnclick: function (element) {
-			var auth = {};
-			auth.type = $(".authtype", element.parentElement).val();
-			if (auth.type == "password") {
-				auth.param = $(".authuser", element.parentElement).val();
-				auth.param2 = $(".authpassword", element.parentElement).val();
+			var perm = {};
+			perm.type = $(".authtype", element.parentElement).val();
+			if (perm.type == "password") {
+				perm.param1 = $(".authuser", element.parentElement).val();
+				perm.param2 = $(".authpassword", element.parentElement).val();
 			}
 			dict = {}
-			dict['auth_type'] = auth.type;
-			dict['auth_param'] = auth.param;
-			dict['auth_param2'] = auth.param2;
+			dict['type'] = perm.type;
+			dict['param1'] = perm.param1;
+			dict['param2'] = perm.param2;
 			dict[$(element.parentElement).data('type')+'_id'] = $(element.parentElement).data('id');
 
-			moderator.api.add_new(dict,'auth',true);
+			moderator.api.add_new(dict,'perm',true);
 			var option = $('<option>', {
-				"text": auth.type+' '+( auth.type == "password" ? ' ("'+auth.param+'":"'+auth.param2+'")' : '' ) ,
-				"data-auth": JSON.stringify(auth)
+				"text": perm.type+' '+( perm.type == "password" ? ' ("'+perm.param1+'":"'+perm.param2+'")' : '' ) ,
+				"data-auth": JSON.stringify(perm)
 			});
 			$(".acllist",element.parentElement).append(option);
 		},
diff --git a/templates/course.html b/templates/course.html
index be0890a..3d20d42 100644
--- a/templates/course.html
+++ b/templates/course.html
@@ -12,7 +12,7 @@
 		<h1 class="panel-title">{{ moderator_editor(['courses',course.id,'title'], course.title)}} {% if ismod() %}<i>(<a href={{ url_for('course', id=course.id) }}>{{course.id}}</a>)</i>{% endif %}
 			<ul class="pull-right list-inline">
 				<li>{{ moderator_delete(['courses',course.id,'deleted']) }}</li>
-				<li>{{ moderator_acleditor('course',course.id,course.auth, global_acls) }}</li>
+				<li>{{ moderator_acleditor('course',course.id,course.perm, global_acls) }}</li>
 			</ul>
 		</h1>
 	</div>
diff --git a/templates/macros.html b/templates/macros.html
index ab23ba5..8f9381c 100644
--- a/templates/macros.html
+++ b/templates/macros.html
@@ -154,7 +154,7 @@ $('#embedcodebtn').popover(
 					{{ moderator_delete(['lectures',lecture.id,'deleted']) }}
 				</li>
 				<li>
-					{{ moderator_acleditor('lecture', lecture.id, lecture.auth, global_acls) }}
+					{{ moderator_acleditor('lecture', lecture.id, lecture.perm, global_acls) }}
 				</li>
 			</ul>
 		</div>
-- 
GitLab