LibraryUser replaces LibraryCard, used for all backends, has datestamp

pull/1/head
eric 2013-10-10 15:56:40 -04:00
parent d99aaa97c9
commit 9929452ebc
5 changed files with 47 additions and 26 deletions

View File

@ -1,10 +1,22 @@
'''
to make a backend named <backend> you need to...
1. define a function <backend>_authenticate(request, library)
returns true if can request.user can be authenticated to the library, and attaches a credential property to the library object
returns fals if otherwise.
2. define a class <backend>_authenticator
with a process((self, authenticator, success_url, deny_url) method which is expected to return a response
3. make a libraryauth/<backend>_join.html template (authenticator will be in its context) to insert a link or form for a user to join the library
4. if you need to show the user a form, define a model form class <backend>_form with init method __init__(self, request, library, *args, **kwargs)
and model LibraryUser
'''
import logging import logging
from django.db.models import Q from django.db.models import Q
from django import forms from django import forms
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.shortcuts import render from django.shortcuts import render
from .models import Block, IP, UserCard from .models import Block, IP, LibraryUser
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -16,6 +28,7 @@ def ip_authenticate(request, library):
for block in blocks: for block in blocks:
if block.library==library: if block.library==library:
logger.info('%s authenticated for %s from %s'%(request.user, library, ip)) logger.info('%s authenticated for %s from %s'%(request.user, library, ip))
library.credential=ip
return True return True
return False return False
except KeyError: except KeyError:
@ -42,7 +55,7 @@ class cardnum_authenticator():
}) })
class cardnum_form(forms.ModelForm): class cardnum_form(forms.ModelForm):
number = forms.RegexField( credential = forms.RegexField(
label="Enter Your Library Card Number", label="Enter Your Library Card Number",
max_length=20, max_length=20,
regex=r'^\d+$', regex=r'^\d+$',
@ -60,12 +73,12 @@ class cardnum_form(forms.ModelForm):
def clean(self): def clean(self):
library = self.cleaned_data.get('library', None) library = self.cleaned_data.get('library', None)
number = self.cleaned_data.get('number', '') credential = self.cleaned_data.get('credential', '')
for card_pattern in library.card_patterns.all(): for card_pattern in library.card_patterns.all():
if card_pattern.is_valid(number): if card_pattern.is_valid(credential):
return self.cleaned_data return self.cleaned_data
raise forms.ValidationError("the library card number must be VALID.") raise forms.ValidationError("the library card number must be VALID.")
class Meta: class Meta:
model = UserCard model = LibraryUser
widgets = { 'library': forms.HiddenInput, 'user': forms.HiddenInput } widgets = { 'library': forms.HiddenInput, 'user': forms.HiddenInput }

View File

@ -35,14 +35,15 @@ class Migration(SchemaMigration):
)) ))
db.send_create_signal('libraryauth', ['CardPattern']) db.send_create_signal('libraryauth', ['CardPattern'])
# Adding model 'UserCard' # Adding model 'LibraryUser'
db.create_table('libraryauth_usercard', ( db.create_table('libraryauth_libraryuser', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('library', self.gf('django.db.models.fields.related.ForeignKey')(related_name='library_cards', to=orm['libraryauth.Library'])), ('library', self.gf('django.db.models.fields.related.ForeignKey')(related_name='library_users', to=orm['libraryauth.Library'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='library_cards', to=orm['auth.User'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='user_libraries', to=orm['auth.User'])),
('number', self.gf('django.db.models.fields.CharField')(max_length=20)), ('credential', self.gf('django.db.models.fields.CharField')(max_length=30, null=True)),
('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
)) ))
db.send_create_signal('libraryauth', ['UserCard']) db.send_create_signal('libraryauth', ['LibraryUser'])
def backwards(self, orm): def backwards(self, orm):
@ -55,8 +56,8 @@ class Migration(SchemaMigration):
# Deleting model 'CardPattern' # Deleting model 'CardPattern'
db.delete_table('libraryauth_cardpattern') db.delete_table('libraryauth_cardpattern')
# Deleting model 'UserCard' # Deleting model 'LibraryUser'
db.delete_table('libraryauth_usercard') db.delete_table('libraryauth_libraryuser')
models = { models = {
@ -117,12 +118,13 @@ class Migration(SchemaMigration):
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'library'", 'unique': 'True', 'to': "orm['auth.User']"}) 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'library'", 'unique': 'True', 'to': "orm['auth.User']"})
}, },
'libraryauth.usercard': { 'libraryauth.libraryuser': {
'Meta': {'object_name': 'UserCard'}, 'Meta': {'object_name': 'LibraryUser'},
'credential': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True'}),
'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'library': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'library_cards'", 'to': "orm['libraryauth.Library']"}), 'library': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'library_users'", 'to': "orm['libraryauth.Library']"}),
'number': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_libraries'", 'to': "orm['auth.User']"})
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'library_cards'", 'to': "orm['auth.User']"})
} }
} }

View File

@ -17,12 +17,16 @@ class Library(models.Model):
user = models.OneToOneField(User, related_name='library') user = models.OneToOneField(User, related_name='library')
group = models.OneToOneField(Group, related_name='library', null = True) group = models.OneToOneField(Group, related_name='library', null = True)
backend = models.CharField(max_length=10, choices=(('ip','IP authentication'),('cardnum', 'Library Card Number check')),default='ip') backend = models.CharField(max_length=10, choices=(('ip','IP authentication'),('cardnum', 'Library Card Number check')),default='ip')
credential = None
def __unicode__(self): def __unicode__(self):
return self.user.username return self.user.username
def add_user(self, user): def add_user(self, user):
user.groups.add(self.group) user.groups.add(self.group)
(library_user, created) = LibraryUser.objects.get_or_create(library=self, user=user)
library_user.credential=self.credential
library_user.save()
def has_user(self, user): def has_user(self, user):
return self.group in user.groups.all() return self.group in user.groups.all()
@ -258,7 +262,8 @@ class CardPattern(models.Model):
else: else:
return True return True
class UserCard(models.Model): class LibraryUser(models.Model):
library = models.ForeignKey(Library, related_name='library_cards') library = models.ForeignKey(Library, related_name='library_users')
user = models.ForeignKey(User, related_name='library_cards') user = models.ForeignKey(User, related_name='user_libraries')
number = models.CharField(max_length=20) credential = models.CharField(max_length=30, null=True)
date_modified = models.DateTimeField(auto_now=True)

View File

@ -1,11 +1,11 @@
<div class="p_form">To use {{ library }}...{{authenticator.form.non_field_errors}}<br /> <div class="p_form">To use {{ library }}...{{authenticator.form.non_field_errors}}<br />
<form action="{% url join_library library %}#" method="POST" class="std_form " id="join_form"> <form action="{% url join_library library %}#" method="POST" class="std_form " id="join_form">
{% csrf_token %} {% csrf_token %}
{{ authenticator.form.number.label_tag }}: {{ authenticator.form.number }} {{ authenticator.form.credential.label_tag }}: {{ authenticator.form.credential }}
{% if authenticator.form.number.errors %} {% if authenticator.form.credential.errors %}
{{ authenticator.form.number.errors }} {{ authenticator.form.credential.errors }}
{% else %} {% else %}
{{ authenticator.form.number.help_text }} {{ authenticator.form.credential.help_text }}
{% endif %}<br /> {% endif %}<br />
<input type="submit" name="join" value="Make this my Library"> <input type="submit" name="join" value="Make this my Library">
{{ authenticator.form.library }} {{ authenticator.form.library }}

View File

@ -1,3 +1,4 @@
<br />
{% if authenticator.allowed %} {% if authenticator.allowed %}
<a href="{% url join_library authenticator.library %}?next={% url join_library authenticator.library %}" class="fakeinput">Make this my Library</a> <a href="{% url join_library authenticator.library %}?next={% url join_library authenticator.library %}" class="fakeinput">Make this my Library</a>
{% else %} {% else %}