Skip to content

Commit

Permalink
EDLY-2438 Upgrade to junipper (#7)
Browse files Browse the repository at this point in the history
* Update translations

* Update translations

* Update edx-credentials-themes to the bootstrap version

* Update to DOT instead of DOP for OAuth2 Authentication

* After this commit, credentials no longer depends on OpenID Connect.
* Split OAuth2 credentials into two different sets:
  1. "SSO" for user auth (authorization grant).
  2. "backend-service" for server-to-server auth (client credentials grant).
* Bump auth-backends to 1.2.2 for DOT support.
* Deprecate credentials.apps.api.authentication.BearerAuthentication

For hackathon J-N-T (Julia-Nimisha-Troy).

* Remove usages of OAUTH2_PROVIDER_URL, add BACKEND_SERVICE_EDX_OAUTH2_PROVIDER_URL

Replace with either of these alternatives, depending on how its used:

* BACKEND_SERVICE_EDX_OAUTH2_PROVIDER_URL
* SOCIAL_AUTH_EDX_OAUTH2_URL_ROOT

* Updated Credentials-theme package version

Updated credentials-themes version in base.txt

* LEARNER-7043: Encode filename to download record

* Remove PUBLIC_URL default from base - should only be set in devstack.

* Update translations

* fix(i18n): update translations

* Add username replacement API

New API replaces all copies of username in this service with a new
username. Requires user be in a username_replacement_admin group. Should
only be ran as a larger job to update usernames across all services,
otherwise the system will be left in a broken state for those users.

* fix(i18n): update translations

* send emails for program if records_enabled is true

send_updated_emails_for_program() should be called only if the site
configurations has the value for records_enabled set to true.

PROD-189

* Revert "send emails for program if records_enabled is true"

This reverts commit 3d26cc0.

* Use the site configuration associated with the ProgramCredentials instead

* Delete AUTHORS

* fix(i18n): update translations

* fix(i18n): update translations

* Disable share and send record button on onClick

Due to a known issue in get_or_create() method which is prone to a
race-condition which can result in multiple rows with the same
parameters being inserted simultaneously, added a unique_together
constraint and disabled button after onClick event to avoid concurrent
requests.

PROD-197

* Update openedx.yaml

* Add masters-neem as a supporting team

* Add a tag.

* Upgrade DRF to 3.9.4

* unpin django

* Move credentials defaults from configration repo (openedx#656)

* Pin django to 1.11.22

* fix(i18n): update translations

* fix(i18n): update translations

* Updating credentials-themes to 0.1.29 (openedx#661)

* fix(i18n): update translations

* Fix program certificate print view.

Program certificate print preview is loading in vertical instead
of horizontal like course certificate.

PROD-492

* Upgrade Django to 1.11.23

Fixes four security vulnerabilities.

EDUCATOR-4551

* Fix program record url in credit request email.

Building the program record URL incorrectly by concatenating site domain
and record path. Fixed by using request.build_absolute_uri().

PROD-564

* Add make update to credentials (openedx#668)

* add make upgrade for oep-18 compliance, unpin dependencies in .in files

* Update openedx.yaml for Masters squad reorg

* Updating Python Requirements (openedx#671)

* Field names updated for the search field attributes.

* Changed from_address while sending email to partner

previously we were using [email protected] in from address.
Now we will be using learner eamil address so that partner can
contact with learner.

Prod-624

* fix(i18n): update translations

* Enabled admin search for uuid

Prod-706

* Updating Python Requirements

* fix(i18n): update translations

* Invalid UUID error in credentials api

Learner-5999

Problem:
Giving invalid uuid in credentials api raises a validation exception.

Solution:
Added an except clause to return empty list in case of invalid uuid instead of raising an exception.
Test checks if invalid uuid returns an empty list instead of raising validation error or not.

* Updating Python Requirements

* Revert "Changed from_address while sending email to partner"

This reverts commit 19e4252.

* Add the admin section for the Catalog Cache

* Updating Python Requirements

* Add better admin table data for search and viewing

* Restriction on the version of MySql that we use for testing (openedx#689)

[PROD-830]

This is being added to deal with a failure in tests running with the
current version.

* learner email added in reply_field

PROD-624

* Updating Python Requirements

* Rename start and end fields (1/4)

This is the first stage of renaming the start and end fields of
CourseRun to start_date and end_date.  This release ONLY adds the new
column, no code changes.

DE-1708

* Rename start and end fields (2/4)

This is the second stage of renaming the start and end fields of
CourseRun to start_date and end_date.  This release updates the code to
make writes additionally go into the new column (preserving writes to
the old column, still).

DE-1708

* Rename start and end fields (2.5/4)

This is the second-and-a-halfth stage of renaming the start and end
fields of CourseRun to start_date and end_date.  This release includes a
data migration which copies all values from old into new field.

DE-1708

* Rename start and end fields (3/4) (openedx#695)

This is the third stage of renaming the start and end fields of
CourseRun to start_date and end_date.  This release updates the code to
make writes ONLY go into the new column, and removes references to the
old column.

DE-1708

* Rename start and end fields (4/4) (openedx#696)

This is the fourth stage of renaming the start and end fields of
CourseRun to start_date and end_date.  This release ONLY removes the old
columns which, by now, should not be referenced in any code.

DE-1708

* Revert "Rename start and end fields (4/4) (openedx#696)"

This reverts commit da001b1.

* Rename start and end fields (4.1/4)

This is the 4.1th stage of renaming the start and end fields of
CourseRun to start_date and end_date.

This release ONLY removes the django model fields corresponding to the
old columns.  Note that this does not include the migration to remove
the columns.

DE-1708

* upgrade edx-drf-extensions to 2.4.5

- Upgrade edx-drf-extensions to 2.4.5
- Remove unused JWT_AUTH_REFRESH_COOKIE setting.

ARCH-418, ARCH-1269, ARCH-1044

* Rename start and end fields (4.2/4)

This is the 4.2th stage of renaming the start and end fields of
CourseRun to start_date and end_date.

This release ONLY removes the old columns via migration.  Note that this
does not include removing the django model fields corresponding to the
old columns.

DE-1708

* fix(i18n): update translations

* Added devstack config yml file to app repo (openedx#700)

* Added devstack config yml file to app repo

* Added config yml file to app repo

* Updating Python Requirements

* fix(i18n): update translations

* fix(i18n): update translations

* Updating Python Requirements

* test path problem

* fix(i18n): update translations

* fix(i18n): update translations

* make upgrade

Removing these constraints appears to get us moving forward again
without conflicts, which nominally was the only reason they were
constrained.

* Grades on learner record are not consistent with progress page.

Credentials service is not rounding the user grade in a particular
course while displaying it on the learner record.This makes an
inconsistent behaviour compared to support tool as well as progress
page.To fix it, learner grade are rounded properly so that a
consistent grade would appear on all views.

PROD-1051

* Updating Python Requirements

* Address an issue that was preventing make upgrade

It seems like there was a pip/piptools version incompatibility which
was preventing make upgrade from even getting started

* Updating Python Requirements

* fix(i18n): update translations

* Django 2.2 Upgrade via codemods (openedx#723)

* Move devstack credentials.yml t configuration repo (openedx#724)

* Move default variables from config repo (openedx#725)

* Updating Python Requirements

* fix(i18n): update translations

* Remove oidc settings.

* Update credentials themes to include MB certs

Upgrading requirements to bump credentials theme to install the new
MicroBachelors programs cert templates.

* replacing django-ratelimit to the version that supports django22 (openedx#732)

* BOM-1260
-Upgrade social-auth-app-django to support django22

* upgrade edx-lint and fixed quality (openedx#733)

* removed the constraint for edx-ace (openedx#735)

* BOM-1257 (openedx#731)

Remove the django-filter constraint.

* BOM-1281 (openedx#739)

Fixing the tox.

* BOM-1283 (openedx#740)

Fixing m2m warnings.

* Removing use of BearerAuthentication (openedx#741)

BearerAuthentication is deprecated and is not currently used by system.

* BOM-1281 : Implement Tox in credentials (openedx#742)

* use tox for running tests

* changes in tox.ini

* revert package-lock

* correct indentation

* reset some changes

* test

* removing jasmine from tox

* all requirements

* Removed js from tox.ini

* removed setup.py

Co-authored-by: Ayub <[email protected]>

* Bump codecov from 2.3.1 to 3.6.5

Bumps [codecov](https://github.com/codecov/codecov-node) from 2.3.1 to 3.6.5.
- [Release notes](https://github.com/codecov/codecov-node/releases)
- [Commits](https://github.com/codecov/codecov-node/commits)

Signed-off-by: dependabot[bot] <[email protected]>

* fix(i18n): update translations

* added django 2.x workers to travis (openedx#748)

* BOM-1346 (openedx#746)

Fixing permissions and tests issues.

* Updating Python Requirements (openedx#752)

* BOM-1045
- edx-drf-extensions
- fixed tests
- preserves admin group behavior while using edx-drf-extensions instead.

* Pin edx-ace because it causes test issues.

* Allow edx-ace to be upgraded by unpinning attrs (openedx#756)

* BOM-1407 (openedx#757)

upgrade django2.2

* Updating Python Requirements (openedx#758)

* run keyword linter in CI (openedx#759)

* run linter on all systems (openedx#760)

* fix(i18n): update translations

* Downgrade social-auth-core to work around permission loss

JIRA:ARCHBOM-1078

* fix(i18n): update translations

* Removed Django version < 2.2

* Updating Python Requirements

* Replace deprecated static loading (openedx#766)

* Bump eslint from 3.19.0 to 4.18.2 (openedx#750)

Bumps [eslint](https://github.com/eslint/eslint) from 3.19.0 to 4.18.2.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/master/CHANGELOG.md)
- [Commits](eslint/eslint@v3.19.0...v4.18.2)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump axios from 0.18.0 to 0.18.1 (openedx#749)

Bumps [axios](https://github.com/axios/axios) from 0.18.0 to 0.18.1.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v0.18.1/CHANGELOG.md)
- [Commits](axios/axios@v0.18.0...v0.18.1)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Address EDUCATOR-4716: Backend (openedx#769)

* Updating Python Requirements

* Import private.py in devstack.py

* Added Python 3.8 for testing (openedx#772)

* Added data migration

PROD-1443

* Updating Python Requirements

* Switch from pyinotify to pywatchman for filemonitoring.

pyinotify was causing performance issues with django 2.2 in development environments.

* fix(i18n): update translations

* Updating Python Requirements (openedx#778)

* Updating Python Requirements (openedx#779)

Added Nose for missing testing dependency

* Updating Python Requirements (openedx#780)

* Updating Python Requirements

* Upgrade Django to 2.2.13

* Resolved conflicts and fixed deprecations EDLY-2438

* Removed unnessary migrations EDLY-2438

* Added migrations with proper naming EDLY-2438

Co-authored-by: edX Transifex Bot <[email protected]>
Co-authored-by: Michael Terry <[email protected]>
Co-authored-by: Nimisha Asthagiri <[email protected]>
Co-authored-by: Troy Sankey <[email protected]>
Co-authored-by: Usama <[email protected]>
Co-authored-by: Zainab Amir <[email protected]>
Co-authored-by: Julia Eskew <[email protected]>
Co-authored-by: Matt Tuchfarber <[email protected]>
Co-authored-by: Zainab Amir <[email protected]>
Co-authored-by: Simon Chen <[email protected]>
Co-authored-by: Brandon Baker <[email protected]>
Co-authored-by: Kyle McCormick <[email protected]>
Co-authored-by: Feanil Patel <[email protected]>
Co-authored-by: Alex Dusenbery <[email protected]>
Co-authored-by: jansenk <[email protected]>
Co-authored-by: syedimranhassan <[email protected]>
Co-authored-by: Albert (AJ) St. Aubin <[email protected]>
Co-authored-by: Waheed Ahmed <[email protected]>
Co-authored-by: edX requirements bot <[email protected]>
Co-authored-by: usama sadiq <[email protected]>
Co-authored-by: adeelehsan <[email protected]>
Co-authored-by: edX requirements bot <[email protected]>
Co-authored-by: Troy Sankey <[email protected]>
Co-authored-by: Robert Raposa <[email protected]>
Co-authored-by: Matt Hughes <[email protected]>
Co-authored-by: uzairr <[email protected]>
Co-authored-by: M Zulqarnain <[email protected]>
Co-authored-by: Diana Huang <[email protected]>
Co-authored-by: Aarif <[email protected]>
Co-authored-by: Ayub-khan <[email protected]>
Co-authored-by: Muhammad Soban Javed <[email protected]>
Co-authored-by: Awais Qureshi <[email protected]>
Co-authored-by: Manjinder Singh <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Stu Young <[email protected]>
Co-authored-by: usamasadiq <[email protected]>
Co-authored-by: Hassan Tariq <[email protected]>
Co-authored-by: Ned Batchelder <[email protected]>
  • Loading branch information
1 parent 376699b commit edfb3e2
Show file tree
Hide file tree
Showing 276 changed files with 4,027 additions and 1,540 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ coverage.xml
diff_*.html
*.report
report
reports
venv
# auth.py holds an autogenerated token
acceptance_tests/auth.py
Expand Down
52 changes: 36 additions & 16 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
language: python

python:
- "3.5"

branches:
only:
- master
Expand All @@ -25,37 +22,60 @@ before_install:

matrix:
include:
- env: TESTNAME=quality-and-translations

# Doing so is a waste of time since they won't be used.
- python: 3.5
env: TESTNAME=quality-and-translations
install: true

script:
- make exec-requirements
- make exec-check_translations_up_to_date
- make exec-validate-translations
- make exec-quality
- make exec-check_keywords
- python: 3.8
env: TESTNAME=quality-and-translations
install: true
script:
- make exec-requirements
- make exec-check_translations_up_to_date
- make exec-validate-translations
- make exec-quality
- make exec-check_keywords

- env: TESTNAME=acceptance-tests
- python: 3.5
env: TESTNAME=acceptance-tests
install:
- make exec-requirements
script:
- make exec-static
- make exec-accept
addons:
firefox: latest
- python: 3.8
env: TESTNAME=acceptance-tests
install:
- make exec-requirements
script:
- make exec-static
- make exec-accept
addons:
firefox: latest

- env: TESTNAME=unit-tests

# Doing so is a waste of time since they won't be used.
- python: 3.5
env: TOXENV=django22
install: true
script:
- make exec-requirements
- make exec-static
- make exec-tests
- python: 3.8
env: TOXENV=django22
install: true

script:
- make exec-requirements
- make exec-static
- make exec-tests

after_success:
- pip install --upgrade codecov
- make exec-coverage
- codecov
after_success:
- pip install --upgrade codecov
- make exec-coverage
- codecov
17 changes: 0 additions & 17 deletions AUTHORS

This file was deleted.

72 changes: 56 additions & 16 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
.DEFAULT_GOAL := tests
NODE_BIN=./node_modules/.bin
TOX = ''

.PHONY: requirements
.PHONY: requirements upgrade piptools production-requirements all-requirements

ifdef TOXENV
TOX := tox -- #to isolate each tox environment if TOXENV is defined
endif

# Generates a help message. Borrowed from https://github.com/pydanny/cookiecutter-djangopackage.
help: ## Display this help message
Expand All @@ -12,16 +17,24 @@ clean: ## Remove all generated files
coverage erase
find . -path '*/__pycache__/*' -delete
find . -name \*.pyc -o -name \*.pyo -o -name __pycache__ -delete
rm -rf credentials/assets/ credentials/static/bundles/ credentials/static/jsi18n/ coverage htmlcov test_root/uploads
rm -rf credentials/assets/ credentials/static/bundles/ credentials/static/jsi18n/ coverage htmlcov test_root/uploads reports
git clean -fd credentials/conf/locale

production-requirements: ## Install requirements for production
production-requirements: piptools ## Install requirements for production
npm install --production --no-save
pip install -r requirements.txt
pip-sync requirements.txt

js-requirements: ## Install frontend requirements
npm install

requirements: ## Install requirements for local development
all-requirements: piptools ## Install local and prod requirements
npm install --unsafe-perm ## This flag exists to force node-sass to build correctly on docker. Remove as soon as possible.
pip install -r requirements/local.txt
npm install --production --no-save
pip-sync requirements/all.txt

requirements: piptools ## Install requirements for local development
npm install --unsafe-perm ## This flag exists to force node-sass to build correctly on docker. Remove as soon as possible.
pip-sync requirements/dev.txt

quality: ## Run linters
isort --check-only --recursive acceptance_tests/ credentials/
Expand All @@ -36,20 +49,24 @@ test-react: ## Run Jest tests for React
npm run test-react

tests: ## Run tests and generate coverage report
coverage run -m pytest --ds credentials.settings.test --durations=25
coverage report
$(TOX)coverage run -m pytest --ds credentials.settings.test --durations=25
$(TOX)coverage report
$(NODE_BIN)/gulp test
make test-react

js-tests: ## Run tests and generate coverage report
$(NODE_BIN)/gulp test
make test-react

static: ## Gather all static assets for production (minimized)
$(NODE_BIN)/webpack --config webpack.config.js --display-error-details --progress --optimize-minimize
python manage.py compilejsi18n
python manage.py collectstatic --noinput -i *.scss
$(TOX)python manage.py compilejsi18n
$(TOX)python manage.py collectstatic --noinput -i *.scss

static.dev: ## Gather all static assets for development (not minimized)
$(NODE_BIN)/webpack --config webpack.config.js --display-error-details --progress
python manage.py compilejsi18n
python manage.py collectstatic --noinput -i *.scss
$(TOX)python manage.py compilejsi18n
$(TOX)python manage.py collectstatic --noinput -i *.scss

static.watch: ## Gather static assets when they change (not minimized)
$(NODE_BIN)/webpack --config webpack.config.js --display-error-details --progress --watch
Expand All @@ -73,25 +90,28 @@ exec-validate-translations: ## Check translations on a container
exec-check_translations_up_to_date: ## test translations on a container
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make check_translations_up_to_date'

exec-check_keywords: ## Scan the Django models in all installed apps in this project for restricted field names
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make check_keywords'

exec-clean: ## Remove all generated files from a container
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make clean'

exec-requirements:
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make requirements && make production-requirements'
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make all-requirements'

exec-static: ## Gather static assets on a container
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make static'
docker exec -e TOXENV=$(TOXENV) -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make static'

exec-quality: ## Run linters on a container
docker exec -t credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make quality'

exec-tests: ## Run tests on a container
docker exec -it credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && xvfb-run make tests'
docker exec -e TOXENV=$(TOXENV) -it credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && xvfb-run make tests'

exec-accept: ## Run acceptance tests on a container
docker exec -it credentials bash -c 'source /edx/app/credentials/credentials_env && cd /edx/app/credentials/credentials/ && make accept'

exec-validate: exec-validate-translations exec-clean exec-static exec-quality exec-tests exec-accept ## Run linters and tests after checking translations and gathering static assets
exec-validate: exec-validate-translations exec-clean exec-static exec-quality exec-tests exec-accept exec-check_keywords ## Run linters and tests after checking translations and gathering static assets

exec-coverage: ## Generate XML coverage report on a container
docker exec -t credentials bash -c 'coverage xml'
Expand Down Expand Up @@ -135,3 +155,23 @@ validate_translations: ## Test translations files
cd credentials && i18n_tool validate -v --check-all

check_translations_up_to_date: fake_translations detect_changed_source_translations ## Install fake translations and check if translation files are up-to-date

piptools:
pip install -q -r requirements/pip_tools.txt

export CUSTOM_COMPILE_COMMAND = make upgrade
upgrade: piptools ## update the requirements/*.txt files with the latest packages satisfying requirements/*.in
pip-compile --rebuild --upgrade -o requirements/pip_tools.txt requirements/pip_tools.in
pip-compile --rebuild --upgrade -o requirements/base.txt requirements/base.in
pip-compile --rebuild --upgrade -o requirements/test.txt requirements/test.in
pip-compile --rebuild --upgrade -o requirements/docs.txt requirements/docs.in
pip-compile --rebuild --upgrade -o requirements/dev.txt requirements/dev.in
pip-compile --rebuild --upgrade -o requirements/production.txt requirements/production.in
pip-compile --rebuild --upgrade -o requirements/all.txt requirements/all.in
# Let tox control the Django version for tests
grep -e "^django==" requirements/production.txt > requirements/django.txt
sed '/^[dD]jango==/d' requirements/test.txt > requirements/test.tmp
mv requirements/test.tmp requirements/test.txt

check_keywords: ## Scan the Django models in all installed apps in this project for restricted field names
python manage.py check_reserved_keywords --override_file db_keyword_overrides.yml
17 changes: 17 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ Reporting Security Issues

Please do not report security issues in public. Please email [email protected].

Testing
-------

The command below runs all of the Python and JS tests::

$ make tests

The Python tests can be run independently with::

$ pytest --ds credentials.settings.test

If this is the first time you've run tests, you'll have to run::

$ make static

first, otherwise you'll run into ``webpack_loader.exceptions.WebpackBundleLookupErrors``.

Get Help
--------

Expand Down
2 changes: 1 addition & 1 deletion acceptance_tests/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
auth = None


class LoginMixin(object):
class LoginMixin:
""" Mixin used for log in through a cookie."""

def login(self, superuser=False):
Expand Down
13 changes: 9 additions & 4 deletions credentials/apps/api/accreditors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# pylint: disable=missing-docstring
import logging

from credentials.apps.api import exceptions
Expand All @@ -8,7 +7,7 @@
logger = logging.getLogger(__name__)


class Accreditor(object):
class Accreditor:
""" Accreditor class identifies credential type and calls corresponding issuer
class for generating credential.
"""
Expand All @@ -30,14 +29,20 @@ def _create_credential_type_issuer_map(self):
else:
self.credential_type_issuer_map[credential_type] = issuer

def issue_credential(self, credential, username, status=UserCredentialStatus.AWARDED, attributes=None):
def issue_credential(
self, credential, username,
status=UserCredentialStatus.AWARDED,
attributes=None,
request=None
):
"""Issues a credential.
Arguments:
credential (AbstractCredential): Type of credential to issue.
username (str): Username of the recipient.
status (str): Status of credential.
attributes (List[dict]): attributes list containing dictionaries of attributes
request (HttpRequest): request object to build program record absolute uris
Returns:
UserCredential
Expand All @@ -54,4 +59,4 @@ def issue_credential(self, credential, username, status=UserCredentialStatus.AWA
)
)

return credential_issuer.issue_credential(credential, username, status, attributes)
return credential_issuer.issue_credential(credential, username, status, attributes, request)
38 changes: 7 additions & 31 deletions credentials/apps/api/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@

import logging

from django.conf import settings
import edx_rest_framework_extensions.auth.jwt.authentication as edx_drf_auth

from django.contrib.auth.models import Group
from edx_rest_framework_extensions.auth.bearer.authentication import BearerAuthentication as BaseBearerAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from credentials.apps.core.constants import Role
from credentials.apps.core.models import User

logger = logging.getLogger(__name__)

Expand All @@ -28,7 +25,7 @@ def _set_user_roles(user, payload):
user.groups.remove(admin_group)


def pipeline_set_user_roles(response, user=None, *_, **__):
def pipeline_set_user_roles(response, user=None, *_, **__): # pylint: disable=keyword-arg-before-vararg
"""
Social auth pipeline function to update group memberships based
on claims present in the id token.
Expand All @@ -39,40 +36,19 @@ def pipeline_set_user_roles(response, user=None, *_, **__):
return {}


class JwtAuthentication(JSONWebTokenAuthentication):
class JwtAuthentication(edx_drf_auth.JwtAuthentication):
"""
Custom authentication using JWT from the edx oidc provider.
Overrides the default JwtAuthentication class to ensure that admin users are added to the admin group.
"""

def authenticate_credentials(self, payload):
"""
Return a user object to be associated with the present request, based on
the content of an already-decoded / verified JWT payload.
In the process of inflating the user object based on the payload, we also
make sure that the roles associated with this user are up-to-date.
Return the user object with the admin group added or removed if the user is an admin.
"""
if 'preferred_username' not in payload:
logger.warning('Invalid JWT payload: preferred_username not present.')
raise AuthenticationFailed()
username = payload['preferred_username']
user, __ = User.objects.get_or_create(username=username)
user = super(JwtAuthentication, self).authenticate_credentials(payload)
admin_group = Group.objects.get(name=Role.ADMINS)
if payload.get('administrator'):
user.groups.add(admin_group)
else:
user.groups.remove(admin_group)

return user


class BearerAuthentication(BaseBearerAuthentication):
"""
Simple token based authentication.
This authentication class is useful for authenticating an OAuth2 access token against a remote
authentication provider. Clients should authenticate by passing the token key in the "Authorization" HTTP header,
prepended with the string `"Bearer "`.
"""
def get_user_info_url(self):
""" Returns the URL, hosted by the OAuth2 provider, from which user information can be pulled. """
return '{base}/user_info/'.format(base=settings.OAUTH2_PROVIDER_URL)
2 changes: 0 additions & 2 deletions credentials/apps/api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
class UnsupportedCredentialTypeError(Exception):
""" Raised when the Accreditor is asked to issue a type of credential
for which there is no registered issuer. """
pass


class DuplicateAttributeError(Exception):
""" Raised when the Accreditor is asked to issue credential with duplicate
attributes.
"""
pass
Loading

0 comments on commit edfb3e2

Please sign in to comment.