', template_content)
- self.assertNotIn('
', template_content)
- self.assertNotIn('
', template_content)
-
-
-class RegisterViewGetTest(TestCase):
- def setUp(self):
- self.factory = RequestFactory()
-
- def test_get_with_disclaimer_in_tolasite(self):
- site = Site.objects.create(domain='api.toladata.com', name='API')
- TolaSites.objects.create(
- name='TolaData',
- privacy_disclaimer='Nice disclaimer',
- site=site)
-
- request = self.factory.get('')
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- template_content = response.content
- self.assertIn('Nice disclaimer', template_content)
-
- def test_get_with_disclaimer_in_template(self):
- request = self.factory.get('')
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- template_content = response.content
- self.assertIn('Humanitec - Privacy Policy', template_content)
- self.assertIn('Privacy disclaimer accepted', template_content)
-
- def test_get_with_org_organization_uuid(self):
- org = factories.Organization(organization_uuid='123456')
-
- query_params = '?organization_uuid={}'.format(org.organization_uuid)
- request = self.factory.get('/accounts/register/{}'.format(query_params))
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- template_content = response.content
- self.assertIn(('').format(org.name), template_content)
-
- def test_get_with_chargebee_active_sub_in_template(self):
- class ExternalResponse:
- def __init__(self, values):
- self.subscription = Subscription(values)
- self.subscription.status = 'active'
-
- external_response = ExternalResponse(None)
- Subscription.retrieve = Mock(return_value=external_response)
- query_params = '?cus_fname={}&cus_lname={}&cus_email={}&cus_company={}'\
- '&sub_id={}'.format('John', 'Lennon',
- 'johnlennon@test.com', 'The Beatles',
- '1234567890')
- request = self.factory.get('/accounts/register/{}'.format(query_params))
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- template_content = response.content
-
- self.assertIn(
- (''),
- template_content)
- self.assertIn(
- (''),
- template_content)
- self.assertIn(
- (''),
- template_content)
- self.assertIn(
- (''), template_content)
- org = Organization.objects.get(name='The Beatles')
- self.assertEqual(org.chargebee_subscription_id, '1234567890')
-
- def test_get_with_chargebee_cancel_sub_in_template(self):
- class ExternalResponse:
- def __init__(self, values):
- self.subscription = Subscription(values)
- self.subscription.status = 'cancelled'
-
- external_response = ExternalResponse(None)
- Subscription.retrieve = Mock(return_value=external_response)
- query_params = '?cus_fname={}&cus_lname={}&cus_email={}&cus_company={}'\
- '&sub_id={}'.format('John', 'Lennon',
- 'johnlennon@test.com', 'The Beatles',
- '1234567890')
- request = self.factory.get('/accounts/register/{}'.format(query_params))
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- self.assertRaises(
- Organization.DoesNotExist,
- Organization.objects.get, name='The Beatles')
-
- def test_get_with_chargebee_demo(self):
- class ExternalResponse:
- def __init__(self, values):
- self.subscription = Subscription(values)
- self.subscription.status = 'active'
-
- os.environ['APP_BRANCH'] = DEMO_BRANCH
- query_params = '?cus_fname={}&cus_lname={}&cus_email={}&cus_company={}'\
- '&sub_id={}'.format('John', 'Lennon',
- 'johnlennon@test.com', 'The Beatles',
- '1234567890')
- request = self.factory.get('/accounts/register/{}'.format(query_params))
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- self.assertRaises(
- Organization.DoesNotExist,
- Organization.objects.get, name='The Beatles')
- os.environ['APP_BRANCH'] = ''
-
- def test_get_with_chargebee_without_sub_in_template(self):
- json_obj = {
- 'message': "Sorry, we couldn't find that resource",
- 'error_code': 500
- }
- external_response = InvalidRequestError(500, json_obj)
- Subscription.retrieve = Mock(return_value=external_response)
- query_params = '?cus_fname={}&cus_lname={}&cus_email={}&cus_company=' \
- '{}'.format('John', 'Lennon', 'johnlennon@test.com',
- 'The Beatles')
- request = self.factory.get('/accounts/register/{}'.format(query_params))
- response = views.RegisterView.as_view()(request)
- self.assertEqual(response.status_code, 200)
- self.assertRaises(
- Organization.DoesNotExist,
- Organization.objects.get, name='The Beatles')
-
-
-class RegisterViewPostTest(TestCase):
- def setUp(self):
- self.factory = RequestFactory()
- self.organization = factories.Organization(organization_uuid='12345')
- factories.Group(name=ROLE_VIEW_ONLY)
- logging.disable(logging.ERROR)
-
- def tearDown(self):
- logging.disable(logging.NOTSET)
-
- @staticmethod
- def _hotfix_django_bug(request):
- # Django 1.4 bug
- # https://code.djangoproject.com/ticket/17971
- from django.contrib.messages.storage.fallback import FallbackStorage
- setattr(request, 'session', 'session')
- messages = FallbackStorage(request)
- setattr(request, '_messages', messages)
-
- def test_post_organization_not_found(self):
- data = {
- 'org': 'Invalid Org'
- }
- request = self.factory.post(reverse('register'), data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 200)
- template_content = response.content
- self.assertIn('The Organization was not found',
- template_content)
-
- def test_post_fields_not_sent(self):
- data = {
- 'org': self.organization.name
- }
- request = self.factory.post(reverse('register'), data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 200)
- template_content = response.content
- for field in ('username', 'password1', 'password2',
- 'privacy_disclaimer_accepted'):
- msg = (''
- 'This field is required.
'.format(field))
- self.assertIn(msg, template_content)
-
- @patch('tola.track_sync.requests')
- def test_post_success_with_full_name(self, mock_requests):
- mock_requests.post.return_value = Mock(status_code=201)
-
- data = {
- 'first_name': 'John',
- 'last_name': 'Lennon',
- 'email': 'johnlennon@test.com',
- 'username': 'ILoveYoko',
- 'password1': '123456',
- 'password2': '123456',
- 'title': TITLE_CHOICES[0][0],
- 'privacy_disclaimer_accepted': 'on',
- 'org': self.organization.name,
- }
- request = self.factory.post(reverse('register'), data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(reverse('login'), response.url)
-
- tolauser = TolaUser.objects.select_related('user').get(
- name='John Lennon')
- user = tolauser.user
- self.assertEqual(user.first_name, data['first_name'])
- self.assertEqual(user.last_name, data['last_name'])
- self.assertEqual(user.email, data['email'])
- self.assertEqual(tolauser.organization, self.organization)
- self.assertEqual(tolauser.title, data['title'])
- self.assertTrue(User.objects.filter(username='ILoveYoko').exists())
-
- @patch('tola.track_sync.requests')
- def test_post_success_with_first_name(self, mock_requests):
- mock_requests.post.return_value = Mock(status_code=201)
-
- data = {
- 'first_name': 'John',
- 'email': 'johnlennon@test.com',
- 'username': 'ILoveYoko',
- 'password1': '123456',
- 'password2': '123456',
- 'title': TITLE_CHOICES[0][0],
- 'privacy_disclaimer_accepted': 'on',
- 'org': self.organization.name,
- }
- request = self.factory.post(reverse('register'), data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(reverse('login'), response.url)
-
- tolauser = TolaUser.objects.select_related('user').get(
- name='John')
- user = tolauser.user
- self.assertEqual(user.first_name, data['first_name'])
- self.assertEqual(user.email, data['email'])
- self.assertEqual(tolauser.organization, self.organization)
- self.assertEqual(tolauser.title, data['title'])
- self.assertTrue(User.objects.filter(username='ILoveYoko').exists())
-
- @patch('tola.track_sync.requests')
- def test_post_success_with_default_org(self, mock_requests):
- mock_requests.post.return_value = Mock(status_code=201)
- factories.Organization(name=settings.DEFAULT_ORG)
- os.environ['APP_BRANCH'] = DEMO_BRANCH
-
- data = {
- 'first_name': 'John',
- 'last_name': 'Lennon',
- 'email': 'johnlennon@test.com',
- 'username': 'ILoveYoko',
- 'password1': '123456',
- 'password2': '123456',
- 'title': TITLE_CHOICES[0][0],
- 'privacy_disclaimer_accepted': 'on',
- }
- request = self.factory.post(reverse('register'), data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- os.environ['APP_BRANCH'] = ''
- self.assertEqual(response.status_code, 302)
- self.assertEqual(reverse('login'), response.url)
-
- tolauser = TolaUser.objects.select_related('user').get(
- name='John Lennon')
- user = tolauser.user
- self.assertEqual(user.first_name, data['first_name'])
- self.assertEqual(user.last_name, data['last_name'])
- self.assertEqual(user.email, data['email'])
- self.assertEqual(tolauser.organization.name, settings.DEFAULT_ORG)
- self.assertEqual(tolauser.title, data['title'])
- self.assertTrue(User.objects.filter(username='ILoveYoko').exists())
-
- os.environ['APP_BRANCH'] = ''
-
- @patch('tola.track_sync.requests')
- def test_post_success_with_organization_uuid(self, mock_requests):
- mock_requests.post.return_value = Mock(status_code=201)
-
- data = {
- 'first_name': 'John',
- 'email': 'johnlennon@test.com',
- 'username': 'ILoveYoko',
- 'password1': '123456',
- 'password2': '123456',
- 'title': TITLE_CHOICES[0][0],
- 'privacy_disclaimer_accepted': 'on',
- }
- query_params = '?organization_uuid={}'.format(
- self.organization.organization_uuid)
- url = '/accounts/register/{}'.format(query_params)
- request = self.factory.post(url, data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(reverse('login'), response.url)
-
- tolauser = TolaUser.objects.select_related('user').get(
- name='John')
- user = tolauser.user
- self.assertEqual(user.first_name, data['first_name'])
- self.assertEqual(user.email, data['email'])
- self.assertEqual(tolauser.organization, self.organization)
- self.assertEqual(tolauser.title, data['title'])
- self.assertTrue(User.objects.filter(username='ILoveYoko').exists())
-
- @patch('tola.track_sync.requests')
- def test_post_success_with_cus_company(self, mock_requests):
- mock_requests.post.return_value = Mock(status_code=201)
-
- data = {
- 'first_name': 'John',
- 'email': 'johnlennon@test.com',
- 'username': 'ILoveYoko',
- 'password1': '123456',
- 'password2': '123456',
- 'title': TITLE_CHOICES[0][0],
- 'privacy_disclaimer_accepted': 'on',
- }
- query_params = '?cus_company={}'.format(self.organization.name)
- url = '/accounts/register/{}'.format(query_params)
- request = self.factory.post(url, data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(reverse('login'), response.url)
-
- tolauser = TolaUser.objects.select_related('user').get(
- name='John')
- user = tolauser.user
- self.assertEqual(user.first_name, data['first_name'])
- self.assertEqual(user.email, data['email'])
- self.assertEqual(tolauser.organization, self.organization)
- self.assertEqual(tolauser.title, data['title'])
- self.assertTrue(User.objects.filter(username='ILoveYoko').exists())
-
- @patch('tola.track_sync.requests')
- @patch('tola.views.load_strategy')
- def test_post_success_with_partial_pipeline(self, mock_load_strategy,
- mock_requests):
- class PartialTest(object):
- def __init__(self, backend):
- self.backend = backend
-
- class StrategyTest(object):
- def __init__(self, partial):
- self.partial = partial
-
- def partial_load(self, *args):
- return self.partial
-
- partial = PartialTest('blablabla')
- strategy = StrategyTest(partial)
- mock_load_strategy.return_value = strategy
- mock_requests.post.return_value = Mock(status_code=201)
-
- data = {
- 'first_name': 'John',
- 'email': 'johnlennon@test.com',
- 'username': 'ILoveYoko',
- 'password1': '123456',
- 'password2': '123456',
- 'title': TITLE_CHOICES[0][0],
- 'privacy_disclaimer_accepted': 'on',
- }
- query_params = '?organization_uuid={}&partial_token=09876'.format(
- self.organization.organization_uuid)
- url = '/accounts/register/{}'.format(query_params)
- request = self.factory.post(url, data)
- self._hotfix_django_bug(request)
- view = views.RegisterView.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(reverse('social:complete', args=('blablabla', )),
- response.url)
-
- tolauser = TolaUser.objects.select_related('user').get(
- name='John')
- user = tolauser.user
- self.assertEqual(user.first_name, data['first_name'])
- self.assertEqual(user.email, data['email'])
- self.assertEqual(tolauser.organization, self.organization)
- self.assertEqual(tolauser.title, data['title'])
- self.assertTrue(User.objects.filter(username='ILoveYoko').exists())
-
-
-class TolaTrackSiloProxyTest(TestCase):
- def setUp(self):
- self.factory = RequestFactory()
- self.tola_user = factories.TolaUser()
-
- def test_get_unauthenticated_user(self):
- request = self.factory.get('')
- view = views.TolaTrackSiloProxy.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 403)
-
- @override_settings(TOLA_TRACK_URL='https://tolatrack.com')
- @override_settings(TOLA_TRACK_TOKEN='TheToken')
- @patch('tola.views.requests')
- def test_get_authenticated_user_url_without_ending_slash(
- self, mock_requests):
- external_response = ['foo', {'bar': 'baz'}]
- mock_requests.get.return_value = Mock(
- status_code=200, content=json.dumps(external_response))
- request = Mock(user=self.tola_user.user)
- response = views.TolaTrackSiloProxy().get(request)
-
- self.assertEqual(response.status_code, 200)
- self.assertEqual(json.loads(response.content), external_response)
- mock_requests.get.assert_called_once_with(
- 'https://tolatrack.com/api/silo?user_uuid={}'.format(
- self.tola_user.tola_user_uuid),
- headers={'content-type': 'application/json',
- 'Authorization': 'Token TheToken'})
-
- @override_settings(TOLA_TRACK_URL='https://tolatrack.com/')
- @override_settings(TOLA_TRACK_TOKEN='TheToken')
- @patch('tola.views.requests')
- def test_get_authenticated_user_url_with_ending_slash(
- self, mock_requests):
- external_response = ['foo', {'bar': 'baz'}]
- mock_requests.get.return_value = Mock(
- status_code=200, content=json.dumps(external_response))
- request = Mock(user=self.tola_user.user)
- response = views.TolaTrackSiloProxy().get(request)
-
- self.assertEqual(response.status_code, 200)
- self.assertEqual(json.loads(response.content), external_response)
- mock_requests.get.assert_called_once_with(
- 'https://tolatrack.com/api/silo?user_uuid={}'.format(
- self.tola_user.tola_user_uuid),
- headers={'content-type': 'application/json',
- 'Authorization': 'Token TheToken'})
-
- @override_settings(TOLA_TRACK_URL='https://tolatrack.com/')
- @override_settings(TOLA_TRACK_TOKEN='TheToken')
- @patch('tola.views.requests')
- def test_get_gateway_502_exception(
- self, mock_requests):
- mock_requests.get.return_value = Mock(status_code=400)
- request = Mock(user=self.tola_user.user)
- response = views.TolaTrackSiloProxy().get(request)
- self.assertEqual(response.status_code, 502)
-
-
-class TolaTrackSiloDataProxyTest(TestCase):
- def setUp(self):
- self.factory = RequestFactory()
- self.tola_user = factories.TolaUser()
-
- def test_get_unauthenticated_user(self):
- request = self.factory.get('')
- view = views.TolaTrackSiloDataProxy.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 403)
-
- @override_settings(TOLA_TRACK_URL='https://tolatrack.com')
- @override_settings(TOLA_TRACK_TOKEN='TheToken')
- @patch('tola.views.requests')
- def test_get_authenticated_user_url_without_ending_slash(
- self, mock_requests):
- external_response = ['foo', {'bar': 'baz'}]
- mock_requests.get.return_value = Mock(
- status_code=200, content=json.dumps(external_response))
- request = Mock(user=self.tola_user.user)
- response = views.TolaTrackSiloDataProxy().get(request, '123')
-
- self.assertEqual(response.status_code, 200)
- self.assertEqual(json.loads(response.content), external_response)
- mock_requests.get.assert_called_once_with(
- 'https://tolatrack.com/api/silo/123/data',
- headers={'content-type': 'application/json',
- 'Authorization': 'Token TheToken'})
-
- @override_settings(TOLA_TRACK_URL='https://tolatrack.com/')
- @override_settings(TOLA_TRACK_TOKEN='TheToken')
- @patch('tola.views.requests')
- def test_get_authenticated_user_url_with_ending_slash(
- self, mock_requests):
- external_response = ['foo', {'bar': 'baz'}]
- mock_requests.get.return_value = Mock(
- status_code=200, content=json.dumps(external_response))
- request = Mock(user=self.tola_user.user)
- response = views.TolaTrackSiloDataProxy().get(request, '123')
-
- self.assertEqual(response.status_code, 200)
- self.assertEqual(json.loads(response.content), external_response)
- mock_requests.get.assert_called_once_with(
- 'https://tolatrack.com/api/silo/123/data',
- headers={'content-type': 'application/json',
- 'Authorization': 'Token TheToken'})
-
- @override_settings(TOLA_TRACK_URL='https://tolatrack.com/')
- @override_settings(TOLA_TRACK_TOKEN='TheToken')
- @patch('tola.views.requests')
- def test_get_gateway_502_exception(
- self, mock_requests):
- mock_requests.get.return_value = Mock(status_code=400)
- request = Mock(user=self.tola_user.user)
- response = views.TolaTrackSiloDataProxy().get(request, '288')
- self.assertEqual(response.status_code, 502)
-
-
-class LogoutViewTest(TestCase):
- def setUp(self):
- self.user = factories.User()
- self.user.set_password(12345)
- self.user.save()
- self.tola_user = factories.TolaUser(user=self.user)
- self.factory = RequestFactory()
-
- def test_logout_redirect_to_track(self):
- c = Client()
- c.post('/accounts/login/', {'username': self.user.username,
- 'password': '12345'})
- self.user = auth.get_user(c)
- self.assertEqual(self.user.is_authenticated(), True)
-
- response = c.post('/accounts/logout/')
- self.user = auth.get_user(c)
- self.assertEqual(self.user.is_authenticated(), False)
- self.assertEqual(response.status_code, 302)
-
- url_subpath = 'accounts/logout/'
- redirect_url = urljoin(settings.TOLA_TRACK_URL, url_subpath)
- self.assertEqual(response.url, redirect_url)
-
- def test_logout_redirect_to_index(self):
- c = Client()
- response = c.post('/accounts/logout/')
- self.user = auth.get_user(c)
- self.assertEqual(self.user.is_authenticated(), False)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(response.url, '/')
diff --git a/tola/urls.py b/tola/urls.py
deleted file mode 100755
index 0a45ec4a3..000000000
--- a/tola/urls.py
+++ /dev/null
@@ -1,156 +0,0 @@
-import os
-
-from django.conf import settings
-from django.conf.urls import include, url
-from django.conf.urls.static import static
-from django.contrib import admin
-from django.contrib.auth import views as auth_views
-from django.contrib.staticfiles.urls import staticfiles_urlpatterns
-from rest_framework import routers
-
-from formlibrary.views import BinaryFieldViewSet, binary_test
-from tola import views as tola_views
-from feed import views as feed_views
-from tola import DEMO_BRANCH
-
-admin.autodiscover()
-admin.site.site_header = 'TolaActivity administration'
-
-
-# REST FRAMEWORK
-router = routers.DefaultRouter()
-router.register(r'users', feed_views.UserViewSet)
-router.register(r'groups', feed_views.GroupViewSet)
-router.register(r'tolauser', feed_views.TolaUserViewSet)
-router.register(r'tolauserfilter', feed_views.TolaUserFilterViewSet)
-router.register(r'organization', feed_views.OrganizationViewSet)
-router.register(r'country', feed_views.CountryViewSet)
-router.register(r'award', feed_views.AwardViewSet)
-router.register(r'workflowlevel1', feed_views.WorkflowLevel1ViewSet)
-router.register(r'workflowlevel2', feed_views.WorkflowLevel2ViewSet)
-router.register(r'workflowlevel2sort', feed_views.WorkflowLevel2SortViewSet)
-router.register(r'workflowmodules', feed_views.WorkflowModulesViewSet)
-router.register(r'workflowteam', feed_views.WorkflowTeamViewSet)
-router.register(r'workflowlevel1sector', feed_views.WorkflowLevel1SectorViewSet)
-router.register(r'approvaltype', feed_views.ApprovalTypeViewSet)
-router.register(r'approvalworkflow', feed_views.ApprovalWorkflowViewSet)
-router.register(r'milestone', feed_views.MilestoneViewSet)
-router.register(r'checklist', feed_views.ChecklistViewSet)
-router.register(r'sector', feed_views.SectorViewSet)
-router.register(r'projecttype', feed_views.ProjectTypeViewSet)
-router.register(r'office', feed_views.OfficeViewSet)
-router.register(r'budget', feed_views.BudgetViewSet)
-router.register(r'fundcode', feed_views.FundCodeViewSet)
-router.register(r'siteprofile', feed_views.SiteProfileViewSet)
-router.register(r'adminboundaryone', feed_views.ProvinceViewSet)
-router.register(r'adminboundarytwo', feed_views.DistrictViewSet)
-router.register(r'adminboundarythree', feed_views.AdminLevelThreeViewSet)
-router.register(r'adminboundaryfour', feed_views.VillageViewSet)
-router.register(r'frequency', feed_views.FrequencyViewSet)
-router.register(r'indicatortype', feed_views.IndicatorTypeViewSet)
-router.register(r'indicator', feed_views.IndicatorViewSet)
-router.register(r'objective', feed_views.ObjectiveViewSet)
-router.register(r'strategicobjective', feed_views.StrategicObjectiveViewSet)
-router.register(r'level', feed_views.LevelViewSet)
-router.register(r'externalservice', feed_views.ExternalServiceViewSet)
-router.register(r'externalservicerecord', feed_views.ExternalServiceRecordViewSet)
-router.register(r'stakeholder', feed_views.StakeholderViewSet)
-router.register(r'stakeholdertype', feed_views.StakeholderTypeViewSet)
-router.register(r'profiletype', feed_views.ProfileTypeViewSet)
-router.register(r'contact', feed_views.ContactViewSet)
-router.register(r'documentation', feed_views.DocumentationViewSet)
-router.register(r'collecteddata', feed_views.CollectedDataViewSet)
-router.register(r'periodictarget', feed_views.PeriodicTargetViewSet)
-router.register(r'tolatable', feed_views.TolaTableViewSet, base_name='tolatable')
-router.register(r'disaggregationtype', feed_views.DisaggregationTypeViewSet)
-router.register(r'disaggregationlabel', feed_views.DisaggregationLabelViewSet)
-router.register(r'disaggregationvalue', feed_views.DisaggregationValueViewSet)
-router.register(r'checklist', feed_views.ChecklistViewSet)
-router.register(r'organization', feed_views.OrganizationViewSet)
-router.register(r'currency', feed_views.CurrencyViewSet)
-router.register(r'beneficiary', feed_views.BeneficiaryViewSet)
-router.register(r'riskregister', feed_views.RiskRegisterViewSet)
-router.register(r'issueregister', feed_views.IssueRegisterViewSet)
-router.register(r'fieldtype', feed_views.FieldTypeViewSet)
-router.register(r'customformfield', feed_views.CustomFormFieldViewSet)
-router.register(r'customform', feed_views.CustomFormViewSet)
-router.register(r'codedfield', feed_views.CodedFieldViewSet)
-router.register(r'codedfieldvalues', feed_views.CodedFieldValuesViewSet)
-router.register(r'landtype', feed_views.LandTypeViewSet)
-router.register(r'internationalization', feed_views.InternationalizationViewSet)
-router.register(r'dashboard', feed_views.DashboardViewSet)
-router.register(r'widget', feed_views.WidgetViewSet)
-router.register(r'portfolio', feed_views.PortfolioViewSet)
-router.register(r'sectorrelated', feed_views.SectorRelatedViewSet)
-router.register(r'pindicators', feed_views.ProgramIndicatorReadOnlyViewSet, base_name='pindicators')
-# router.register(r'search', search_views.SearchView, base_name='search')
-router.register(r'binary', BinaryFieldViewSet, base_name='binary')
-
-urlpatterns = [
- # Rest framework
- url(r'^check', tola_views.check_view),
- url(r'^api/', include(router.urls)),
- url(r'^binarytest/(?P
\w+)', binary_test),
- url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
-
- # Admin:
- url(r'^admin/', include(admin.site.urls)),
-
- # Index / Homepage
- url(r'^$', tola_views.IndexView.as_view(), name='index'),
-
- # App include of indicator urls
- url(r'^indicators/', include('indicators.urls')),
-
- # App include of customdashboard urls
- url(r'^customdashboard/', include('customdashboard.urls')),
-
- # App include of reports urls
- url(r'^reports/', include('reports.urls')),
-
- # App include of workflow urls
- url(r'^formlibrary/', include('formlibrary.urls')),
-
- # Local login
- url(r'^accounts/login/$', auth_views.LoginView.as_view(
- extra_context={
- 'chargebee_signup_org_url': settings.CHARGEBEE_SIGNUP_ORG_URL,
- 'is_demo_branch': os.getenv('APP_BRANCH') == DEMO_BRANCH
- }),
- name='login'),
- url(r'^accounts/logout/$', tola_views.logout_view, name='logout'),
-
- # Accounts
- url(r'^accounts/profile/$', tola_views.profile, name='profile'),
- url(r'^accounts/register/$', tola_views.RegisterView.as_view(), name='register'),
-
- # Bookmarks
- url(r'^bookmark_list', tola_views.BookmarkList.as_view(), name='bookmark_list'),
- url(r'^bookmark_add', tola_views.BookmarkCreate.as_view(), name='bookmark_add'),
- url(r'^bookmark_update/(?P\w+)/$', tola_views.BookmarkUpdate.as_view(), name='bookmark_update'),
- url(r'^bookmark_delete/(?P\w+)/$', tola_views.BookmarkDelete.as_view(), name='bookmark_delete'),
-
- # Search app URL's
- url(r'^search/', include('search.urls')),
-
- # Auth backend URL's
- url('', include('django.contrib.auth.urls', namespace='auth')),
- url('', include('social_django.urls', namespace='social')),
-
- url(r'^oauth/', include('oauth2_provider.urls', namespace='oauth2_provider')),
- url(r'^oauthuser', tola_views.OAuthUserEndpoint.as_view()),
- url(r'^tolatrack/silo', tola_views.TolaTrackSiloProxy.as_view()),
- url(r'^tolatrackdata/silo/(?P\w+)/$', tola_views.TolaTrackSiloDataProxy.as_view()),
-] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
-
-urlpatterns += staticfiles_urlpatterns()
-
-if settings.DEBUG:
- try:
- import debug_toolbar
- except ImportError:
- pass
- else:
- urlpatterns = [
- url(r'^__debug__/', include(debug_toolbar.urls)),
- ] + urlpatterns
diff --git a/tola/util.py b/tola/util.py
deleted file mode 100755
index e49459d44..000000000
--- a/tola/util.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import unicodedata
-import json
-import requests
-
-from workflow.models import Country, TolaUser, TolaSites, WorkflowTeam
-from django.contrib.auth.models import User
-from django.core.mail import mail_admins, EmailMessage
-from django.core.exceptions import PermissionDenied
-from django.contrib.auth.decorators import user_passes_test
-
-
-def getCountry(user):
- """
- Returns the object the view is displaying.
- """
- # get users country from django cosign module
- user_countries = TolaUser.objects.all().filter(user__id=user.id).values('countries')
-
- get_countries = Country.objects.all().filter(id__in=user_countries)
-
- return get_countries
-
-
-def emailGroup(country, group, link, subject, message, submiter=None):
- # email incident to admins in each country assoicated with the
- # projects program
- for single_country in country.all():
- country = Country.objects.all().filter(country=single_country)
- getGroupEmails = User.objects.all().filter(tola_user=group,tola_user__country=country).values_list('email', flat=True)
- email_link = link
- formatted_email = email_link
- subject = str(subject)
- message = str(message) + formatted_email
-
- to = [str(item) for item in getGroupEmails]
- if submiter:
- to.append(submiter)
- print to
-
- email = EmailMessage(subject, message, 'systems@mercycorps.org',
- to)
-
- email.send()
-
- mail_admins(subject, message, fail_silently=False)
-
-
-def get_table(url, data=None):
- """
- Get table data from a Silo. First get the Data url from the silo details
- then get data and return it
- :param url: URL to silo meta detail info
- :param data:
- :return: json dump of table data
- """
- token = TolaSites.objects.get(site_id=1)
- if token.tola_tables_token:
- headers = {'content-type': 'application/json',
- 'Authorization': 'Token ' + token.tola_tables_token }
- else:
- headers = {'content-type': 'application/json'}
- print "Token Not Found"
-
- response = requests.get(url,headers=headers, verify=True)
- if data:
- data = json.loads(response.content['data'])
- else:
- data = json.loads(response.content)
- return data
-
-
-def group_excluded(*group_names, **url):
- # If user is in the group passed in permission denied
- def in_groups(u):
- if u.is_authenticated():
- if not bool(u.groups.filter(name__in=group_names)):
- return True
- raise PermissionDenied
- return False
-
- return user_passes_test(in_groups)
-
-
-def group_required(*group_names, **url):
- # Requires user membership in at least one of the groups passed in.
- def in_groups(u):
- if u.is_authenticated():
- if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
- return True
- raise PermissionDenied
- return False
- return user_passes_test(in_groups)
diff --git a/tola/views.py b/tola/views.py
deleted file mode 100755
index cc4d48999..000000000
--- a/tola/views.py
+++ /dev/null
@@ -1,406 +0,0 @@
-import json
-import os
-from urlparse import urljoin
-import warnings
-import requests
-import logging
-
-from django.conf import settings
-from django.contrib import messages
-from django.contrib.auth import logout
-from django.contrib.auth.decorators import login_required
-from django.contrib.auth.mixins import LoginRequiredMixin
-from django.contrib.auth.models import Group
-from django.http import HttpResponse, HttpResponseRedirect
-from django.shortcuts import render, redirect, get_object_or_404
-from django.urls import reverse
-from django.utils.decorators import method_decorator
-from django.views.generic.base import TemplateView, View
-from django.views.generic.edit import CreateView, UpdateView, DeleteView
-from django.views.generic.list import ListView
-from oauth2_provider.views.generic import ProtectedResourceView
-
-from social_django.utils import load_strategy
-from chargebee import APIError, InvalidRequestError, Subscription
-
-from tola import DEMO_BRANCH
-from tola.track_sync import register_user
-from feed.serializers import TolaUserSerializer, OrganizationSerializer, \
- CountrySerializer
-from tola.forms import RegistrationForm, NewUserRegistrationForm, \
- NewTolaUserRegistrationForm, BookmarkForm
-from workflow.models import (Organization, TolaSites, TolaUser, TolaBookmarks,
- FormGuidance, ROLE_VIEW_ONLY, TolaSites)
-
-logger = logging.getLogger(__name__)
-
-
-@method_decorator(login_required, name='dispatch')
-class IndexView(LoginRequiredMixin, TemplateView):
- template_name = 'index.html'
-
- def get_context_data(self, **kwargs):
- context = super(IndexView, self).get_context_data(**kwargs)
- if settings.TOLA_ACTIVITY_URL and settings.TOLA_TRACK_URL:
- extra_context = {
- 'tolaactivity_url': settings.TOLA_ACTIVITY_URL,
- 'tolatrack_url': settings.TOLA_TRACK_URL,
- }
- else: # CE only
- warnings.warn(
- "TolaSite.front_end_url and TolaSite.tola_tables_url are "
- "deprecated. Please, set instead TOLA_ACTIVITY_URL and "
- "TOLA_TRACK_URL values in settings", DeprecationWarning)
- tola_site = TolaSites.objects.get(name="TolaData")
- extra_context = {
- 'tolaactivity_url': tola_site.front_end_url,
- 'tolatrack_url': tola_site.tola_tables_url,
- }
- context.update(extra_context)
- return context
-
-
-class RegisterView(View):
- template_name = 'registration/register.html'
-
- def _get_context_data(self, params, **kwargs):
- context = {}
- try: # CE only
- privacy_disclaimer = TolaSites.objects.values_list(
- 'privacy_disclaimer', flat=True).get(name="TolaData")
- except TolaSites.DoesNotExist:
- privacy_disclaimer = ''
- context['privacy_disclaimer'] = privacy_disclaimer
-
- if kwargs:
- context.update(kwargs)
-
- # Auto fill some fields based on query parameters and set partial token
- if params:
- if 'organization_uuid' in params:
- org_uuid = params.get('organization_uuid', '')
- org_name = Organization.objects.values_list(
- 'name', flat=True).get(organization_uuid=org_uuid)
- else:
- org_name = params.get('cus_company', '')
- first_name = params.get('cus_fname', '')
- last_name = params.get('cus_lname', '')
- email = params.get('cus_email', '')
- context['form_tolauser'] = NewTolaUserRegistrationForm(org=org_name)
- context['form_user'] = NewUserRegistrationForm(
- first_name=first_name, last_name=last_name, email=email)
- return context
-
- def _get_chargebee_data(self, params, **kwargs):
- context = {}
- context.update(kwargs)
- org_name = params.get('cus_company', '')
- sub_id = params.get('sub_id', '')
-
- if not org_name and not sub_id:
- return context
-
- # Check subscription id and
- # Create an organization defined on ChargeBee
- try:
- result = Subscription.retrieve(sub_id)
- except InvalidRequestError:
- logger.info('The given subscription id ({}) is not valid.'.format(
- sub_id))
- except APIError as e:
- logger.warn(e)
- else:
- subscription = result.subscription
- if subscription.status in ['active', 'in_trial']:
- org = Organization.objects.get_or_create(name=org_name)[0]
- org.chargebee_subscription_id = sub_id
- org.save()
- return context
-
- def get(self, request, *args, **kwargs):
- extra_context = {
- 'form_user': NewUserRegistrationForm(),
- 'form_tolauser': NewTolaUserRegistrationForm(),
- }
- if (request.GET.get('sub_id', None) and
- os.getenv('APP_BRANCH') != DEMO_BRANCH):
- extra_context = self._get_chargebee_data(
- request.GET, **extra_context)
- context = self._get_context_data(request.GET, **extra_context)
- return render(request, self.template_name, context)
-
- def post(self, request, *args, **kwargs):
- register_form = request.POST.copy()
-
- # Check if an organization uuid was given and create the user
- # associate with that organization
- if 'org' not in register_form:
- org_name = ''
- if 'organization_uuid' in request.GET:
- org_uuid = request.GET.get('organization_uuid', '')
- org_name = Organization.objects.values_list(
- 'name', flat=True).get(organization_uuid=org_uuid)
- elif 'cus_company' in request.GET:
- org_name = request.GET.get('cus_company', '')
- register_form.appendlist('org', org_name)
- partial_token = request.GET.get('partial_token', '')
-
- # Create the user and tola user django forms for validation
- form_user = NewUserRegistrationForm(register_form)
- form_tolauser = NewTolaUserRegistrationForm(register_form)
-
- if form_user.is_valid() and form_tolauser.is_valid():
- user = form_user.save()
- user.groups.add(Group.objects.get(name=ROLE_VIEW_ONLY))
-
- tolauser = form_tolauser.save(commit=False)
- tolauser.user = user
- tolauser.organization = form_tolauser.cleaned_data.get('org')
- tolauser.name = ' '.join([user.first_name, user.last_name]).strip()
- tolauser.save()
- register_form.appendlist('tola_user_uuid', tolauser.tola_user_uuid)
- register_user(register_form, tolauser)
- messages.error(
- request,
- 'Thank you, You have been registered as a new user.',
- fail_silently=False)
- if partial_token:
- strategy = load_strategy()
- partial = strategy.partial_load(partial_token)
- return redirect('social:complete', backend=partial.backend)
- return HttpResponseRedirect(reverse('login'))
-
- context = self._get_context_data(request.GET, **{
- 'form_user': form_user,
- 'form_tolauser': form_tolauser,
- })
- return render(request, self.template_name, context)
-
-
-def profile(request):
- """
- Update a User profile using built in Django Users Model if the user is logged in
- otherwise redirect them to registration version
- """
- if request.user.is_authenticated():
- obj = get_object_or_404(TolaUser, user=request.user)
- form = RegistrationForm(request.POST or None, instance=obj, initial={'username': request.user})
-
- if request.method == 'POST':
- if form.is_valid():
- form.save()
- messages.error(request, 'Your profile has been updated.', fail_silently=False)
-
- return render(request, "registration/profile.html", {
- 'form': form, 'helper': RegistrationForm.helper
- })
- else:
- return HttpResponseRedirect("/accounts/register")
-
-
-class BookmarkList(ListView):
- """
- Bookmark Report filtered by project
- """
- model = TolaBookmarks
- template_name = 'registration/bookmark_list.html'
-
- def get(self, request, *args, **kwargs):
- get_user = TolaUser.objects.all().filter(user=request.user)
- get_bookmarks = TolaBookmarks.objects.all().filter(user=get_user)
-
- return render(request, self.template_name, {'getBookmarks': get_bookmarks})
-
-
-class BookmarkCreate(CreateView):
- """
- Using Bookmark Form for new bookmark per user
- """
- model = TolaBookmarks
- template_name = 'registration/bookmark_form.html'
-
- def dispatch(self, request, *args, **kwargs):
- try:
- self.guidance = FormGuidance.objects.get(form="Bookmarks")
- except FormGuidance.DoesNotExist:
- self.guidance = None
- return super(BookmarkCreate, self).dispatch(request, *args, **kwargs)
-
- # add the request to the kwargs
- def get_form_kwargs(self):
- kwargs = super(BookmarkCreate, self).get_form_kwargs()
- kwargs['request'] = self.request
- return kwargs
-
- def get_initial(self):
-
- initial = {
- 'user': self.request.user,
- }
-
- return initial
-
- def form_invalid(self, form):
-
- messages.error(self.request, 'Invalid Form', fail_silently=False)
-
- return self.render_to_response(self.get_context_data(form=form))
-
- def form_valid(self, form):
- form.save()
- messages.success(self.request, 'Success, Bookmark Created!')
- latest = TolaBookmarks.objects.latest('id')
- redirect_url = '/bookmark_update/' + str(latest.id)
- return HttpResponseRedirect(redirect_url)
-
- form_class = BookmarkForm
-
-
-class BookmarkUpdate(UpdateView):
- """
- Bookmark Form Update an existing site profile
- """
- model = TolaBookmarks
- template_name = 'registration/bookmark_form.html'
-
- def dispatch(self, request, *args, **kwargs):
- try:
- self.guidance = FormGuidance.objects.get(form="Bookmarks")
- except FormGuidance.DoesNotExist:
- self.guidance = None
- return super(BookmarkUpdate, self).dispatch(request, *args, **kwargs)
-
- def get_initial(self):
-
- initial = {
- 'user': self.request.user,
- }
-
- return initial
-
- def form_invalid(self, form):
-
- messages.error(self.request, 'Invalid Form', fail_silently=False)
-
- return self.render_to_response(self.get_context_data(form=form))
-
- def form_valid(self, form):
- form.save()
- messages.success(self.request, 'Success, Bookmark Updated!')
- latest = TolaBookmarks.objects.latest('id')
- redirect_url = '/bookmark_update/' + str(latest.id)
- return HttpResponseRedirect(redirect_url)
-
- form_class = BookmarkForm
-
-
-class BookmarkDelete(DeleteView):
- """
- Bookmark Form Delete an existing bookmark
- """
- model = TolaBookmarks
- template_name = 'registration/bookmark_confirm_delete.html'
- success_url = "/bookmark_list"
-
- def dispatch(self, request, *args, **kwargs):
- return super(BookmarkDelete, self).dispatch(request, *args, **kwargs)
-
- def form_invalid(self, form):
-
- messages.error(self.request, 'Invalid Form', fail_silently=False)
-
- return self.render_to_response(self.get_context_data(form=form))
-
- def form_valid(self, form):
-
- form.save()
-
- messages.success(self.request, 'Success, Bookmark Deleted!')
- return self.render_to_response(self.get_context_data(form=form))
-
- form_class = BookmarkForm
-
-
-def logout_view(request):
- """
- Logout a user in activity and track
- """
- # Redirect to track, so the user will
- # be logged out there as well
- if request.user.is_authenticated:
- logout(request)
- url_subpath = 'accounts/logout/'
- url = urljoin(settings.TOLA_TRACK_URL, url_subpath)
- return HttpResponseRedirect(url)
-
- return HttpResponseRedirect("/")
-
-
-def check_view(request):
- return HttpResponse("Hostname " + request.get_host())
-
-
-def oauth_user_view(request):
- return HttpResponse("Hostname "+request.get_host())
-
-
-class OAuthUserEndpoint(ProtectedResourceView):
- def get(self, request, *args, **kwargs):
- user = request.user
- body = {
- 'username': user.username,
- 'email': user.email,
- 'id': user.id,
- 'first_name': user.first_name,
- 'last_name': user.last_name,
-
- }
- tola_user = TolaUser.objects.all().filter(user=user)
- if len(tola_user) == 1:
- body["tola_user"] = TolaUserSerializer(instance=tola_user[0], context={'request': request}).data
- body["organization"] = OrganizationSerializer(instance=tola_user[0].organization,
- context={'request': request}).data
- body["country"] = CountrySerializer(instance=tola_user[0].country, context={'request': request}).data
-
- return HttpResponse(json.dumps(body))
-
-
-class TolaTrackSiloProxy(ProtectedResourceView):
- def get(self, request, *args, **kwargs):
- headers = {
- "content-type": "application/json",
- 'Authorization': 'Token {}'.format(settings.TOLA_TRACK_TOKEN),
- }
-
- tola_user_uuid = TolaUser.objects.values_list(
- 'tola_user_uuid', flat=True).get(user=request.user)
-
- url_subpath = 'api/silo'
- url_base = urljoin(settings.TOLA_TRACK_URL, url_subpath)
- url = '{}?user_uuid={}'.format(url_base, tola_user_uuid)
-
- response = requests.get(url, headers=headers)
- if response.status_code == 200:
- return HttpResponse(response.content)
- else:
- reason = 'URL: {}. Responded with status code {}'.format(
- url, response.status_code)
- return HttpResponse(status=502, reason=reason)
-
-
-class TolaTrackSiloDataProxy(ProtectedResourceView):
- def get(self, request, silo_id, *args, **kwargs):
- headers = {
- "content-type": "application/json",
- 'Authorization': 'Token {}'.format(settings.TOLA_TRACK_TOKEN),
- }
-
- url_subpath = 'api/silo/{}/data'.format(silo_id)
- url = urljoin(settings.TOLA_TRACK_URL, url_subpath)
- response = requests.get(url, headers=headers)
- if response.status_code == 200:
- return HttpResponse(response.content)
- else:
- reason = 'URL: {}. Responded with status code {}'.format(
- url, response.status_code)
- return HttpResponse(status=502, reason=reason)