Commit 62d0c01e authored by Leonidas Poulopoulos's avatar Leonidas Poulopoulos

Added elementary shibboleth login to management

parent bf3e4525
import os
import sys
sys.path.append('/home/leopoul/projects/')
sys.path.append('/home/leopoul/projects/eduroam')
os.environ['DJANGO_SETTINGS_MODULE'] = 'eduroam.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
# -*- coding: utf-8 -*- vim:encoding=utf-8:
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
from django.contrib.auth.models import User, UserManager, Permission, Group
from django.conf import settings
class shibauthBackend:
def authenticate(self, **kwargs):
username = kwargs.get('username')
firstname = kwargs.get('firstname')
lastname = kwargs.get('lastname')
mail = kwargs.get('mail')
authsource = kwargs.get('authsource')
if authsource != 'shibboleth':
return None
try:
user = self._auth_user(username, firstname, lastname, mail)
except:
return None
if not user:
return None
return user
def _auth_user(self, username, firstname, lastname, mail):
try:
user = User.objects.get(username__exact=username)
# The user did not exist. Create one with no privileges
except:
user = User.objects.create_user(username, mail, None)
user.first_name = firstname
user.last_name = lastname
user.is_staff = False
user.is_superuser = False
user.is_active = False
user.save()
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
......@@ -2,6 +2,7 @@ from django import forms
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from edumanage.models import *
from accounts.models import *
from django.conf import settings
from django.contrib.contenttypes.generic import BaseGenericInlineFormSet
......@@ -14,6 +15,11 @@ import re
FQDN_RE = r'(^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$)'
#FQDN_RE = r'(^[a-z0-9.-]{1,255}$)'
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
class InstDetailsForm(forms.ModelForm):
class Meta:
......
......@@ -35,6 +35,7 @@ urlpatterns = patterns('edumanage.views',
url(r'^manage/adduser/?$', 'adduser', name="adduser"),
url(r'^manage/selectinst/?$', 'selectinst', name="selectinst"),
......
......@@ -22,6 +22,10 @@ from django.contrib import messages
from django.db.models import Max
from django.views.decorators.cache import never_cache
from django.utils.translation import ugettext as _
from django.contrib.auth import authenticate, login
def index(request):
return render_to_response('front/index.html', context_instance=RequestContext(request))
......@@ -666,12 +670,107 @@ def del_service(request):
resp['success'] = "Service successfully deleted"
return HttpResponse(json.dumps(resp), mimetype='application/json')
@never_cache
def user_login(request):
try:
error_username = False
error_orgname = False
error_entitlement = False
error_mail = False
has_entitlement = False
error = ''
username = request.META['HTTP_EPPN']
if not username:
error_username = True
firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
#organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
entitlement = request.META['HTTP_SHIB_EP_ENTITLEMENT']
if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
has_entitlement = True
if not has_entitlement:
error_entitlement = True
# if not organization:
# error_orgname = True
if not mail:
error_mail = True
if error_username:
error = _("Your idP should release the HTTP_EPPN attribute towards this service<br>")
if error_orgname:
error = error + _("Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service<br>")
if error_entitlement:
error = error + _("Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service<br>")
if error_mail:
error = error + _("Your idP should release the HTTP_SHIB_INETORGPERSON_MAIL attribute towards this service")
if error_username or error_orgname or error_entitlement or error_mail:
return render_to_response('error.html', {'error': error, "missing_attributes": True},
context_instance=RequestContext(request))
try:
user = User.objects.get(username__exact=username)
user.email = mail
user.first_name = firstname
user.last_name = lastname
user.save()
user_exists = True
except User.DoesNotExist:
user_exists = False
user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
if user is not None:
# try:
# peer = Peer.objects.get(domain_name=organization)
# up = UserProfile.objects.get_or_create(user=user,peer=peer)
# except:
# error = _("Your organization's domain name does not match our peers' domain names<br>Please contact Helpdesk to resolve this issue")
# return render_to_response('error.html', {'error': error}, context_instance=RequestContext(request))
# if not user_exists:
# user_activation_notify(user)
# user does not exist... forward to an institution selection form to create profile
try:
profile = user.get_profile()
inst = profile.institution
except UserProfile.DoesNotExist:
form = UserProfileForm()
form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse("manage"))
else:
error = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %user.username
return render_to_response('error.html', {'error': error, 'inactive': True},
context_instance=RequestContext(request))
else:
error = _("Something went wrong during user authentication. Contact your administrator %s" %user)
return render_to_response('error.html', {'error': error,},
context_instance=RequestContext(request))
except Exception as e:
error = _("Invalid login procedure %s" %e)
return render_to_response('error.html', {'error': error,},
context_instance=RequestContext(request))
# Return an 'invalid login' error message.
# return HttpResponseRedirect(reverse("user-routes"))
def geolocate(request):
return render_to_response('front/geolocate.html',
context_instance=RequestContext(request))
def selectinst(request):
if request.method == 'POST':
request_data = request.POST.copy()
user = request_data['user']
form = UserProfileForm(request_data)
if form.is_valid():
userprofile = form.save()
error = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %userprofile.user.username
return render_to_response('error.html', {'error': error, 'inactive': True},
context_instance=RequestContext(request))
else:
form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
def closest(request):
if request.method == 'GET':
......
from django.conf import settings
def MAX_USERNAME_LENGTH():
if hasattr(settings,"MAX_USERNAME_LENGTH"):
return settings.MAX_USERNAME_LENGTH
else:
return 255
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from longerusername.forms import UserCreationForm, UserChangeForm
class LongerUserNameUserAdmin(UserAdmin):
add_form = UserCreationForm
form = UserChangeForm
admin.site.unregister(User)
admin.site.register(User, LongerUserNameUserAdmin)
from django.utils.translation import ugettext as _
from django.core.validators import MaxLengthValidator
from django.contrib.auth import forms as auth_forms
from django import forms
from longerusername import MAX_USERNAME_LENGTH
def update_username_field(field):
field.widget.attrs['maxlength'] = MAX_USERNAME_LENGTH()
field.max_length = MAX_USERNAME_LENGTH()
field.help_text = _("Required, %s characters or fewer. Only letters, "
"numbers, and characters such as @.+_- are "
"allowed." % MAX_USERNAME_LENGTH())
# we need to find the MaxLengthValidator and change its
# limit_value otherwise the auth forms will fail validation
for v in field.validators:
if isinstance(v, MaxLengthValidator):
v.limit_value = MAX_USERNAME_LENGTH()
class UserCreationForm(auth_forms.UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
update_username_field(self.fields['username'])
class UserChangeForm(auth_forms.UserChangeForm):
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
update_username_field(self.fields['username'])
class AuthenticationForm(auth_forms.AuthenticationForm):
def __init__(self, *args, **kwargs):
super(AuthenticationForm, self).__init__(*args, **kwargs)
update_username_field(self.fields['username'])
# encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from longerusername import MAX_USERNAME_LENGTH
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'User.username'
db.alter_column('auth_user', 'username', models.CharField(max_length=MAX_USERNAME_LENGTH()))
def backwards(self, orm):
# Changing field 'User.username'
db.alter_column('auth_user', 'username', models.CharField(max_length=35))
models = {
}
complete_apps = ['django_monkeypatches']
import django
from django.core.validators import MaxLengthValidator
from django.utils.translation import ugettext as _
from django.db.models.signals import class_prepared
from django.conf import settings
from longerusername import MAX_USERNAME_LENGTH
def longer_username_signal(sender, *args, **kwargs):
if (sender.__name__ == "User" and
sender.__module__ == "django.contrib.auth.models"):
patch_user_model(sender)
class_prepared.connect(longer_username_signal)
def patch_user_model(model):
field = model._meta.get_field("username")
field.max_length = MAX_USERNAME_LENGTH()
field.help_text = _("Required, %s characters or fewer. Only letters, "
"numbers, and @, ., +, -, or _ "
"characters." % MAX_USERNAME_LENGTH())
# patch model field validator because validator doesn't change if we change
# max_length
for v in field.validators:
if isinstance(v, MaxLengthValidator):
v.limit_value = MAX_USERNAME_LENGTH()
from django.contrib.auth.models import User
# https://github.com/GoodCloud/django-longer-username/issues/1
# django 1.3.X loads User model before class_prepared signal is connected
# so we patch model after it's prepared
# check if User model is patched
if User._meta.get_field("username").max_length != MAX_USERNAME_LENGTH():
patch_user_model(User)
\ No newline at end of file
from django.contrib.auth.models import User
from django.test import TestCase
class LongerUsernameTests(TestCase):
"""
Unit tests for longerusername app
"""
def setUp(self):
"""
creates a user with a terribly long username
"""
long_username = ''.join([str(i) for i in range(100)])
self.user = User.objects.create_user('test' + long_username, 'test@test.com', 'testpassword')
def testUserCreation(self):
"""
tests that self.user was successfully saved, and can be retrieved
"""
self.assertNotEqual(self.user,None)
User.objects.get(id=self.user.id) # returns DoesNotExist error if the user wasn't created
\ No newline at end of file
# Create your views here.
{{error}}
\ No newline at end of file
......@@ -11,7 +11,7 @@
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<script src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&language=en"></script>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true&language=en"></script>
<style>
......
......@@ -11,7 +11,7 @@
</style>
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/markerclusterer.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var lat = 36.97;
var lng = 23.71;
......@@ -268,7 +268,7 @@
<li><a href="/how/en/">How</a></li>
<li><a href="#">About</a></li>
<li class="nav-header">Institutions</li>
<li><a href="{% url manage %}">{% trans "Management" %}</a></li>
<li><a href="{% url login %}">{% trans "Management" %}</a></li>
</ul>
</div><!--/.well -->
<div><img src="/static/img/keep_calm_eduroam_small.png"></div>
......
......@@ -12,7 +12,7 @@
<div class="span3"></div>
<div class="span9">Institutional eduroam management</div>
</div>
<form class="form-horizontal" method="post" action="{% url django.contrib.auth.views.login %}">
<form class="form-horizontal" method="post" action="{% url login %}">
{% if form.non_field_errors %}
{% for err in form.non_field_errors %}
......
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
</div><!--/span-->
<div class="span10">
<div class="row-fluid">
<!--/span-->
<div class="span10">
<h4>Select you institution</h4>
<hr>
<div class="span1"></div>
<div class="span7">
Excellent! You are a click away from getting into your institution eduroam management.
Select your institution to proceed. Our administrators will activate your account and notify you via e-mail.
</div>
<div class="span12"></div>
<div class="span12">
<form method="POST" class="form-horizontal" action="{% url selectinst %}">
{% csrf_token %}
{% if form.non_field_errors %}
<p class="error">
{{ form.non_field_errors}}
</p>
{% endif %}
<div style="display: none">
{{form.user}}
</div>
<div class="control-group {% if form.institution.errors %} error {% endif %}">
<label class="control-label" for="id_institution"><b>{% trans "Institution" %}</b></label>
<div class="controls">
{{ form.institution }}
{% if form.institution.errors %} <span class="help-inline"> {{ form.institution.errors|join:", " }} </span>
{% endif %} <span class="help-block"> {{ form.institution.help_text }}</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" id="applybutton" value="Apply" class="btn btn-primary"/>
{% trans "Apply" %}</button>
</div>
</div>
</form>
</div>
</div><!--/span-->
<!--/span-->
</div><!--/row-->
</div><!--/span-->
</div><!--/row-->
<hr>
<footer>
<p>
&copy; GRNET NOC - GRNET S.A - 2012
</p>
</footer>
</div><!--/.fluid-container-->
{% endblock %}
{% block subcontent %}
{% endblock %}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment