Commit de9d1507 authored by Kostas Papadimitriou's avatar Kostas Papadimitriou
Browse files

astakos: Replace some explicit settings imports

importing setting names explicitly makes it hard to write tests that
depend on specific setting values and polutes the module namespace.

In this commit only settings that are currently used in tests where
refactored.
parent 70e7ed69
...@@ -42,7 +42,6 @@ from django.template import Context, loader ...@@ -42,7 +42,6 @@ from django.template import Context, loader
from django.contrib.auth import ( from django.contrib.auth import (
login as auth_login, login as auth_login,
logout as auth_logout) logout as auth_logout)
from django.conf import settings
from django.contrib.auth.models import AnonymousUser from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.db import IntegrityError from django.db import IntegrityError
...@@ -54,7 +53,6 @@ from smtplib import SMTPException ...@@ -54,7 +53,6 @@ from smtplib import SMTPException
from datetime import datetime from datetime import datetime
from functools import wraps from functools import wraps
import astakos.im.settings as astakos_settings
from astakos.im.settings import ( from astakos.im.settings import (
CONTACT_EMAIL, SITENAME, BASEURL, LOGGING_LEVEL, CONTACT_EMAIL, SITENAME, BASEURL, LOGGING_LEVEL,
VERIFICATION_EMAIL_SUBJECT, ACCOUNT_CREATION_SUBJECT, VERIFICATION_EMAIL_SUBJECT, ACCOUNT_CREATION_SUBJECT,
...@@ -64,8 +62,7 @@ from astakos.im.settings import ( ...@@ -64,8 +62,7 @@ from astakos.im.settings import (
PROJECT_CREATION_SUBJECT, PROJECT_APPROVED_SUBJECT, PROJECT_CREATION_SUBJECT, PROJECT_APPROVED_SUBJECT,
PROJECT_TERMINATION_SUBJECT, PROJECT_SUSPENSION_SUBJECT, PROJECT_TERMINATION_SUBJECT, PROJECT_SUSPENSION_SUBJECT,
PROJECT_MEMBERSHIP_CHANGE_SUBJECT, PROJECT_MEMBERSHIP_CHANGE_SUBJECT,
PROJECT_MEMBER_JOIN_POLICIES, PROJECT_MEMBER_LEAVE_POLICIES, HELPDESK, PROJECT_MEMBER_JOIN_POLICIES, PROJECT_MEMBER_LEAVE_POLICIES)
ADMINS, MANAGERS)
from astakos.im.notifications import build_notification, NotificationError from astakos.im.notifications import build_notification, NotificationError
from astakos.im.models import ( from astakos.im.models import (
AstakosUser, Invitation, ProjectMembership, ProjectApplication, Project, AstakosUser, Invitation, ProjectMembership, ProjectApplication, Project,
...@@ -79,7 +76,7 @@ from astakos.im.project_notif import ( ...@@ -79,7 +76,7 @@ from astakos.im.project_notif import (
application_submit_notify, application_approve_notify, application_submit_notify, application_approve_notify,
application_deny_notify, application_deny_notify,
project_termination_notify, project_suspension_notify) project_termination_notify, project_suspension_notify)
from astakos.im import settings
import astakos.im.messages as astakos_messages import astakos.im.messages as astakos_messages
from astakos.quotaholder.exception import NoCapacityError from astakos.quotaholder.exception import NoCapacityError
...@@ -147,7 +144,7 @@ def _send_admin_notification(template_name, ...@@ -147,7 +144,7 @@ def _send_admin_notification(template_name,
dictionary = dictionary or {} dictionary = dictionary or {}
message = render_to_string(template_name, dictionary) message = render_to_string(template_name, dictionary)
sender = settings.SERVER_EMAIL sender = settings.SERVER_EMAIL
recipient_list = [e[1] for e in HELPDESK + MANAGERS] recipient_list = [e[1] for e in settings.HELPDESK + settings.MANAGERS]
try: try:
send_mail(subject, message, sender, recipient_list, send_mail(subject, message, sender, recipient_list,
connection=get_connection()) connection=get_connection())
...@@ -177,7 +174,7 @@ def send_helpdesk_notification(user, template_name='im/helpdesk_notification.txt ...@@ -177,7 +174,7 @@ def send_helpdesk_notification(user, template_name='im/helpdesk_notification.txt
{'user': user} {'user': user}
) )
sender = settings.SERVER_EMAIL sender = settings.SERVER_EMAIL
recipient_list = [e[1] for e in HELPDESK + MANAGERS] recipient_list = [e[1] for e in settings.HELPDESK + settings.MANAGERS]
try: try:
send_mail(_(HELPDESK_NOTIFICATION_EMAIL_SUBJECT) % {'user': user.email}, send_mail(_(HELPDESK_NOTIFICATION_EMAIL_SUBJECT) % {'user': user.email},
message, sender, recipient_list, connection=get_connection()) message, sender, recipient_list, connection=get_connection())
...@@ -246,7 +243,7 @@ def send_greeting(user, email_template_name='im/welcome_email.txt'): ...@@ -246,7 +243,7 @@ def send_greeting(user, email_template_name='im/welcome_email.txt'):
def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'): def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'):
subject = _(FEEDBACK_EMAIL_SUBJECT) subject = _(FEEDBACK_EMAIL_SUBJECT)
from_email = settings.SERVER_EMAIL from_email = settings.SERVER_EMAIL
recipient_list = [e[1] for e in HELPDESK] recipient_list = [e[1] for e in settings.HELPDESK]
content = render_to_string(email_template_name, { content = render_to_string(email_template_name, {
'message': msg, 'message': msg,
'data': data, 'data': data,
...@@ -894,7 +891,7 @@ def get_user_setting(user_id, key): ...@@ -894,7 +891,7 @@ def get_user_setting(user_id, key):
user=user_id, setting=key) user=user_id, setting=key)
return setting.value return setting.value
except UserSetting.DoesNotExist: except UserSetting.DoesNotExist:
return getattr(astakos_settings, key) return getattr(settings, key)
def set_user_setting(user_id, key, value): def set_user_setting(user_id, key, value):
......
...@@ -26,7 +26,7 @@ SERVER_EMAIL = settings.SERVER_EMAIL ...@@ -26,7 +26,7 @@ SERVER_EMAIL = settings.SERVER_EMAIL
IM_MODULES = getattr(settings, 'ASTAKOS_IM_MODULES', ['local']) IM_MODULES = getattr(settings, 'ASTAKOS_IM_MODULES', ['local'])
# Force user profile verification # Force user profile verification
FORCE_PROFILE_UPDATE = getattr(settings, 'ASTAKOS_FORCE_PROFILE_UPDATE', True) FORCE_PROFILE_UPDATE = getattr(settings, 'ASTAKOS_FORCE_PROFILE_UPDATE', False)
#Enable invitations #Enable invitations
INVITATIONS_ENABLED = getattr(settings, 'ASTAKOS_INVITATIONS_ENABLED', False) INVITATIONS_ENABLED = getattr(settings, 'ASTAKOS_INVITATIONS_ENABLED', False)
......
...@@ -66,22 +66,24 @@ astakos_settings.RECAPTCHA_ENABLED = False ...@@ -66,22 +66,24 @@ astakos_settings.RECAPTCHA_ENABLED = False
settings.LOGGING_SETUP['disable_existing_loggers'] = False settings.LOGGING_SETUP['disable_existing_loggers'] = False
# shortcut decorators to override provider settings
prefixes = {'im': 'ASTAKOS_', 'providers': 'AUTH_PROVIDER_', # e.g. shibboleth_settings(ENABLED=True) will set
'shibboleth': 'AUTH_PROVIDER_SHIBBOLETH_', # ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_ENABLED = True in global synnefo settings
'local': 'AUTH_PROVIDER_LOCAL_'} prefixes = {'providers': 'AUTH_PROVIDER_',
'shibboleth': 'ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_',
'local': 'ASTAKOS_AUTH_PROVIDER_LOCAL_'}
im_settings = functools.partial(with_settings, astakos_settings) im_settings = functools.partial(with_settings, astakos_settings)
provider_settings = functools.partial(with_settings, astakos_settings,
prefix=prefixes['providers'])
shibboleth_settings = functools.partial(with_settings, shibboleth_settings = functools.partial(with_settings,
astakos_settings, settings,
prefix=prefixes['shibboleth']) prefix=prefixes['shibboleth'])
localauth_settings = functools.partial(with_settings, astakos_settings, localauth_settings = functools.partial(with_settings, settings,
prefix=prefixes['local']) prefix=prefixes['local'])
class AstakosTestClient(Client): class AstakosTestClient(Client):
pass pass
class ShibbolethClient(AstakosTestClient): class ShibbolethClient(AstakosTestClient):
""" """
A shibboleth agnostic client. A shibboleth agnostic client.
...@@ -182,6 +184,7 @@ class ShibbolethTests(TestCase): ...@@ -182,6 +184,7 @@ class ShibbolethTests(TestCase):
astakos_settings.IM_MODULES = ['local', 'shibboleth'] astakos_settings.IM_MODULES = ['local', 'shibboleth']
astakos_settings.MODERATION_ENABLED = True astakos_settings.MODERATION_ENABLED = True
@im_settings(FORCE_PROFILE_UPDATE=False)
def test_create_account(self): def test_create_account(self):
client = ShibbolethClient() client = ShibbolethClient()
...@@ -233,21 +236,23 @@ class ShibbolethTests(TestCase): ...@@ -233,21 +236,23 @@ class ShibbolethTests(TestCase):
'last_name': 'Mitroglou', 'last_name': 'Mitroglou',
'provider': 'shibboleth'} 'provider': 'shibboleth'}
signup_url = reverse('signup')
# invlid email # invlid email
post_data['email'] = 'kpap' post_data['email'] = 'kpap'
r = client.post('/im/signup', post_data) r = client.post(signup_url, post_data)
self.assertContains(r, token) self.assertContains(r, token)
# existing email # existing email
existing_user = get_local_user('test@test.com') existing_user = get_local_user('test@test.com')
post_data['email'] = 'test@test.com' post_data['email'] = 'test@test.com'
r = client.post('/im/signup', post_data) r = client.post(signup_url, post_data)
self.assertContains(r, messages.EMAIL_USED) self.assertContains(r, messages.EMAIL_USED)
existing_user.delete() existing_user.delete()
# and finally a valid signup # and finally a valid signup
post_data['email'] = 'kpap@grnet.gr' post_data['email'] = 'kpap@grnet.gr'
r = client.post('/im/signup', post_data, follow=True) r = client.post(signup_url, post_data, follow=True)
self.assertContains(r, messages.NOTIFICATION_SENT) self.assertContains(r, messages.NOTIFICATION_SENT)
# everything is ok in our db # everything is ok in our db
...@@ -267,8 +272,6 @@ class ShibbolethTests(TestCase): ...@@ -267,8 +272,6 @@ class ShibbolethTests(TestCase):
cn="Kostas Papadimitriou", ) cn="Kostas Papadimitriou", )
r = client.get("/im/login/shibboleth?", follow=True) r = client.get("/im/login/shibboleth?", follow=True)
self.assertContains(r, 'is pending moderation') self.assertContains(r, 'is pending moderation')
r = client.get("/im/profile", follow=True)
self.assertRedirects(r, 'http://testserver/im/?next=/im/profile')
# admin activates our user # admin activates our user
u = AstakosUser.objects.get(username="kpap@grnet.gr") u = AstakosUser.objects.get(username="kpap@grnet.gr")
...@@ -434,7 +437,7 @@ class ShibbolethTests(TestCase): ...@@ -434,7 +437,7 @@ class ShibbolethTests(TestCase):
# we can reenable the local provider by setting a password # we can reenable the local provider by setting a password
r = client.get("/im/password_change", follow=True) r = client.get("/im/password_change", follow=True)
r = client.post("/im/password_change", {'new_password1':'111', r = client.post("/im/password_change", {'new_password1': '111',
'new_password2': '111'}, 'new_password2': '111'},
follow=True) follow=True)
user = r.context['request'].user user = r.context['request'].user
...@@ -539,7 +542,8 @@ class TestLocal(TestCase): ...@@ -539,7 +542,8 @@ class TestLocal(TestCase):
form = forms.LocalUserCreationForm(data) form = forms.LocalUserCreationForm(data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@with_settings(settings, HELPDESK=(('support','support@synnefo.org'),)) @im_settings(HELPDESK=(('support', 'support@synnefo.org'),))
@im_settings(FORCE_PROFILE_UPDATE=False)
def test_local_provider(self): def test_local_provider(self):
self.helpdesk_email = astakos_settings.HELPDESK[0][1] self.helpdesk_email = astakos_settings.HELPDESK[0][1]
# enable moderation # enable moderation
...@@ -564,7 +568,6 @@ class TestLocal(TestCase): ...@@ -564,7 +568,6 @@ class TestLocal(TestCase):
self.assertFalse(user.activation_sent) # activation automatically sent self.assertFalse(user.activation_sent) # activation automatically sent
# admin gets notified and activates the user from the command line # admin gets notified and activates the user from the command line
self.assertEqual(len(get_mailbox(self.helpdesk_email)), 1) self.assertEqual(len(get_mailbox(self.helpdesk_email)), 1)
r = self.client.post('/im/local', {'username': 'kpap@grnet.gr', r = self.client.post('/im/local', {'username': 'kpap@grnet.gr',
'password': 'password'}) 'password': 'password'})
...@@ -782,20 +785,20 @@ class TestAuthProviderViews(TestCase): ...@@ -782,20 +785,20 @@ class TestAuthProviderViews(TestCase):
@shibboleth_settings(AUTOMODERATE_POLICY=True) @shibboleth_settings(AUTOMODERATE_POLICY=True)
@im_settings(IM_MODULES=['shibboleth', 'local']) @im_settings(IM_MODULES=['shibboleth', 'local'])
@im_settings(MODERATION_ENABLED=True) @im_settings(MODERATION_ENABLED=True)
@im_settings(FORCE_PROFILE_UPDATE=False)
def test_user(self): def test_user(self):
Profile = AuthProviderPolicyProfile Profile = AuthProviderPolicyProfile
Pending = PendingThirdPartyUser Pending = PendingThirdPartyUser
User = AstakosUser User = AstakosUser
oldpendinguser = User.objects.create(email="newuser@grnet.gr") User.objects.create(email="newuser@grnet.gr")
olduser = get_local_user("olduser@grnet.gr") get_local_user("olduser@grnet.gr")
cl_olduser = ShibbolethClient() cl_olduser = ShibbolethClient()
olduser2 = get_local_user("olduser2@grnet.gr") get_local_user("olduser2@grnet.gr")
cl_olduser2 = ShibbolethClient() ShibbolethClient()
cl_newuser = ShibbolethClient() cl_newuser = ShibbolethClient()
cl_newuser2 = Client() cl_newuser2 = Client()
policy = ('only_academic', 'shibboleth')
academic_group, created = Group.objects.get_or_create( academic_group, created = Group.objects.get_or_create(
name='academic-login') name='academic-login')
academic_users = academic_group.user_set academic_users = academic_group.user_set
...@@ -1201,7 +1204,8 @@ class TestProjects(TestCase): ...@@ -1201,7 +1204,8 @@ class TestProjects(TestCase):
self.service = Service.objects.create(name="service1", self.service = Service.objects.create(name="service1",
api_url="http://service.api") api_url="http://service.api")
self.resource = Resource.objects.create(name="service1.resource", self.resource = Resource.objects.create(name="service1.resource",
uplimit=100) uplimit=100,
service=self.service)
self.admin = get_local_user("projects-admin@synnefo.org") self.admin = get_local_user("projects-admin@synnefo.org")
self.admin.uuid = 'uuid1' self.admin.uuid = 'uuid1'
self.admin.save() self.admin.save()
......
...@@ -37,7 +37,8 @@ from astakos.im.forms import ( ...@@ -37,7 +37,8 @@ from astakos.im.forms import (
ExtendedPasswordResetForm, ExtendedPasswordResetForm,
ExtendedPasswordChangeForm, ExtendedPasswordChangeForm,
ExtendedSetPasswordForm, LoginForm) ExtendedSetPasswordForm, LoginForm)
from astakos.im.settings import IM_MODULES, INVITATIONS_ENABLED, EMAILCHANGE_ENABLED
from astakos.im import settings
urlpatterns = patterns( urlpatterns = patterns(
'astakos.im.views', 'astakos.im.views',
...@@ -81,14 +82,14 @@ urlpatterns = patterns( ...@@ -81,14 +82,14 @@ urlpatterns = patterns(
) )
if EMAILCHANGE_ENABLED: if settings.EMAILCHANGE_ENABLED:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.views', 'astakos.im.views',
url(r'^email_change/?$', 'change_email', {}, name='email_change'), url(r'^email_change/?$', 'change_email', {}, name='email_change'),
url(r'^email_change/confirm/(?P<activation_key>\w+)/?$', 'change_email', {}, url(r'^email_change/confirm/(?P<activation_key>\w+)/?$', 'change_email', {},
name='email_change_confirm')) name='email_change_confirm'))
if 'local' in IM_MODULES: if 'local' in settings.IM_MODULES:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.target', 'astakos.im.target',
url(r'^local/?$', 'local.login'), url(r'^local/?$', 'local.login'),
...@@ -113,32 +114,32 @@ if 'local' in IM_MODULES: ...@@ -113,32 +114,32 @@ if 'local' in IM_MODULES:
url(r'^local/password/reset/complete/?$', 'password_reset_complete') url(r'^local/password/reset/complete/?$', 'password_reset_complete')
) )
if INVITATIONS_ENABLED: if settings.INVITATIONS_ENABLED:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.views', 'astakos.im.views',
url(r'^invite/?$', 'invite', {}, name='invite')) url(r'^invite/?$', 'invite', {}, name='invite'))
if 'shibboleth' in IM_MODULES: if 'shibboleth' in settings.IM_MODULES:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.target', 'astakos.im.target',
url(r'^login/shibboleth/?$', 'shibboleth.login'), url(r'^login/shibboleth/?$', 'shibboleth.login'),
) )
if 'twitter' in IM_MODULES: if 'twitter' in settings.IM_MODULES:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.target', 'astakos.im.target',
url(r'^login/twitter/?$', 'twitter.login'), url(r'^login/twitter/?$', 'twitter.login'),
url(r'^login/twitter/authenticated/?$', url(r'^login/twitter/authenticated/?$',
'twitter.authenticated')) 'twitter.authenticated'))
if 'google' in IM_MODULES: if 'google' in settings.IM_MODULES:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.target', 'astakos.im.target',
url(r'^login/google/?$', 'google.login'), url(r'^login/google/?$', 'google.login'),
url(r'^login/google/authenticated/?$', url(r'^login/google/authenticated/?$',
'google.authenticated')) 'google.authenticated'))
if 'linkedin' in IM_MODULES: if 'linkedin' in settings.IM_MODULES:
urlpatterns += patterns( urlpatterns += patterns(
'astakos.im.target', 'astakos.im.target',
url(r'^login/linkedin/?$', 'linkedin.login'), url(r'^login/linkedin/?$', 'linkedin.login'),
......
...@@ -47,9 +47,8 @@ from django.core.exceptions import ValidationError, ObjectDoesNotExist ...@@ -47,9 +47,8 @@ from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from astakos.im.models import AstakosUser, Invitation from astakos.im.models import AstakosUser, Invitation
from astakos.im.settings import (
COOKIE_DOMAIN, FORCE_PROFILE_UPDATE, LOGIN_SUCCESS_URL)
from astakos.im.functions import login from astakos.im.functions import login
from astakos.im import settings
import astakos.im.messages as astakos_messages import astakos.im.messages as astakos_messages
...@@ -170,9 +169,10 @@ def prepare_response(request, user, next='', renew=False): ...@@ -170,9 +169,10 @@ def prepare_response(request, user, next='', renew=False):
except ValidationError, e: except ValidationError, e:
return HttpResponseBadRequest(e) return HttpResponseBadRequest(e)
next = restrict_next(next, domain=COOKIE_DOMAIN) next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser: if settings.FORCE_PROFILE_UPDATE and \
not user.is_verified and not user.is_superuser:
params = '' params = ''
if next: if next:
params = '?' + urlencode({'next': next}) params = '?' + urlencode({'next': next})
...@@ -186,7 +186,7 @@ def prepare_response(request, user, next='', renew=False): ...@@ -186,7 +186,7 @@ def prepare_response(request, user, next='', renew=False):
request.session.set_expiry(user.auth_token_expires) request.session.set_expiry(user.auth_token_expires)
if not next: if not next:
next = LOGIN_SUCCESS_URL next = settings.LOGIN_SUCCESS_URL
response['Location'] = next response['Location'] = next
response.status_code = 302 response.status_code = 302
......
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