Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
12 changes: 6 additions & 6 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ jobs:
run: |
poetry sync

- name: Run Server-side linting with pytest
# Only run on new files for now-- for all changes, filter is ACMRTUXB
# Check manage.py to prevent a crash if no files are selected.
- name: Run Server-side linting with Ruff
run: |
poetry run pylint $(git diff --name-only --diff-filter=A origin/${{github.base_ref}} | grep -E "(.py$)") manage.py
Comment thread
fnets marked this conversation as resolved.
poetry run ruff check designsafe/apps

- name: Run Server-side formatting with black
- name: Run Server-side formatting with Ruff
# Only run on new files for now-- for all changes, filter is ACMRTUXB
# Check manage.py to prevent a crash if no files are selected.
run: |
poetry run black $(git diff --name-only --diff-filter=A origin/${{github.base_ref}} | grep -E "(.py$)") manage.py --check
poetry run ruff format $(git diff --name-only --diff-filter=A origin/${{github.base_ref}} | grep -E "(.py$)") manage.py --check

Client_Side_Unit_Tests:
runs-on: ubuntu-22.04
Expand Down
1 change: 0 additions & 1 deletion designsafe/apps/accounts/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
from django.contrib import admin

# Register your models here.
1 change: 1 addition & 0 deletions designsafe/apps/accounts/apps.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.apps import AppConfig


class DesignSafeAccountsConfig(AppConfig):
name = 'designsafe.apps.accounts'
label = 'designsafe_accounts'
Expand Down
43 changes: 24 additions & 19 deletions designsafe/apps/accounts/forms.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import re
import logging
import re

from django import forms
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils.translation import gettext as _
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import gettext as _
from pytas.http import TASClient
from snowpenguin.django.recaptcha2.fields import ReCaptchaField
from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget

from .models import (DesignSafeProfile, NotificationPreferences,
DesignSafeProfileNHInterests, DesignSafeProfileResearchActivities,
DesignSafeProfileNHTechnicalDomains)
from termsandconditions.models import TermsAndConditions, UserTermsAndConditions
from pytas.http import TASClient

from .models import (
DesignSafeProfile,
DesignSafeProfileNHInterests,
DesignSafeProfileNHTechnicalDomains,
DesignSafeProfileResearchActivities,
NotificationPreferences,
)

LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -161,7 +165,7 @@ class ChangePasswordForm(forms.Form):

def __init__(self, *args, **kwargs):
self._username = kwargs.pop('username')
super(ChangePasswordForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def clean(self):
cleaned_data = self.cleaned_data
Expand All @@ -182,8 +186,8 @@ def clean(self):
err_msg = mark_safe(
'The current password you provided is incorrect. Please try again. '
'If you do not remember your current password you can '
'<a href="%s" tabindex="-1">reset your password</a> with an email '
'confirmation.' % reset_link)
f'<a href="{reset_link}" tabindex="-1">reset your password</a> with an email '
'confirmation.')
self.add_error('current_password', err_msg)

def save(self):
Expand Down Expand Up @@ -218,7 +222,8 @@ def clean(self):
try:
tas = TASClient()
user = tas.get_user(username=username)
except:
except Exception:
LOGGER.exception("")
msg = 'The username provided does not match an existing user.'
self.add_error('username', msg)
raise forms.ValidationError(msg)
Expand All @@ -244,7 +249,7 @@ class UserProfileForm(forms.Form):
gender = forms.ChoiceField(label='Gender', choices=GENDER_OPTIONS)

def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)


class TasUserProfileAdminForm(forms.Form):
Expand Down Expand Up @@ -380,7 +385,7 @@ class UserRegistrationForm(UserProfileForm, ProfessionalProfileForm):
'bio', 'website', 'orcid_id', 'professional_level', 'research_activities']

def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.fields['institutionId'].choices = get_institution_choices()
self.fields['institutionId'].choices += (('-1', 'My Institution is not listed'),)
self.fields['countryId'].choices = get_country_choices()
Expand Down Expand Up @@ -438,7 +443,7 @@ def save(self, source='DesignSafe', pi_eligibility=INELIGIBLE):
safe_data = tas_data.copy()
safe_data['password'] = safe_data['confirmPassword'] = '********'

LOGGER.info('Attempting new user registration: %s' % safe_data)
LOGGER.info('Attempting new user registration: %s', safe_data)
tas_user = TASClient().save_user(None, tas_data)

# create local user
Expand All @@ -447,7 +452,7 @@ def save(self, source='DesignSafe', pi_eligibility=INELIGIBLE):
# the user should not exist
user = UserModel.objects.get(username=data['username'])
LOGGER.warning('On TAS registration, local user already existed? '
'user=%s' % user)
'user=%s', user)
except UserModel.DoesNotExist:
user = UserModel.objects.create_user(
username=data['username'],
Expand Down Expand Up @@ -486,13 +491,13 @@ def save(self, source='DesignSafe', pi_eligibility=INELIGIBLE):
pro_profile.save()

# terms of use
LOGGER.info('Prior to Registration, %s %s <%s> agreed to Terms of Use' % (
data['firstName'], data['lastName'], data['email']))
LOGGER.info('Prior to Registration, %s %s <%s> agreed to Terms of Use',
data['firstName'], data['lastName'], data['email'])
try:
terms = TermsAndConditions.get_active()
user_terms = UserTermsAndConditions(user=user, terms=terms)
user_terms.save()
except:
except Exception:
LOGGER.exception('Error saving UserTermsAndConditions for user=%s', user)

return tas_user
Expand Down
18 changes: 11 additions & 7 deletions designsafe/apps/accounts/integrations.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.conf import settings
from importlib import import_module
import logging
from importlib import import_module

from django.conf import settings

logger = logging.getLogger(__name__)

Expand All @@ -11,15 +11,19 @@ def get_integrations():

for app in settings.INSTALLED_APPS:
try:
mod = import_module('%s.integrations' % app)
mod = import_module(f"{app}.integrations")
try:
app_integrations += mod.provide_integrations()
except AttributeError:
continue
except:
logger.warning('Call to module.provide_integrations fail for module: %s' % mod.__name__)
except:
except Exception:
logger.exception("")
logger.warning(
"Call to module.provide_integrations fail for module: %s",
mod.__name__,
)
except Exception:
logger.exception("")
continue

return app_integrations

16 changes: 8 additions & 8 deletions designsafe/apps/accounts/models.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import logging

import six
from django.conf import settings
from django.db import models
from django.db import connections, DatabaseError
from django.utils.translation import gettext_lazy as _
from django.core.mail import send_mail
from django.db import DatabaseError, connections, models
from django.utils.translation import gettext_lazy as _
from pytas.http import TASClient
import logging
import six

logger = logging.getLogger(__name__)


class NEESUser(object):
class NEESUser:

def __init__(self, **kwargs):
for k, v in six.iteritems(kwargs):
Expand Down Expand Up @@ -123,6 +123,6 @@ class NotificationPreferences(models.Model):

class Meta:
permissions = (
('view_notification_subscribers', 'Can view list of users subscribed to a '
'notification type'),
('view_notification_subscribers', ('Can view list of users subscribed to a '
'notification type')),
)
22 changes: 10 additions & 12 deletions designsafe/apps/accounts/tasks.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import csv
import io
import logging
from django.conf import settings

# from agavepy.agave import Agave, AgaveException
from celery import shared_task
from requests import HTTPError
from django.conf import settings
from django.contrib.auth import get_user_model
from pytas.models import User as TASUser
from django.db.models import Q
from designsafe.apps.accounts.models import (DesignSafeProfile,
NotificationPreferences)

from requests import HTTPError

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -59,14 +56,14 @@ def create_report(username, list_name):
research_activities = [activity['description'] for activity in activities]

# order of items as required by user
writer.writerow([user_profile.lastName if user_profile.lastName else user_profile.lastName,
user_profile.firstName if user_profile.firstName else user_profile.firstName,
writer.writerow([user_profile.lastName,
user_profile.firstName,
user_profile.email,
user_profile.phone,
user_profile.institution,
user_profile.title,
designsafe_user.profile.professional_level,
designsafe_user.profile.bio if designsafe_user.profile.bio else designsafe_user.profile.bio,
designsafe_user.profile.bio,
nh_interests if nh_interests else None,
research_activities if research_activities else None,
user_profile,
Expand All @@ -79,13 +76,14 @@ def create_report(username, list_name):
else:
writer.writerow(['Unable to find user data for username "' +
user.username + '"', ])
except:
except Exception:
logger.exception("")
continue

User = get_user_model().objects.get(username=username)
client = User.agave_oauth.client

setattr(csv_file, 'name', 'user_report.csv')
csv_file.name = 'user_report.csv'
client.files.importData(
filePath=username,
fileName='user_report.csv',
Expand All @@ -95,7 +93,7 @@ def create_report(username, list_name):

csv_file.close()

except (HTTPError, AgaveException):
except (HTTPError, AgaveException): # noqa
logger.exception('Failed to create user report.',
extra={'user': username,
'systemId': settings.AGAVE_STORAGE_SYSTEM})
15 changes: 8 additions & 7 deletions designsafe/apps/accounts/tests.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.test import TestCase
from django.contrib.auth import get_user_model, signals
from django.contrib.auth.models import Permission
from django.urls import reverse
from unittest import skip
from mock import patch
from unittest.mock import patch

import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse

pytestmark = pytest.mark.django_db

Expand Down Expand Up @@ -64,7 +65,7 @@ def test_mailing_list_subscribe(self):
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertContains(
resp, '"{0}","{1}"'.format(ds_user.get_full_name(), ds_user.email))
resp, f'"{ds_user.get_full_name()}","{ds_user.email}"')

def test_mailing_list_unsubscribe(self):
"""
Expand All @@ -83,7 +84,7 @@ def test_mailing_list_unsubscribe(self):
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertNotContains(
resp, '"{0}","{1}"'.format(ds_user.get_full_name(), ds_user.email))
resp, f'"{ds_user.get_full_name()}","{ds_user.email}"')

@skip("Need to mock celery call")
def test_user_report_access(self):
Expand Down
3 changes: 2 additions & 1 deletion designsafe/apps/accounts/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.urls import include, re_path as url
from django.urls import re_path as url
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from designsafe.apps.accounts import views

urlpatterns = [
Expand Down
Loading
Loading