From 19be800c00994d9bfea391f359290d8c8afe03ae Mon Sep 17 00:00:00 2001
From: Roman Karwacik <roman.karwacik@rwth-aachen.de>
Date: Fri, 8 Apr 2022 16:07:56 +0200
Subject: [PATCH] Feature: Use S3 presigned urls instead of direct links

---
 config.py.example |  5 +++++
 requirements.txt  |  1 +
 server.py         | 19 ++++++++++++++++++-
 3 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/config.py.example b/config.py.example
index 767ec61..9cc6698 100644
--- a/config.py.example
+++ b/config.py.example
@@ -40,3 +40,8 @@ MAIL_DEFAULT = 'Video AG <videoag@fsmpi.rwth-aachen.de>'
 MAIL_ADMINS = 'videoag-it@lists.fsmpi.rwth-aachen.de'
 STREAMING_SERVER = 'rtmp://video-web-0.fsmpi.rwth-aachen.de/src/'
 BACKUP_STREAMING_SERVER = 'rtmp://video-web-1.fsmpi.rwth-aachen.de/src/'
+
+S3_ACCESS_KEY = None
+S3_SECRET_KEY = None
+S3_ENDPOINT = "http://rgw.fsmpi.rwth-aachen.de:7480"
+S3_BUCKET_NAME = "VIDEO.rgw.fsmpi.rwth-aachen.de"
diff --git a/requirements.txt b/requirements.txt
index d0976ac..f27bc38 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,7 @@
 # required
 flask
 requests
+boto3
 
 # optional
 lxml
diff --git a/server.py b/server.py
index a07832d..8600c2b 100644
--- a/server.py
+++ b/server.py
@@ -7,6 +7,7 @@ import traceback
 import string
 import locale
 import urllib
+import boto3
 
 from flask import Flask, request, url_for, redirect, session, render_template, flash, Response, make_response
 from werkzeug.routing import Rule
@@ -39,6 +40,10 @@ if config['DEBUG']:
 if not config.get('SECRET_KEY', None):
 	config['SECRET_KEY'] = os.urandom(24)
 
+if config.get("S3_ACCESS_KEY") and config.get("S3_SECRET_KEY"):
+	b3_session = boto3.Session(aws_access_key_id=config["S3_ACCESS_KEY"],
+	                           aws_secret_access_key=config["S3_SECRET_KEY"])
+
 mod_endpoints = [] #pylint: disable=invalid-name
 def mod_required(func):
 	mod_endpoints.append(func.__name__)
@@ -539,7 +544,19 @@ def auth(): #pylint: disable=too-many-branches
 
 @app.route('/files/<filename>')
 def files(filename):
-	return redirect(config['VIDEOPREFIX']+'/'+filename)
+	if config.get("S3_ACCESS_KEY") and config.get("S3_SECRET_KEY"):
+		s3_client = b3_session.client('s3', endpoint_url=config["S3_ENDPOINT"])
+		# creates a presigned url, doesn't check wether the object exists though
+		try:
+			generated_url = s3_client.generate_presigned_url('get_object',
+			                                                 Params={"Bucket":config["S3_BUCKET_NAME"], "Key": filename},
+			                                                 ExpiresIn=3600)
+		except:
+			notify_admins('s3 error', traceback="creating presigned url failed!")
+			return None
+		return redirect(generated_url)
+	else:
+		return redirect(config['VIDEOPREFIX']+'/'+filename)
 
 @app.route('/sitemap.xml')
 def sitemap():
-- 
GitLab