This commit is contained in:
2023-11-24 11:33:07 +01:00
parent b225c2bc71
commit 6806381e70
9 changed files with 166 additions and 56 deletions

132
app.py
View File

@ -1,30 +1,57 @@
#!/usr/bin/env python3.6 #!/usr/bin/env python3.6
import os import requests
from flask import Flask from flask import Flask
from flask import render_template, url_for, send_from_directory, redirect, request, send_file from flask import render_template, url_for, send_from_directory, redirect, request, send_file
from flask_login import login_user, login_required, current_user, LoginManager, UserMixin, logout_user
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
import pymysql
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
import hashlib import hashlib
import dualisauth import dualisauth
import requesthelpers
from fetchRAPLA import * from fetchRAPLA import *
from get_mysql import get_mysql from get_mysql import get_mysql
import time
def create():
app = Flask(__name__)
dbpw = get_mysql()[1]
dbun = get_mysql()[0]
app.config['SECRET_KEY'] = 'SECRET_KEY_GOES_HERE'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://' + dbun + ':' + dbpw + '@localhost/paulmrtn_DUALHUB'
db.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
@login_manager.user_loader
def load_user(uid: int):
return User.query.filter_by(id=uid).first()
return app
app = Flask(__name__)
db = SQLAlchemy() db = SQLAlchemy()
dbpw = get_mysql() app = create()
app.config['SECRET_KEY'] = 'ASDF)uhdsklvbkuezafdpo12i34rewfgvoukzgp3zerfpg8owiu2301394trilfkj'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://paulmrtn:' + dbpw + '@localhost/paulmrtn_DUALHUB'
db.init_app(app)
class User(db.Model): class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True) # primary keys are required by SQLAlchemy id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True) email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(100)) password = db.Column(db.String(255))
name = db.Column(db.String(1000)) name = db.Column(db.String(255))
kurs = db.Column(db.String(15))
class Dualis(db.Model):
token = db.Column(db.String(255), unique=True)
uid = db.Column(db.Integer, primary_key=True)
token_created = db.Column(db.Integer)
result_lists = db.Column(db.String(255))
cookie = db.Column(db.String(255))
@app.route("/") @app.route("/")
@ -32,6 +59,20 @@ def index():
return render_template('index.html', headermessage='Header', message='DualHub') return render_template('index.html', headermessage='Header', message='DualHub')
@app.route("/welcome")
@login_required
def welcome():
d = Dualis.query.filter_by(uid=current_user.id).first()
if not d.kurs:
kurs = dualisauth.getKurs(d.token, d.cookie)
current_user.kurs = kurs
db.session.commit()
else:
kurs = d.kurs
name = current_user.name
return render_template('index.html', headermessage='DualHub', message="Hallo, "
+ name + " (" + kurs + ")")
@app.route("/backendpoc/error<int:ecode>") @app.route("/backendpoc/error<int:ecode>")
def error(ecode): def error(ecode):
if ecode == 900: if ecode == 900:
@ -44,11 +85,13 @@ def error(ecode):
@app.route("/backendpoc/rapla") @app.route("/backendpoc/rapla")
@login_required
def chooseRaplas(): def chooseRaplas():
r = getRaplas() r = getRaplas()
return render_template("rapla.html", raplas=r) return render_template("rapla.html", raplas=r)
@login_required
@app.route("/backendpoc/plan", methods=["POST"]) @app.route("/backendpoc/plan", methods=["POST"])
def getRapla(): def getRapla():
file = str(request.form.get("file")) file = str(request.form.get("file"))
@ -56,10 +99,14 @@ def getRapla():
if file == url == "None": if file == url == "None":
return redirect(url_for("chooseRaplas")) return redirect(url_for("chooseRaplas"))
if file != "None": if file != "None":
User.query.filter_by(id=current_user.id).first().kurs = file[5:-5]
db.session.commit()
return send_file("calendars/" + file) return send_file("calendars/" + file)
elif url != "None": elif url != "None":
file = getNewRapla(url) file = getNewRapla(url)
if type(file) is not int: if type(file) is not int:
User.query.filter_by(id=current_user.id).first().kurs = file[5:-5]
db.session.commit()
return send_file("calendars/" + file) return send_file("calendars/" + file)
else: else:
return redirect(url_for("error", ecode=file + 900)) return redirect(url_for("error", ecode=file + 900))
@ -67,9 +114,9 @@ def getRapla():
@app.route("/backendpoc/log-in") @app.route("/backendpoc/log-in")
def login(ecode: int = None): def login(code: int = None):
if ecode: if code:
print(ecode) print(code)
return render_template("login.html") return render_template("login.html")
@ -77,32 +124,65 @@ def login(ecode: int = None):
def login_post(): def login_post():
email = request.form.get("email") email = request.form.get("email")
password = request.form.get("password") password = request.form.get("password")
n = request.args.get("next")
if n:
success = redirect(n)
else:
success = redirect(url_for("welcome"))
user = User.query.filter_by(email=email).first() user = User.query.filter_by(email=email).first()
if user: if user:
dualis = Dualis.query.filter_by(uid=user.id).first()
if check_password_hash(user.password, password): if check_password_hash(user.password, password):
return redirect(url_for("index")) if not dualisauth.checkLifetime(dualis.token_created):
new_token = dualisauth.checkUser(email, password)
dualis.token = new_token[0]
dualis.cookie = requesthelpers.getCookie(new_token[1].cookies)
dualis.token_created = time.time()
db.session.commit()
login_user(user)
return success
else: else:
t = dualisauth.checkUser(email, password) t = dualisauth.checkUser(email, password)
if t == -2: if t[0] == -2:
return redirect(url_for("login", ecode=-2)) return redirect(url_for("login", code=-2))
else: else:
user.password = generate_password_hash(password, method="pbkdf2:sha256") user.password = generate_password_hash(password, method="pbkdf2:sha256")
dualis.token = t[0]
dualis.cookie = requesthelpers.getCookie(t[1].cookies)
dualis.token_created = time.time()
db.session.commit() db.session.commit()
return redirect(url_for("index")) login_user(user)
return success
t = dualisauth.checkUser(email, password) t = dualisauth.checkUser(email, password)
if t == -2: if t[0] == -2:
return redirect(url_for("login", ecode=-2)) return redirect(url_for("login", code=-2))
hashid = int(hashlib.sha1(email.encode("utf-8")).hexdigest(), 16) % (10 ** 12) hashid = int(hashlib.sha1(email.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
hashpw = generate_password_hash(password, method="pbkdf2:sha256") hashpw = generate_password_hash(password, method="pbkdf2:sha256")
new_user = User(id=hashid, email=email, password=hashpw) pname = email.find(".") + 1
db.session.add(new_user) ename = min(email[pname:].find("."), email[pname:].find("@"))
db.session.commit() name = email[pname:pname + ename].capitalize()
return redirect(url_for("index")) new_user = User(email=email, password=hashpw, name=name, id=hashid)
db.session.add(new_user)
cookie = requesthelpers.getCookie(t[1].cookies)
new_dualis = Dualis(uid=hashid, token=t[0], token_created=int(time.time()), cookie=cookie)
db.session.add(new_dualis)
db.session.commit()
login_user(new_user)
return success
@app.route("/backendpoc/log-out")
def logout():
logout_user()
return redirect(url_for("login", code=1))
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,31 +1,52 @@
import requests import requests
from requests.utils import requote_uri, unquote_unreserved
import urllib.parse import urllib.parse
import time
from bs4 import BeautifulSoup
headers = {
def checkUser(email: str, password: str):
url = "https://dualis.dhbw.de/scripts/mgrqispi.dll"
fpw = urllib.parse.quote(password, safe='', encoding=None, errors=None)
fmail = urllib.parse.quote(email, safe='', encoding=None, errors=None)
payload = 'usrname=' + fmail + '&pass=' + fpw + '&ARGUMENTS=clino%2Cusrname%2Cpass%2Cmenuno%2Cmenu_type%2Cbrowser%2Cplatform&APPNAME=CampusNet&PRGNAME=LOGINCHECK'
headers = {
'Cookie': 'cnsc=0', 'Cookie': 'cnsc=0',
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
} }
response = requests.request("POST", url, headers=headers, data=payload) url = "https://dualis.dhbw.de/scripts/mgrqispi.dll"
def checkUser(email: str, password: str):
s = requests.Session()
fpw = urllib.parse.quote(password, safe='', encoding=None, errors=None)
fmail = urllib.parse.quote(email, safe='', encoding=None, errors=None)
payload = 'usrname=' + fmail + '&pass=' + fpw + '&ARGUMENTS=clino%2Cusrname%2Cpass%2Cmenuno%2Cmenu_type%2Cbrowser%2Cplatform&APPNAME=CampusNet&PRGNAME=LOGINCHECK'
response = s.post(url, headers=headers, data=payload)
header = response.headers header = response.headers
try: try:
refresh = header["REFRESH"] refresh = header["REFRESH"]
arg = refresh.find("=-N") + 3 arg = refresh.find("=-N") + 3
komma = refresh[arg:].find(",") komma = refresh[arg:].find(",")
except KeyError: except KeyError:
return -2 return -2, s
token = refresh[arg:komma + arg] token = refresh[arg:komma + arg]
return token return token, s
def getName(token: str): def getKurs(token: str, cookie: int):
print(token) headers["Cookie"] = "cnsc=" + str(cookie)
response = requests.request("GET",
url + "?APPNAME=CampusNet&PRGNAME=COURSERESULTS&ARGUMENTS=-N" + token + ",-N000307,",
headers=headers, data={})
html = BeautifulSoup(response.text, 'lxml')
link = html.body.find('a', attrs={'id': "Popup_details0001"})['href']
response = requests.request("GET", url+link[21:], headers=headers, data={})
html = BeautifulSoup(response.text, 'lxml')
content = html.body.find('td', attrs={'class': 'level02'}).text
start = content.find(" ")+4
end = start + (content[start:].find(" "))
kurs = content[start:end]
return kurs
def checkLifetime(timecode):
if time.time() - timecode > 1800:
return False
else:
return True

View File

@ -1,10 +1,13 @@
import getpass import getpass
def get_mysql ():
def get_mysql():
u = getpass.getuser() u = getpass.getuser()
f = open("/home/"+u+"/.my.cnf", "r") f = open("/home/"+u+"/.my.cnf", "r")
i = f.read() i = f.read()
u = i.find("user=")
p = i.find("password=") p = i.find("password=")
ro = i.find ("[clientreadonly]") u = i[u+5:p-1]
ro = i.find("[clientreadonly]")
p = i[p+9:ro-2] p = i[p+9:ro-2]
return p return u, p

8
requesthelpers.py Normal file
View File

@ -0,0 +1,8 @@
def getCookie (cookies):
cookie = 0
for c in cookies:
cookie = c.value
return cookie

View File

@ -14,7 +14,7 @@ input {
height: 50px height: 50px
} }
#url { input[type=url], input[type=email], input[type=password] {
width: 500px; width: 500px;
} }

View File

@ -4,11 +4,10 @@
<title> {{headermessage}} 👀</title> <title> {{headermessage}} 👀</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<script async src="https://analytics.paulmartin.cloud/script.js" data-website-id="1c02dacf-6952-4560-a303-0c25f432c48d"></script> <script async src="https://analytics.paulmartin.cloud/script.js" data-website-id="459fa66e-e255-4393-8e89-ead8b1572d0d"></script>
</head> </head>
<link rel="shortcut icon" type="image/x-icon" href="temp.png">
<body> <body>
<div class="cs"> <div class="cs">
<h1>{{message}}</h1> <h1>{{message}}</h1>

View File

@ -1,20 +1,19 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="de"> <html lang="de">
<head> <head>
<title> {{headermessage}} 👀</title> <title> Log In 👀</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<script async src="https://analytics.paulmartin.cloud/script.js" data-website-id="1c02dacf-6952-4560-a303-0c25f432c48d"></script> <script async src="https://analytics.paulmartin.cloud/script.js" data-website-id="459fa66e-e255-4393-8e89-ead8b1572d0d"></script>
</head> </head>
<link rel="shortcut icon" type="image/x-icon" href="temp.png">
<body> <body>
<div class="cs"> <div class="cs">
<form method="post" action={{ url_for ("login_post") }}> <form method="post" action={{ url_for ("login_post", next=request.args.get("next")) }}>
<label for="email" >Dualis-Email</label> <label for="email" >Dualis-Email: </label>
<input class="input" type="email" name="email" placeholder="Email-Adresse" autofocus=""> <input class="input" type="email" name="email" placeholder="Email-Adresse" autofocus="">
<label for="password">Dualis-Passwort</label> <label for="password">Dualis-Passwort:</label>
<input class="input" type="password" name="password" placeholder="Passwort"> <input class="input" type="password" name="password" placeholder="Passwort">
<button class="button">Login</button> <button class="button">Login</button>
</form> </form>

View File

@ -1,9 +1,9 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="de"> <html lang="de">
<head> <head>
<title> {{headermessage}} 👀</title> <title> RAPLA importieren 👀</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<script async src="https://analytics.paulmartin.cloud/script.js" data-website-id="1c02dacf-6952-4560-a303-0c25f432c48d"></script> <script async src="https://analytics.paulmartin.cloud/script.js" data-website-id="459fa66e-e255-4393-8e89-ead8b1572d0d"></script>
</head> </head>
<body> <body>
<h1>Verfügbare Raplas </h1> <h1>Verfügbare Raplas </h1>
@ -23,7 +23,7 @@
<h1>Eigenen Rapla hinzufügen</h1> <h1>Eigenen Rapla hinzufügen</h1>
<form method="post" action={{ url_for ("getRapla") }}> <form method="post" action={{ url_for ("getRapla") }}>
<label for="url">Rapla-URL eingeben, falls Du deinen Kurs nicht siehst:</label> <label for="url">Rapla-URL eingeben, falls Du deinen Kurs nicht siehst:</label>
<input type="text" name="url" id="url"> <input type="url" name="url" id="url">
<input type="submit" value="Importieren!"> <input type="submit" value="Importieren!">
</form> </form>
</body> </body>