add a new app for ldap3-authentication (currently, it uses a testserver), login/logout from django, my own decorator

This commit is contained in:
2020-08-25 17:09:08 +00:00
parent a8cd21b930
commit ffa248ce03
11 changed files with 224 additions and 0 deletions

View File

View File

@@ -0,0 +1,3 @@
# from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class AuthenticationsConfig(AppConfig):
name = 'authentications'

View File

@@ -0,0 +1,27 @@
import ldap3
def authentication(username, password):
# no empty passwords
if password is None or password.strip() == "":
# messages.info("username:%s Login denied for blank password", username)
return None
# username format
new_username = 'uid={username}, cn=users, cn=accounts, dc=demo1, dc=freeipa, dc=org'
userdn = new_username.format(username=username)
server_uri = 'ipa.demo1.freeipa.org'
server = ldap3.Server(server_uri, get_info=ldap3.ALL)
try:
ldap3.Connection(
server,
userdn,
password,
auto_bind=True,
)
except ldap3.core.exceptions.LDAPBindError:
username = None
return username

View File

@@ -0,0 +1,11 @@
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('home')
else:
return view_func(request, *args, **kwargs)
return wrapper_func

View File

@@ -0,0 +1,3 @@
# from django.db import models
# Create your models here.

View File

@@ -0,0 +1,3 @@
# from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,8 @@
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.loginPage, name="login"),
path('logout/', views.logoutUser, name="logout"),
]

View File

@@ -0,0 +1,40 @@
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from django.contrib import messages
from django.contrib.auth.models import User
from .authentications import authentication
# from .decorators import unauthenticated_user
# @unauthenticated_user
def loginPage(request):
"""
if request.user.is_authenticated:
return redirect('home')
else:
"""
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
auth_user = authentication(username, password)
if auth_user is not None:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User.objects.create_user(auth_user)
login(request, user)
return redirect('home')
else:
messages.info(request, 'username OR password is incorrect')
context = {}
return render(request, 'authentications/login.html', context)
def logoutUser(request):
logout(request)
return redirect('home')