Skip to content

Commit

Permalink
Merge pull request EGCETSII#30 from Full-Tortuga/feature/ldap
Browse files Browse the repository at this point in the history
Feature Login LDAP
  • Loading branch information
laur2000 authored Dec 22, 2021
2 parents 4c7b2b3 + db95d02 commit 13cd9a9
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 24 deletions.
2 changes: 1 addition & 1 deletion decide/authentication/templates/bienvenida.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ <h1>Hola {{ user.first_name }}</h1>
{% else %}
<a href="{% url 'sign_in' %}">Registrate</a>
<a href="{% url 'sign_in' %}">Iniciar sesión con usuario/contraseña</a>
<a href="{% url 'loginldap' %}">Iniciar sesión con LDAP</a>
<a href="{% url 'loginldapform' %}">Iniciar sesión con LDAP</a>
<a href="">Iniciar sesión con huella dactilar</a>{% comment %}Meter url huelladactilar {% endcomment %}
<a href="">Iniciar sesión con redes sociales</a>{% comment %}Meter url para rrss {% endcomment %}
{% endif %}
Expand Down
24 changes: 24 additions & 0 deletions decide/authentication/templates/login_ldap_view.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

{% load static %}
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<title>LOGIN LDAP FORM</title>
</head>

<body>
<form method=POST action="{% url 'loginldap' %}">
<label for="username">Username</label>
<input id="username" name="username" type="text">
<label for="password">Password</label>
<input id="password" name="password" type="password">
<input type="submit" value="Iniciar sesión con LDAP">
</form>
</body>

</html>
18 changes: 18 additions & 0 deletions decide/authentication/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from base import mods

from local_settings import AUTH_LDAP_SERVER_URI


class AuthTestCase(APITestCase):

Expand Down Expand Up @@ -149,3 +151,19 @@ def test_register_user_already_exist(self):
response = self.client.post(
'/authentication/register/', token, format='json')
self.assertEqual(response.status_code, 400)

def test_login_ldap_positive(self):
body_form = {'username': 'foobar', 'password': 'test'}
response = self.client.post(
'/authentication/loginLDAP/', body_form, format='json')
self.assertEqual(response.status_code, 200)


def test_login_ldap_negative(self):
body_form = {'username': 'foobar', 'password': 'contrasenyaMal'}
response = self.client.post(
'/authentication/loginLDAP/', body_form, format='json')
self.assertEqual(response.status_code, 400)



6 changes: 3 additions & 3 deletions decide/authentication/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
from django.urls import include, path
from rest_framework.authtoken.views import obtain_auth_token

from .views import BienvenidaView, GetUserView, LogoutView, RegisterView, LDAPLogin, SignInView, cerrarsesion

from .views import BienvenidaView, GetUserView, LogoutView, RegisterView, LDAPLogin, SignInView, cerrarsesion, LDAPSignInView

urlpatterns = [
path('login/', obtain_auth_token),
# path('logout/', LogoutView.as_view(), name='logout'),
path('getuser/', GetUserView.as_view()),
path('register/', RegisterView.as_view(), name='sign_up'),
path('loginLDAP/', LDAPLogin.as_view(), name="loginldap"),
path('loginLDAP_form/', LDAPSignInView.as_view(), name='loginldapform'),
path('loginLDAP/', LDAPLogin.as_view(), name='loginldap'),
path('login_form/', SignInView.as_view(), name='sign_in'),
path('bienvenida/', BienvenidaView.as_view()),
path('logout/', cerrarsesion, name="logout"),
Expand Down
54 changes: 35 additions & 19 deletions decide/authentication/views.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
from rest_framework.response import Response
from rest_framework.status import (
HTTP_200_OK,
HTTP_201_CREATED,
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED
HTTP_401_UNAUTHORIZED,
HTTP_500_INTERNAL_SERVER_ERROR
)
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.views import LoginView
from django.contrib import messages

from django.db import IntegrityError
from django.shortcuts import get_object_or_404
from django.shortcuts import get_object_or_404, render
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import login, logout
from django.views.generic import TemplateView

from .serializers import UserSerializer

import ldap
from local_settings import AUTH_LDAP_SERVER_URI, AUTH_LDAP_BIND_DN, AUTH_LDAP_BIND_PASSWORD


class GetUserView(APIView):
def post(self, request):
Expand Down Expand Up @@ -55,18 +66,6 @@ def post(self, request):
return Response({}, status=HTTP_400_BAD_REQUEST)
return Response({'user_pk': user.pk, 'token': token.key}, HTTP_201_CREATED)

#Incremento
from django.contrib.auth import authenticate, login, logout
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import render, redirect
from django.contrib.auth.views import LoginView
from django.contrib import messages

from django.views.generic import TemplateView


class LDAPLogin(APIView):
"""
Class to authenticate a user via LDAP and
Expand All @@ -80,11 +79,26 @@ def post(self, request):
:param request:
:return:
"""
user_obj = authenticate(username=request.data['username'],

try:
#Probamos la conexion con el servidor con las siguientes instrucciones
con = ldap.initialize(AUTH_LDAP_SERVER_URI)
con.simple_bind_s(AUTH_LDAP_BIND_DN, AUTH_LDAP_BIND_PASSWORD)
try:
#Probamos a logear con los datos enviados por el usuario
user_obj = authenticate(username=request.data['username'],
password=request.data['password'])
login(request, user_obj)
data={'detail': 'User logged in successfully'}
return Response(data, status=200)
login(request, user_obj, backend='django_auth_ldap.backend.LDAPBackend')
data={'detail': 'User logged in successfully'}
status = HTTP_200_OK
except AttributeError:
data={'detail': 'Credenciales mal'}
status = HTTP_400_BAD_REQUEST
except ldap.SERVER_DOWN:
data={'detail': 'Problema con el servicio LDAP'}
status = HTTP_500_INTERNAL_SERVER_ERROR
return render(request, 'bienvenida.html', status=status)


class LDAPLogout(APIView):
"""
Expand All @@ -103,6 +117,8 @@ def post(self, request):
return Response(data, status=200)


class LDAPSignInView(LoginView):
template_name = 'login_ldap_view.html'

class SignInView(LoginView):
template_name = 'index.html'
Expand Down
2 changes: 1 addition & 1 deletion decide/local_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
# number of bits for the key, all auths should use the same number of bits
KEYBITS = 256

AUTH_LDAP_SERVER_URI = 'ldap://:388'
AUTH_LDAP_SERVER_URI = 'ldap://:389'

AUTH_LDAP_BIND_DN = 'cn=admin,dc=decide,dc=org'
AUTH_LDAP_BIND_PASSWORD = 'decide'
Expand Down

0 comments on commit 13cd9a9

Please sign in to comment.