commit c7c0ec585dffef6f0aabe8254bbf74c284933131
Author: Giorgos Korfiatis <gkorf@grnet.gr>
Date:   Mon Feb 25 16:22:50 2013 +0200

    Add per-user limit on pending applications
    
    Add UserSettings model for storing integer-valued settings.
    If an entry is missing, a default synnefo setting is consulted.
    
    The limit can be set/unset with snf-manage user-update.

diff --git a/snf-astakos-app/astakos/im/functions.py b/snf-astakos-app/astakos/im/functions.py
index 1a4b950..266a52f 100644
--- a/snf-astakos-app/astakos/im/functions.py
+++ b/snf-astakos-app/astakos/im/functions.py
@@ -54,6 +54,7 @@ from smtplib import SMTPException
 from datetime import datetime
 from functools import wraps
 
+import astakos.im.settings as astakos_settings
 from astakos.im.settings import (
     DEFAULT_CONTACT_EMAIL, SITENAME, BASEURL, LOGGING_LEVEL,
     VERIFICATION_EMAIL_SUBJECT, ACCOUNT_CREATION_SUBJECT,
@@ -67,6 +68,7 @@ from astakos.im.settings import (
 from astakos.im.notifications import build_notification, NotificationError
 from astakos.im.models import (
     AstakosUser, Invitation, ProjectMembership, ProjectApplication, Project,
+    UserSetting,
     PendingMembershipError, get_resource_names, new_chain)
 from astakos.im.project_notif import (
     membership_change_notify, membership_enroll_notify,
@@ -694,6 +696,11 @@ def submit_application(kw, request_user=None):
             m = _(astakos_messages.NOT_ALLOWED)
             raise PermissionDenied(m)
 
+    reached, limit = reached_pending_application_limit(request_user.id, precursor)
+    if reached:
+        m = _(astakos_messages.REACHED_PENDING_APPLICATION_LIMIT) % limit
+        raise PermissionDenied(m)
+
     application = ProjectApplication(**kw)
 
     if precursor is None:
@@ -808,3 +815,70 @@ def get_by_chain_or_404(chain_id):
             raise Http404
         else:
             return None, application
+
+
+def get_user_setting(user_id, key):
+    try:
+        setting = UserSetting.objects.get(
+            user=user_id, setting=key)
+        return setting.value
+    except UserSetting.DoesNotExist:
+        return getattr(astakos_settings, key)
+
+
+def set_user_setting(user_id, key, value):
+    try:
+        setting = UserSetting.objects.get_for_update(
+            user=user_id, setting=key)
+    except UserSetting.DoesNotExist:
+        setting = UserSetting(user_id=user_id, setting=key)
+    setting.value = value
+    setting.save()
+
+
+def unset_user_setting(user_id, key):
+    UserSetting.objects.filter(user=user_id, setting=key).delete()
+
+
+PENDING_APPLICATION_LIMIT_SETTING = 'PENDING_APPLICATION_LIMIT'
+
+def get_pending_application_limit(user_id):
+    key = PENDING_APPLICATION_LIMIT_SETTING
+    return get_user_setting(user_id, key)
+
+
+def set_pending_application_limit(user_id, value):
+    key = PENDING_APPLICATION_LIMIT_SETTING
+    return set_user_setting(user_id, key, value)
+
+
+def unset_pending_application_limit(user_id):
+    key = PENDING_APPLICATION_LIMIT_SETTING
+    return unset_user_setting(user_id, key)
+
+
+def _reached_pending_application_limit(user_id):
+    limit = get_pending_application_limit(user_id)
+
+    PENDING = ProjectApplication.PENDING
+    pending = ProjectApplication.objects.filter(
+        applicant__id=user_id, state=PENDING).count()
+
+    return pending >= limit, limit
+
+
+def reached_pending_application_limit(user_id, precursor=None):
+    reached, limit = _reached_pending_application_limit(user_id)
+
+    if precursor is None:
+        return reached, limit
+
+    chain = precursor.chain
+    objs = ProjectApplication.objects
+    q = objs.filter(chain=chain, state=ProjectApplication.PENDING)
+    has_pending = q.exists()
+
+    if not has_pending:
+        return reached, limit
+
+    return False, limit
diff --git a/snf-astakos-app/astakos/im/management/commands/user-show.py b/snf-astakos-app/astakos/im/management/commands/user-show.py
index b3cc233..cfc73ad 100644
--- a/snf-astakos-app/astakos/im/management/commands/user-show.py
+++ b/snf-astakos-app/astakos/im/management/commands/user-show.py
@@ -71,6 +71,11 @@ class Command(BaseCommand):
             for resource, limits in quotas.iteritems():
                 showable_quotas[resource] = limits.capacity
 
+            settings_dict = {}
+            settings = user.settings()
+            for setting in settings:
+                settings_dict[setting.setting] = setting.value
+
             kv = OrderedDict(
                 [
                     ('id', user.id),
@@ -97,9 +102,13 @@ class Command(BaseCommand):
                     ('email_verified', user.email_verified),
                     ('username', user.username),
                     ('activation_sent_date', user.activation_sent),
-                    ('resources', showable_quotas),
                 ])
 
+            if settings_dict:
+                kv['settings'] = settings_dict
+
+            kv['resources'] = showable_quotas
+
             if get_latest_terms():
                 has_signed_terms = user.signed_terms
                 kv['has_signed_terms'] = has_signed_terms
diff --git a/snf-astakos-app/astakos/im/management/commands/user-update.py b/snf-astakos-app/astakos/im/management/commands/user-update.py
index a24f24f..60b09de 100644
--- a/snf-astakos-app/astakos/im/management/commands/user-update.py
+++ b/snf-astakos-app/astakos/im/management/commands/user-update.py
@@ -34,12 +34,15 @@
 from optparse import make_option
 from datetime import datetime
 
+from django.utils.translation import ugettext as _
 from django.core.management.base import BaseCommand, CommandError
 from django.contrib.auth.models import Group
 from django.core.exceptions import ValidationError
 
 from astakos.im.models import AstakosUser
-from astakos.im.functions import activate, deactivate
+from astakos.im.functions import (activate, deactivate,
+                                  set_pending_application_limit,
+                                  unset_pending_application_limit)
 from ._common import remove_user_permission, add_user_permission
 
 
@@ -102,6 +105,17 @@ class Command(BaseCommand):
         make_option('--delete-permission',
                     dest='delete-permission',
                     help="Delete user permission"),
+        make_option('--set-max-pending',
+                    dest='pending',
+                    metavar='INT',
+                    help=("Set limit on user's maximum pending "
+                          "project applications")),
+        make_option('--unset-max-pending',
+                    dest='unset_pending',
+                    action='store_true',
+                    default=False,
+                    help=("Restore default limit of user's maximum pending "
+                          "project applications")),
     )
 
     def handle(self, *args, **options):
@@ -109,7 +123,8 @@ class Command(BaseCommand):
             raise CommandError("Please provide a user ID")
 
         if args[0].isdigit():
-            user = AstakosUser.objects.get(id=int(args[0]))
+            user_id = int(args[0])
+            user = AstakosUser.objects.get(id=user_id)
         else:
             raise CommandError("Invalid ID")
 
@@ -202,3 +217,17 @@ class Command(BaseCommand):
 
         if password:
             self.stdout.write('User\'s new password: %s\n' % password)
+
+        pending = options.get('pending')
+        if pending:
+            try:
+                pending = int(pending)
+            except ValueError as e:
+                m = _("Expected integer argument")
+                raise CommandError(m)
+            else:
+                set_pending_application_limit(user_id, pending)
+
+        unset_pending = options.get('unset_pending')
+        if unset_pending:
+            unset_pending_application_limit(user_id)
diff --git a/snf-astakos-app/astakos/im/messages.py b/snf-astakos-app/astakos/im/messages.py
index 32bb885..1f56abe 100644
--- a/snf-astakos-app/astakos/im/messages.py
+++ b/snf-astakos-app/astakos/im/messages.py
@@ -194,6 +194,20 @@ APPLICATION_CANNOT_DISMISS              =   "Cannot dismiss application %s in st
 APPLICATION_CANNOT_CANCEL               =   "Cannot cancel application %s in state '%s'"
 APPLICATION_CANCELLED                   =   "Your project request has been cancelled."
 
+REACHED_PENDING_APPLICATION_LIMIT = ("You have reached the maximum number "
+                                     "of pending project applications: %s.")
+
+PENDING_APPLICATION_LIMIT_ADD = \
+    ("You are not allowed to create a new project "
+     "because you have reached the maximum [%s] for "
+     "pending project applications. "
+     "Consider cancelling any unnecessary ones.")
+
+PENDING_APPLICATION_LIMIT_MODIFY = \
+    ("You are not allowed to modify this project "
+     "because you have reached the maximum [%s] for "
+     "pending project applications. "
+     "Consider cancelling any unnecessary ones.")
 
 # Auth providers messages
 AUTH_PROVIDER_NOT_ACTIVE                     =   "'%(provider)s' is disabled."
diff --git a/snf-astakos-app/astakos/im/migrations/0023_auto__add_usersetting__add_unique_usersetting_user_setting.py b/snf-astakos-app/astakos/im/migrations/0023_auto__add_usersetting__add_unique_usersetting_user_setting.py
new file mode 100644
index 0000000..f1f640e
--- /dev/null
+++ b/snf-astakos-app/astakos/im/migrations/0023_auto__add_usersetting__add_unique_usersetting_user_setting.py
@@ -0,0 +1,281 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'UserSetting'
+        db.create_table('im_usersetting', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['im.AstakosUser'])),
+            ('setting', self.gf('django.db.models.fields.CharField')(max_length=255)),
+            ('value', self.gf('django.db.models.fields.IntegerField')()),
+        ))
+        db.send_create_signal('im', ['UserSetting'])
+
+        # Adding unique constraint on 'UserSetting', fields ['user', 'setting']
+        db.create_unique('im_usersetting', ['user_id', 'setting'])
+
+
+    def backwards(self, orm):
+        
+        # Removing unique constraint on 'UserSetting', fields ['user', 'setting']
+        db.delete_unique('im_usersetting', ['user_id', 'setting'])
+
+        # Deleting model 'UserSetting'
+        db.delete_table('im_usersetting')
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.additionalmail': {
+            'Meta': {'object_name': 'AdditionalMail'},
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'activation_sent': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'disturbed_quota': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '4'}),
+            'policy': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.Resource']", 'null': 'True', 'through': "orm['im.AstakosUserQuota']", 'symmetrical': 'False'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}),
+            'uuid': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True'})
+        },
+        'im.astakosuserauthprovider': {
+            'Meta': {'ordering': "('module', 'created')", 'unique_together': "(('identifier', 'module', 'user'),)", 'object_name': 'AstakosUserAuthProvider'},
+            'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'affiliation': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'auth_backend': ('django.db.models.fields.CharField', [], {'default': "'astakos'", 'max_length': '255'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'info_data': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
+            'module': ('django.db.models.fields.CharField', [], {'default': "'local'", 'max_length': '255'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'auth_providers'", 'to': "orm['im.AstakosUser']"})
+        },
+        'im.astakosuserquota': {
+            'Meta': {'unique_together': "(('resource', 'user'),)", 'object_name': 'AstakosUserQuota'},
+            'capacity': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'max_digits': '38', 'decimal_places': '0'}),
+            'export_limit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'import_limit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'quantity': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '0', 'max_digits': '38', 'decimal_places': '0'}),
+            'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Resource']"}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"})
+        },
+        'im.chain': {
+            'Meta': {'object_name': 'Chain'},
+            'chain': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+        },
+        'im.emailchange': {
+            'Meta': {'object_name': 'EmailChange'},
+            'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'requested_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchanges'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        },
+        'im.pendingthirdpartyuser': {
+            'Meta': {'unique_together': "(('provider', 'third_party_identifier'),)", 'object_name': 'PendingThirdPartyUser'},
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'info': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'token': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'im.project': {
+            'Meta': {'object_name': 'Project'},
+            'application': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'project'", 'unique': 'True', 'to': "orm['im.ProjectApplication']"}),
+            'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'deactivation_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'deactivation_reason': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
+            'id': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'chained_project'", 'unique': 'True', 'primary_key': 'True', 'db_column': "'id'", 'to': "orm['im.Chain']"}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
+            'is_modified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
+            'last_approval_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.AstakosUser']", 'through': "orm['im.ProjectMembership']", 'symmetrical': 'False'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True', 'null': 'True', 'db_index': 'True'}),
+            'state': ('django.db.models.fields.IntegerField', [], {'default': '1', 'db_index': 'True'})
+        },
+        'im.projectapplication': {
+            'Meta': {'unique_together': "(('chain', 'id'),)", 'object_name': 'ProjectApplication'},
+            'applicant': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects_applied'", 'to': "orm['im.AstakosUser']"}),
+            'chain': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'chained_apps'", 'db_column': "'chain'", 'to': "orm['im.Chain']"}),
+            'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'end_date': ('django.db.models.fields.DateTimeField', [], {}),
+            'homepage': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'issue_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'limit_on_members_number': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
+            'member_join_policy': ('django.db.models.fields.IntegerField', [], {}),
+            'member_leave_policy': ('django.db.models.fields.IntegerField', [], {}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
+            'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects_owned'", 'to': "orm['im.AstakosUser']"}),
+            'precursor_application': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.ProjectApplication']", 'null': 'True', 'blank': 'True'}),
+            'resource_grants': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['im.Resource']", 'null': 'True', 'through': "orm['im.ProjectResourceGrant']", 'blank': 'True'}),
+            'response_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'start_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'state': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'})
+        },
+        'im.projectmembership': {
+            'Meta': {'unique_together': "(('person', 'project'),)", 'object_name': 'ProjectMembership'},
+            'acceptance_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'db_index': 'True'}),
+            'application': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'memberships'", 'null': 'True', 'to': "orm['im.ProjectApplication']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
+            'is_pending': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
+            'leave_request_date': ('django.db.models.fields.DateField', [], {'null': 'True'}),
+            'pending_application': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'pending_memberships'", 'null': 'True', 'to': "orm['im.ProjectApplication']"}),
+            'pending_serial': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'db_index': 'True'}),
+            'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}),
+            'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Project']"}),
+            'request_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'state': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'})
+        },
+        'im.projectmembershiphistory': {
+            'Meta': {'object_name': 'ProjectMembershipHistory'},
+            'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'person': ('django.db.models.fields.BigIntegerField', [], {}),
+            'project': ('django.db.models.fields.BigIntegerField', [], {}),
+            'reason': ('django.db.models.fields.IntegerField', [], {}),
+            'serial': ('django.db.models.fields.BigIntegerField', [], {})
+        },
+        'im.projectresourcegrant': {
+            'Meta': {'unique_together': "(('resource', 'project_application'),)", 'object_name': 'ProjectResourceGrant'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'member_capacity': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'member_export_limit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'member_import_limit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'project_application': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.ProjectApplication']", 'null': 'True'}),
+            'project_capacity': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'project_export_limit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'project_import_limit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '100000000000000000000000000000000L', 'max_digits': '38', 'decimal_places': '0'}),
+            'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Resource']"})
+        },
+        'im.resource': {
+            'Meta': {'unique_together': "(('service', 'name'),)", 'object_name': 'Resource'},
+            'desc': ('django.db.models.fields.TextField', [], {'null': 'True'}),
+            'group': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'meta': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.ResourceMetadata']", 'symmetrical': 'False'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'service': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Service']"}),
+            'unit': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
+            'uplimit': ('synnefo.lib.db.intdecimalfield.IntDecimalField', [], {'default': '0', 'max_digits': '38', 'decimal_places': '0'})
+        },
+        'im.resourcemetadata': {
+            'Meta': {'object_name': 'ResourceMetadata'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
+            'value': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.serial': {
+            'Meta': {'object_name': 'Serial'},
+            'serial': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+        },
+        'im.service': {
+            'Meta': {'ordering': "('order',)", 'object_name': 'Service'},
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'icon': ('django.db.models.fields.FilePathField', [], {'max_length': '100', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
+            'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
+            'url': ('django.db.models.fields.FilePathField', [], {'max_length': '100'})
+        },
+        'im.sessioncatalog': {
+            'Meta': {'object_name': 'SessionCatalog'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sessions'", 'null': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.usersetting': {
+            'Meta': {'unique_together': "(('user', 'setting'),)", 'object_name': 'UserSetting'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'setting': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}),
+            'value': ('django.db.models.fields.IntegerField', [], {})
+        }
+    }
+
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/models.py b/snf-astakos-app/astakos/im/models.py
index 0b541aa..53144a5 100644
--- a/snf-astakos-app/astakos/im/models.py
+++ b/snf-astakos-app/astakos/im/models.py
@@ -837,6 +837,9 @@ class AstakosUser(User):
             return False
         return True
 
+    def settings(self):
+        return UserSetting.objects.filter(user=self)
+
 
 class AstakosUserAuthProviderManager(models.Manager):
 
@@ -1195,6 +1198,17 @@ class SessionCatalog(models.Model):
     user = models.ForeignKey(AstakosUser, related_name='sessions', null=True)
 
 
+class UserSetting(models.Model):
+    user = models.ForeignKey(AstakosUser)
+    setting = models.CharField(max_length=255)
+    value = models.IntegerField()
+
+    objects = ForUpdateManager()
+
+    class Meta:
+        unique_together = ("user", "setting")
+
+
 ### PROJECTS ###
 ################
 
diff --git a/snf-astakos-app/astakos/im/settings.py b/snf-astakos-app/astakos/im/settings.py
index 6da8a7b..207dfaf 100644
--- a/snf-astakos-app/astakos/im/settings.py
+++ b/snf-astakos-app/astakos/im/settings.py
@@ -340,6 +340,12 @@ TRANSLATE_UUIDS = getattr(settings, 'ASTAKOS_TRANSLATE_UUIDS', False)
 # Users that can approve or deny project applications from the web.
 PROJECT_ADMINS = getattr(settings, 'ASTAKOS_PROJECT_ADMINS', set())
 
+# Maximum pending project applications per applicant.
+# This is to reduce the volume of applications
+# in case users abuse the mechanism.
+PENDING_APPLICATION_LIMIT = getattr(settings,
+                                    'ASTAKOS_PENDING_APPLICATION_LIMIT', 1)
+
 # OAuth2 Twitter credentials.
 TWITTER_TOKEN = getattr(settings, 'ASTAKOS_TWITTER_TOKEN', '')
 TWITTER_SECRET = getattr(settings, 'ASTAKOS_TWITTER_SECRET', '')
diff --git a/snf-astakos-app/astakos/im/views.py b/snf-astakos-app/astakos/im/views.py
index 1822be6..fad1948 100644
--- a/snf-astakos-app/astakos/im/views.py
+++ b/snf-astakos-app/astakos/im/views.py
@@ -99,6 +99,7 @@ from astakos.im.functions import (
     invite,
     send_activation as send_activation_func,
     SendNotificationError,
+    reached_pending_application_limit,
     accept_membership, reject_membership, remove_membership, cancel_membership,
     leave_project, join_project, enroll_member, can_join_request, can_leave_request,
     get_related_project_id, get_by_chain_or_404,
@@ -1045,6 +1046,16 @@ def _update_object(request, model=None, object_id=None, slug=None,
 @signed_terms_required
 @login_required
 def project_add(request):
+
+    user = request.user
+    reached, limit = reached_pending_application_limit(user.id)
+    if reached:
+        m = _(astakos_messages.PENDING_APPLICATION_LIMIT_ADD) % limit
+        messages.error(request, m)
+        next = reverse('astakos.im.views.project_list')
+        next = restrict_next(next, domain=COOKIE_DOMAIN)
+        return redirect(next)
+
     resource_groups = RESOURCES_PRESENTATION_DATA.get('groups', {})
     resource_catalog = ()
     result = callpoint.list_resources()
@@ -1157,6 +1168,14 @@ def project_modify(request, application_id):
         m = _(astakos_messages.NOT_ALLOWED)
         raise PermissionDenied(m)
 
+    reached, limit = reached_pending_application_limit(user.id, app)
+    if reached:
+        m = _(astakos_messages.PENDING_APPLICATION_LIMIT_MODIFY) % limit
+        messages.error(request, m)
+        next = reverse('astakos.im.views.project_list')
+        next = restrict_next(next, domain=COOKIE_DOMAIN)
+        return redirect(next)
+
     resource_groups = RESOURCES_PRESENTATION_DATA.get('groups', {})
     resource_catalog = ()
     result = callpoint.list_resources()
diff --git a/snf-astakos-app/conf/20-snf-astakos-app-settings.conf b/snf-astakos-app/conf/20-snf-astakos-app-settings.conf
index a1f73f1..9b44ef3 100644
--- a/snf-astakos-app/conf/20-snf-astakos-app-settings.conf
+++ b/snf-astakos-app/conf/20-snf-astakos-app-settings.conf
@@ -283,6 +283,11 @@
 # UUIDs of users that can approve or deny project applications from the web.
 # ASTAKOS_PROJECT_ADMINS = set() # e.g. set(['01234567-89ab-cdef-0123-456789abcdef'])
 
+# Maximum pending project applications per applicant.
+# This is to reduce the volume of applications
+# in case users abuse the mechanism.
+#ASTAKOS_PENDING_APPLICATION_LIMIT = 1
+
 # OAuth2 Twitter credentials.
 #ASTAKOS_TWITTER_KEY = ''
 #ASTAKOS_TWITTER_SECRET = ''
