Release - Upload

This commit is contained in:
Js_Sman_Omen
2025-03-24 14:34:56 +01:00
commit 89f35ca466
370 changed files with 32904 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
import getpass
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES
print("Authentifizierung gegen ein Active Directory")
# Eingaben
dom = input("Domain [ADS1]:") or "ADS1"
user = input("User [hofmannol]:") or "hofmannol"
print('Password:', end='')
pwd = getpass.getpass()
# Binden an das AD
server = Server('gso1.ads1.fh-nuernberg.de', get_info=ALL)
conn = Connection(
server,
user=dom+"\\"+user,
password=pwd,
authentication=NTLM)
conn.bind()
print(conn)
print(conn.extend.standard.who_am_i())
print(conn.bound)
# Suche nach dem gerade verbundenen User
conn.search(
search_base='DC='+dom+',DC=fh-nuernberg,DC=de',
search_filter='(&(objectclass=user)(CN='+user+'))',
attributes=ALL_ATTRIBUTES)
print(conn.entries[0])
conn.unbind()
View File
+4
View File
@@ -0,0 +1,4 @@
from django.conf import settings # import the settings file
def logout_redirect(request):
return {'LOGOUT_REDIRECT_URL': settings.LOGOUT_REDIRECT_URL}
+1
View File
@@ -0,0 +1 @@
loaddata medinf/fixtures/groups.json
+30
View File
@@ -0,0 +1,30 @@
[
{
"model": "auth.group",
"pk": 1,
"fields": {
"name": "PP_ADMIN"
}
},
{
"model": "auth.group",
"pk": 10,
"fields": {
"name": "STUD_VIEW"
}
},
{
"model": "auth.group",
"pk": 11,
"fields": {
"name": "STUD_VIEW_EXTENDED"
}
},
{
"model": "auth.group",
"pk": 12,
"fields": {
"name": "STUD_ADMIN"
}
}
]
+92
View File
@@ -0,0 +1,92 @@
import logging
import traceback
import datetime
from django.contrib.auth.models import User
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES
from ldap3.core.exceptions import LDAPSocketOpenError
from django.conf import settings
from authstuff.ldap_access import update_entries_with_conn
class LdapBackend(object):
"""
Authenticate against a LDAP directory.
"""
log = logging.getLogger(__name__)
def check_login(self, username, password):
self.log.info("check login {0}".format(username))
server = Server(settings.LDAP_SERVER, connect_timeout=8)
qualified_user = settings.LDAP_DOMAIN + '\\' + username
conn = Connection(server, qualified_user, password=password, authentication=NTLM)
try:
conn.bind()
except LDAPSocketOpenError:
# LDAP Server nicht erreichbar
self.log.warning("LDAP check_login: Server " + settings.LDAP_SERVER + " not reachable.")
return None
except:
var = traceback.format_exc()
self.log.info("LDAP check_login(bind): Unexpected Error %s" % var)
return None
result = None
self.log.info("Bind successful")
try:
if conn.extend.standard.who_am_i() != None:
conn.search(
search_base='DC=' + settings.LDAP_DOMAIN + ',DC=fh-nuernberg,DC=de',
search_filter='(&(objectclass=user)(CN=' + username + '))', attributes=ALL_ATTRIBUTES)
info = conn.entries[0]
result = {'lastname' : str(info.sn),
'givenname' : str(info.givenName),
'login' : str(info.cn),
'department' : str(info.department),
'role' : str(info.description)}
self.log.info("LDAP check_login: %s" % result)
except:
var = traceback.format_exc()
self.log.warning("LDAP check_login: Unexpected Error %s" % var)
try:
delta = datetime.timedelta(days=settings.LDAP_UPDATE_TIMEOUT_DAYS)
update_entries_with_conn(conn, settings.LDAP_DOMAIN, delta)
except:
var = traceback.format_exc()
self.log.warning("LDAP check_login: Update AD Entries failed %s" % var)
return result
def authenticate(self, request, username=None, password=None):
ldap_user = self.check_login(username,password)
if ldap_user:
# {'lastname': 'Hofmann', 'givenname': 'Oliver', 'login': 'hofmannol', 'department': 'EFI', 'role': 'PF'}
# {'lastname': 'Wimmer', 'givenname': 'Martin', 'login': 'wimmerma', 'department': 'EFI', 'role': 'MA'}
# {'lastname': 'Mueller', 'givenname': 'Vincent', 'login': 'muellervi56608', 'department': 'EFI', 'role': 'ST'}
# {'lastname': 'Poehlau', 'givenname': 'Frank', 'login': 'poehlaufr', 'department': 'EFI', 'role': 'PF'}
try:
user = User.objects.get(username=ldap_user['login'])
except User.DoesNotExist:
self.log.info("LDAP authenticate: create new user %s" % ldap_user['login'])
user = User(username=ldap_user['login'])
user.first_name = ldap_user['givenname']
user.last_name = ldap_user['lastname']
user.is_staff = (ldap_user['role'] != 'ST')
user.is_superuser = False
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
+306
View File
@@ -0,0 +1,306 @@
"""
Django settings for medinf project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
from datetime import timedelta
import os
import re
import socket
# Development or Production
r = re.search(r"^172.17", socket.gethostbyname(socket.gethostname()))
DEVELOPMENT = r == None
DEBUG = True
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = DEVELOPMENT
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Log Configuration
if DEBUG:
LOGLEVEL = "DEBUG"
else:
LOGLEVEL = "INFO"
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
"datefmt": "%d/%b/%Y %H:%M:%S",
},
},
"handlers": {
"null": {
"level": "DEBUG",
"class": "logging.NullHandler",
},
"logfile": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler",
"filename": os.path.join(BASE_DIR, "log/log.txt"),
"maxBytes": 1024 * 1024 * 5,
"backupCount": 5,
"formatter": "standard",
},
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "standard",
},
},
"loggers": {
"": {
"level": "WARNING",
"handlers": ["logfile"],
},
"django.db.backends": {
"handlers": ["console"],
"level": "INFO", # set DEBUG if needed
"propagate": False,
},
"medinf": {
"handlers": ["console"],
"level": LOGLEVEL,
"propagate": True,
},
"studis": {
"handlers": ["console"],
"level": LOGLEVEL,
"propagate": True,
},
"authstuff": {
"handlers": ["console"],
"level": "INFO",
"propagate": True,
},
},
}
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "XXXXXn!i2lx(&)gq7l!art_pr&#9et*$r)r&ogu&j-+wm0^ni5"
USE_X_FORWARDED_HOST = True
ALLOWED_HOSTS = [
"medinf.efi.th-nuernberg.de",
"api.efi.th-nuernberg.de",
"localhost",
"127.0.0.1",
]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# Custom Apps
"authstuff.apps.AuthStuffConfig",
"pruefplan_viewer.apps.PruefplanViewerConfig",
"pruefplan_parser.apps.PruefplanParserConfig",
# Third Party Apps
"rest_framework",
"rest_framework_simplejwt.token_blacklist",
"rest_framework.authtoken",
"corsheaders",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "medinf.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"medinf.context_processors.logout_redirect",
],
},
},
]
WSGI_APPLICATION = "medinf.wsgi.application"
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
if DEVELOPMENT:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "django-app",
"USER": "django-app",
"PASSWORD": "8TFXHv9X",
"HOST": "mysql",
"PORT": "3306",
"OPTIONS": {"init_command": "SET sql_mode='STRICT_TRANS_TABLES'"},
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = "de-de"
TIME_ZONE = "Europe/Berlin"
USE_I18N = True
USE_L10N = True
USE_TZ = True
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
# Nach dem Deployment werden die statischen Inhalte von medinf geholt.
# Sie müssen in das Verzeichnis <HTMLROOT>/static kopiert werden
STATIC_ROOT = os.path.join("/tmp", "static")
STATIC_URL = "/static/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# Konfiguration des Auth-Systems
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
LDAP_DOMAIN = "ADS1"
LDAP_SERVER = "gso1.ads1.fh-nuernberg.de"
LDAP_FORCE_UPDATE = False
LDAP_UPDATE_TIMEOUT_DAYS = 2
if DEVELOPMENT:
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
LOGIN_URL = "/accounts/login/"
else:
LOGIN_REDIRECT_URL = "/app/"
LOGOUT_REDIRECT_URL = "/app/"
LOGIN_URL = "/app/accounts/login/"
if DEVELOPMENT:
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
]
else:
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"medinf.ldap_backend.LdapBackend",
]
# Config the JWT Token with static settings -> from docs
# https://django-rest-framework-simplejwt.readthedocs.io/en/latest/
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
"REFRESH_TOKEN_LIFETIME": timedelta(days=50),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
"UPDATE_LAST_LOGIN": False,
"ALGORITHM": "HS256",
"VERIFYING_KEY": None,
"AUDIENCE": None,
"ISSUER": None,
"JWK_URL": None,
"LEEWAY": 0,
"AUTH_HEADER_TYPES": ("Bearer",),
"AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "user_id",
"USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
"TOKEN_TYPE_CLAIM": "token_type",
"TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",
"JTI_CLAIM": "jti",
"SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
"SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
"SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
}
# Set coresheader to allow all origin
CORS_ALLOW_ALL_ORIGINS = True
# Konfiguration Prüfungsplan
PP_UPLOAD_DIR = os.path.join(BASE_DIR, "pruefplan_parser", "data")
PP_TEACHER_FILE = os.path.join(PP_UPLOAD_DIR, "Dozenten.json")
PP_SUBJECT_FILE = os.path.join(PP_UPLOAD_DIR, "Faecher.json")
PP_ATTENDANCE_FILE = os.path.join(PP_UPLOAD_DIR, "Praesenzen.json")
PP_EXAM_FILE = os.path.join(PP_UPLOAD_DIR, "Pruefungen.json")
PP_STUDENT_FILE = os.path.join(PP_UPLOAD_DIR, "Saaleinteilung.json")
+37
View File
@@ -0,0 +1,37 @@
"""medinf URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
import medinf.views
urlpatterns = [
path("", TemplateView.as_view(template_name="index.html")),
path("navlogin/", medinf.views.navlogin, name="navlogin"),
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
path("pruefplan_viewer/", include("pruefplan_viewer.urls")),
path("pruefplan_parser/", include("pruefplan_parser.urls")),
path("api/", include("api.urls")), # Link the api urls to the main access point
path(
"authenticate/",
medinf.views.AuthenticateView.as_view(),
name="authenticateView",
), # REST call to authenticate a user in the backend
]
+59
View File
@@ -0,0 +1,59 @@
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from yaml import serialize
from api.serializer import MyTokenObtainPairSerializer
from api.views import MyTokenObtainPairView
import medinf.settings
import logging
import medinf.ldap_backend
def navlogin(request):
log = logging.getLogger("medinf")
logout(request)
error = ""
if request.POST:
username = request.POST.get("username", "?")
password = request.POST.get("password", "?")
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect(medinf.settings.LOGIN_REDIRECT_URL)
else:
log.info("Inactive user {} tried to login".format(username))
error = "Ihre Benutzerkennung wurde deaktiviert."
else:
log.info("Login failed for {}".format(username))
error = "Benutzername oder Kennwort falsch."
context = {"error": error}
return render(request, "index.html", context)
################ New REST Token Auth #########################################
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import authenticate
class AuthenticateView(APIView):
def post(self, request):
username = request.data.get("username")
password = request.data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user) #login the user in the backend
# refresh = RefreshToken.for_user(user)
serializer = MyTokenObtainPairSerializer(data={"username":username, "password":password})
serializer.is_valid(raise_exception=True)
token = serializer.validated_data
return Response(token)
return Response({"error": "Invalid credentials"}, status=400)
+21
View File
@@ -0,0 +1,21 @@
"""
WSGI config for medinf project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
import logging
import medinf.settings
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "medinf.settings")
log = logging.getLogger(__name__)
log.info("Starting in %s Environment" % ('DEV' if medinf.settings.DEVELOPMENT else 'PROD'))
application = get_wsgi_application()