Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove django-allauth-2fa, dj-rest-auth and django-user-sessions #6293

Draft
wants to merge 161 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
161 commits
Select commit Hold shift + click to select a range
15c6880
Remove django-allauth-2fa
matmair Jan 19, 2024
cb05b20
fix req
matmair Jan 21, 2024
36da273
fix file again
matmair Jan 21, 2024
a8dfef5
remove allauth_2fa flows
matmair Jan 21, 2024
997b664
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 21, 2024
94473f3
reintroduce otp
matmair Jan 21, 2024
068c05a
fix rq
matmair Jan 21, 2024
c31e8fa
remove old ref
matmair Jan 21, 2024
0270082
remove otp things from settings
matmair Jan 21, 2024
a5da45c
Remove django-allauth-2fa
matmair Mar 21, 2024
6037a70
reintroduce otp codes
matmair Mar 21, 2024
1f5091d
remove totp section
matmair Mar 21, 2024
b769048
Merge branch 'inventree:master' into matmair/issue6281
matmair Mar 27, 2024
20dda94
bump version
matmair Mar 27, 2024
f0146cd
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Mar 27, 2024
acb1280
Merge branch 'matmair/issue6281' of https://github.com/matmair/InvenT…
matmair Mar 27, 2024
e0f70d5
fix reqs
matmair Mar 27, 2024
3d30082
add missing model
matmair Mar 27, 2024
9a05015
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Apr 2, 2024
bff387e
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Apr 3, 2024
22cc148
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Apr 8, 2024
e7b7d03
ignore TOTP migration if the model is not laoded
matmair Apr 8, 2024
81c0346
add model deps
matmair Apr 8, 2024
59390ae
add extra migrations step for easier testing
matmair Apr 8, 2024
08bb851
add migration testing
matmair Apr 8, 2024
432dbf7
remove old catch
matmair Apr 8, 2024
5b61956
cover static devies too
matmair Apr 8, 2024
9077741
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Apr 11, 2024
174508e
Merge branch 'inventree:master' into matmair/issue6281
matmair Apr 14, 2024
b2f5507
Merge branch 'inventree:master' into matmair/issue6281
matmair Apr 16, 2024
523bc66
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Apr 22, 2024
2987a9e
Merge branch 'matmair/issue6281' of https://github.com/matmair/InvenT…
matmair Apr 22, 2024
1079897
Remove django-allauth-2fa
matmair Apr 23, 2024
002cd31
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jun 25, 2024
be18379
remove more old stuff
matmair Jun 25, 2024
ea2d527
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jun 25, 2024
f50f476
fix import
matmair Jun 25, 2024
197d4f0
mrege migrations
matmair Jun 25, 2024
d16ca02
bump API version
matmair Jun 25, 2024
8378600
switch to allauth.usersessions
matmair Jun 25, 2024
580057b
add headless
matmair Jun 25, 2024
7fe8062
re-add saml/openid
matmair Jun 25, 2024
8b1f871
user sessions cleanup
matmair Jun 25, 2024
daacfaf
turn off normal allauth urls if CUI is not active
matmair Jun 25, 2024
bb40d13
disable tests that rely on old endpoints - to be replaced
matmair Jun 25, 2024
ed8dec4
always track session changes
matmair Jun 25, 2024
843fdc9
remove old allauth templates
matmair Jun 25, 2024
21c349b
remove old ref
matmair Jun 25, 2024
df1c51b
add missing model
matmair Jun 25, 2024
1367eae
fix session lookup
matmair Jun 25, 2024
42b3f0c
always logout when pwd is changed
matmair Jun 25, 2024
8fad7b1
reimplement session ending
matmair Jun 26, 2024
043bc88
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Dec 22, 2024
e9c20a4
fix merge
matmair Dec 22, 2024
8e95ad8
upgrade reqs
matmair Dec 22, 2024
0072ded
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Dec 22, 2024
d23cc87
lower cryptography version
matmair Dec 22, 2024
b1a549a
clean allauth_2fa reference
matmair Dec 23, 2024
15c19a6
disable test temporarly
matmair Dec 23, 2024
97522d9
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Dec 25, 2024
e9cd910
fix migration check
matmair Dec 25, 2024
7334dc4
disable tests temporarly
matmair Dec 26, 2024
e3c8b89
Re-implement auth flow using new APIs; adds MFA to PUI
matmair Dec 26, 2024
d701182
re-implement logoff
matmair Dec 26, 2024
7bfdc86
stop failure message from appearing when in MFA flow
matmair Dec 26, 2024
2a77e0b
remove jwt mention
matmair Dec 26, 2024
01d416d
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Dec 26, 2024
61e0fae
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Dec 28, 2024
c003084
fix: email endpoints (to be cleaned TODO@matmair)
matmair Dec 28, 2024
8025260
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Dec 28, 2024
4c99f3d
remove unused endpoints
matmair Dec 28, 2024
a584334
ignore the now often-used 410 error
matmair Dec 28, 2024
ef14310
fix auth for email actions in MFA scenarios
matmair Dec 28, 2024
5b49667
add mfa listing use build-in forms
matmair Dec 29, 2024
3f4239f
add dummy entry for missing frontend urls; see TODO@matmair
matmair Dec 29, 2024
f49a687
remove unneeded change of confirm url
matmair Dec 29, 2024
e5f6f3b
add mfa reg endpoint (not fully implemented)
matmair Dec 29, 2024
27e31e5
Merge branch 'master' into matmair/issue6281
matmair Jan 2, 2025
2e6ba4d
implement more provider stuff
matmair Jan 7, 2025
e19c2e1
simplify calls
matmair Jan 7, 2025
18fdfc9
make calls more robust
matmair Jan 7, 2025
ea940e8
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 8, 2025
d482b36
switch to browser based sessions
matmair Jan 8, 2025
2eea51a
add todo's
matmair Jan 8, 2025
7ef84c8
update api version
matmair Jan 8, 2025
a00f090
remove x-session, not needed anymore
matmair Jan 8, 2025
1191d1c
remove old urls
matmair Jan 8, 2025
f84ce83
remove ui preference - there is no decision anymore
matmair Jan 8, 2025
cb8779a
fix login redirect logic
matmair Jan 8, 2025
29694d2
change name to ensure 1p can detect field
matmair Jan 8, 2025
4b6ab95
add mfa table
matmair Jan 8, 2025
da918b7
fix remove sso provider account action; provider (user) admin stuff i…
matmair Jan 8, 2025
6624dbf
reduce templates to the raw basics
matmair Jan 8, 2025
f0dc4a0
fix tests
matmair Jan 8, 2025
b5223de
more exclusions
matmair Jan 8, 2025
6fad126
rewrite url structure
matmair Jan 8, 2025
af4f0a4
move buildin token test
matmair Jan 8, 2025
31e25eb
re-enable registration tests
matmair Jan 8, 2025
8ad07c4
re-implement registrations
matmair Jan 8, 2025
1a876a7
enable registration for now
matmair Jan 8, 2025
d619cc1
re-implement password change
matmair Jan 9, 2025
6f6829d
adjust tests
matmair Jan 9, 2025
ec6ee2c
fix asserts
matmair Jan 9, 2025
5661b93
align names with allauth
matmair Jan 10, 2025
bf82c4c
simplify
matmair Jan 10, 2025
fc09af5
refactor and rephrasing
matmair Jan 10, 2025
56137d2
fix nesting issue
matmair Jan 10, 2025
72f89ea
clean up urls even more
matmair Jan 10, 2025
cedf302
Merge branch 'master' into matmair/issue6281
matmair Jan 10, 2025
6fe06b5
add mfa add and remove screens
matmair Jan 12, 2025
77bcaeb
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 12, 2025
3c181bb
Merge branch 'matmair/issue6281' of https://github.com/matmair/InvenT…
matmair Jan 12, 2025
d6ef1d9
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 12, 2025
95d3a95
add type
matmair Jan 12, 2025
08c458f
revert dep change
matmair Jan 12, 2025
b6c4b99
fix api version
matmair Jan 12, 2025
cf6eb26
re-add settings
matmair Jan 12, 2025
d94a521
simplify urls
matmair Jan 12, 2025
7b23b73
Add timeout to login wait for
matmair Jan 12, 2025
4fa0660
fix url assertation
matmair Jan 13, 2025
5a07f48
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 13, 2025
d2c9519
remove unneded mfa_enabled
matmair Jan 13, 2025
4b412f5
add setting for configuring types
matmair Jan 13, 2025
d413d11
bump api version
matmair Jan 13, 2025
0802e3a
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 14, 2025
2e8b1e7
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 19, 2025
47ece10
fix password reset flow
matmair Jan 19, 2025
67d89b5
change settings order
matmair Jan 19, 2025
0249114
save auth context
matmair Jan 20, 2025
510361f
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 20, 2025
6bad3ff
rename var to remove confusion
matmair Jan 20, 2025
0c40cb4
make login/register seperate paths
matmair Jan 20, 2025
ec8267f
make info text better
matmair Jan 20, 2025
001ddf2
adjust urls
matmair Jan 20, 2025
0c86f27
add error message
matmair Jan 20, 2025
8be0a52
disable buttons if no email is set
matmair Jan 20, 2025
aaa0219
add custom adapters for MFA and headless authentication to use upstre…
matmair Jan 20, 2025
5746364
move auth settings to status
matmair Jan 20, 2025
254ab4e
respect more settings
matmair Jan 20, 2025
e9a47b2
update settings
matmair Jan 20, 2025
7c4d0e8
bump api version
matmair Jan 20, 2025
eadf7ac
remove depreceated docs part
matmair Jan 21, 2025
dd32ca3
remove dj_rest_auth stuff
matmair Jan 21, 2025
dd68ed0
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 21, 2025
e093fea
Merge branch 'master' into matmair/issue6281
matmair Jan 22, 2025
2110deb
fix api_version bump
matmair Jan 22, 2025
dad2836
remove temp fix
matmair Jan 26, 2025
d91363e
fix provider login
matmair Jan 26, 2025
4fb0108
remove unsupported option
matmair Jan 26, 2025
00bb6c5
remove hash requirement for now
matmair Jan 26, 2025
9bfc0d2
simplify customisation
matmair Jan 26, 2025
79f173f
implement email-verification
matmair Jan 26, 2025
fd10612
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 26, 2025
87b083d
remove auth from api docs
matmair Jan 26, 2025
a98faf3
fix override of get_frontend_url
matmair Jan 26, 2025
c6209d7
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 27, 2025
dc07a8a
bump api again
matmair Jan 28, 2025
6d0132e
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Jan 28, 2025
bfe43b8
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Feb 3, 2025
3da0d02
fix req
matmair Feb 3, 2025
d6417a8
Merge branch 'master' of https://github.com/inventree/InvenTree into …
matmair Feb 4, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ repos:
files: src/backend/requirements-dev\.(in|txt)$
- id: pip-compile
name: pip-compile requirements.txt
args: [src/backend/requirements.in, -o, src/backend/requirements.txt, --no-strip-extras, --generate-hashes]
args: [src/backend/requirements.in, -o, src/backend/requirements.txt, --no-strip-extras]
files: src/backend/requirements\.(in|txt)$
- id: pip-compile
name: pip-compile requirements.txt
Expand Down
1 change: 0 additions & 1 deletion docs/docs/api/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ API schema documentation is split into the following categories:

| Category | Description |
| --- | --- |
| [Authorization and Authentication](./schema/auth.md) | Authorization and Authentication |
| [Background Task Management](./schema/background-task.md) | Background Task Management |
| [Barcode Scanning](./schema/barcode.md) | Barcode Scanning |
| [Bill of Materials](./schema/bom.md) | Bill of Materials |
Expand Down
7 changes: 0 additions & 7 deletions docs/docs/api/schema/auth.md

This file was deleted.

1 change: 1 addition & 0 deletions docs/docs/start/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ InvenTree provides allowance for additional sign-in options. The following optio
| Environment Variable | Configuration File | Description | Default |
| --- | --- | --- | --- |
| INVENTREE_MFA_ENABLED | mfa_enabled | Enable or disable multi-factor authentication support for the InvenTree server | True |
| MFA_SUPPORTED_TYPES | mfa_supported_types | List of supported multi-factor authentication types | recovery_codes,totp |

### Single Sign On

Expand Down
1 change: 0 additions & 1 deletion docs/extract_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

# List of special paths we want to split out
SPECIAL_PATHS = {
'auth': 'Authorization and Authentication',
'background-task': 'Background Task Management',
'barcode': 'Barcode Scanning',
'bom': 'Bill of Materials',
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ line-ending = "auto"
[tool.uv.pip]
python-version = "3.9"
no-strip-extras=true
generate-hashes=true

[tool.coverage.run]
source = ["src/backend/InvenTree", "InvenTree"]
Expand Down
18 changes: 18 additions & 0 deletions src/backend/InvenTree/InvenTree/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@

import InvenTree.version
import users.models
from common.settings import get_global_setting
from InvenTree import helpers
from InvenTree.auth_overrides import registration_enabled
from InvenTree.mixins import ListCreateAPI
from InvenTree.sso import sso_registration_enabled
from part.models import Part
from plugin.serializers import MetadataSerializer
from users.models import ApiToken
Expand Down Expand Up @@ -199,6 +202,13 @@ def list(self, request, *args, **kwargs):
class InfoApiSerializer(serializers.Serializer):
"""InvenTree server information - some information might be blanked if called without elevated credentials."""

class SettingsSerializer(serializers.Serializer):
"""Serializer for InfoApiSerializer."""

sso_registration = serializers.BooleanField()
registration_enabled = serializers.BooleanField()
password_forgotten_enabled = serializers.BooleanField()

class CustomizeSerializer(serializers.Serializer):
"""Serializer for customize field."""

Expand Down Expand Up @@ -230,6 +240,7 @@ class CustomizeSerializer(serializers.Serializer):
installer = serializers.CharField(read_only=True)
target = serializers.CharField(read_only=True)
django_admin = serializers.CharField(read_only=True)
settings = SettingsSerializer(read_only=True, many=False)


class InfoView(APIView):
Expand Down Expand Up @@ -288,6 +299,13 @@ def get(self, request, *args, **kwargs):
'django_admin': settings.INVENTREE_ADMIN_URL
if (is_staff and settings.INVENTREE_ADMIN_ENABLED)
else None,
'settings': {
'sso_registration': sso_registration_enabled(),
'registration_enabled': registration_enabled(),
'password_forgotten_enabled': get_global_setting(
'LOGIN_ENABLE_PWD_FORGOT'
),
},
}

return JsonResponse(data)
Expand Down
5 changes: 4 additions & 1 deletion src/backend/InvenTree/InvenTree/api_version.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
"""InvenTree API version information."""

# InvenTree API version
INVENTREE_API_VERSION = 309
INVENTREE_API_VERSION = 310

"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""


INVENTREE_API_TEXT = """
v310 - 2025-01-29 : https://github.com/inventree/InvenTree/pull/6293
- Removes a considerable amount of old auth endpoints
- Introduces allauth based REST API

v309 - 2025-02-02 : https://github.com/inventree/InvenTree/pull/9008
- Bug fixes for the "Part" serializer
Expand Down
40 changes: 0 additions & 40 deletions src/backend/InvenTree/InvenTree/auth_override_views.py

This file was deleted.

115 changes: 42 additions & 73 deletions src/backend/InvenTree/InvenTree/auth_overrides.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
"""Overrides for allauth and adjacent packages to enforce InvenTree specific auth settings and restirctions."""

from urllib.parse import urlencode

from django import forms
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

import structlog
from allauth.account.adapter import DefaultAccountAdapter
from allauth.account.forms import LoginForm, SignupForm, set_form_field_order
from allauth.core.exceptions import ImmediateHttpResponse
from allauth.headless.adapter import DefaultHeadlessAdapter
from allauth.headless.tokens.sessions import SessionTokenStrategy
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth_2fa.adapter import OTPAdapter
from allauth_2fa.forms import TOTPDeviceForm
from allauth_2fa.utils import user_has_valid_totp_device
from dj_rest_auth.registration.serializers import (
RegisterSerializer as DjRestRegisterSerializer,
)
from rest_framework import serializers

import InvenTree.helpers_model
import InvenTree.sso
from common.settings import get_global_setting
from InvenTree.exceptions import log_error
from users.models import ApiToken

logger = structlog.get_logger('inventree')

Expand Down Expand Up @@ -92,16 +86,6 @@ def clean(self):
return cleaned_data


class CustomTOTPDeviceForm(TOTPDeviceForm):
"""Ensure that db registration is enabled."""

def __init__(self, user, metadata=None, **kwargs):
"""Override to check if registration is open."""
if not settings.MFA_ENABLED:
raise forms.ValidationError(_('MFA Registration is disabled.'))
super().__init__(user, metadata, **kwargs)


def registration_enabled():
"""Determine whether user registration is enabled."""
if (
Expand Down Expand Up @@ -177,19 +161,7 @@ def save_user(self, request, user, form, commit=True):
return user


class CustomUrlMixin:
"""Mixin to set urls."""

def get_email_confirmation_url(self, request, emailconfirmation):
"""Custom email confirmation (activation) url."""
url = reverse('account_confirm_email', args=[emailconfirmation.key])

return InvenTree.helpers_model.construct_absolute_url(url)


class CustomAccountAdapter(
CustomUrlMixin, RegistrationMixin, OTPAdapter, DefaultAccountAdapter
):
class CustomAccountAdapter(RegistrationMixin, DefaultAccountAdapter):
"""Override of adapter to use dynamic settings."""

def send_mail(self, template_prefix, email, context):
Expand All @@ -207,16 +179,14 @@ def send_mail(self, template_prefix, email, context):

return False

def get_email_confirmation_url(self, request, emailconfirmation):
"""Construct the email confirmation url."""
url = super().get_email_confirmation_url(request, emailconfirmation)
url = InvenTree.helpers_model.construct_absolute_url(url)
return url
def send_password_reset_mail(self, user, email, context):
"""Send the password reset mail."""
if not get_global_setting('LOGIN_ENABLE_PWD_FORGOT'):
raise PermissionDenied('Password reset is disabled')
return super().send_password_reset_mail(self, user, email, context)


class CustomSocialAccountAdapter(
CustomUrlMixin, RegistrationMixin, DefaultSocialAccountAdapter
):
class CustomSocialAccountAdapter(RegistrationMixin, DefaultSocialAccountAdapter):
"""Override of adapter to use dynamic settings."""

def is_auto_signup_allowed(self, request, sociallogin):
Expand All @@ -225,29 +195,6 @@ def is_auto_signup_allowed(self, request, sociallogin):
return super().is_auto_signup_allowed(request, sociallogin)
return False

# from OTPAdapter
def has_2fa_enabled(self, user):
"""Returns True if the user has 2FA configured."""
return user_has_valid_totp_device(user)

def login(self, request, user):
"""Ensure user is send to 2FA before login if enabled."""
# Require two-factor authentication if it has been configured.
if self.has_2fa_enabled(user):
# Cast to string for the case when this is not a JSON serializable
# object, e.g. a UUID.
request.session['allauth_2fa_user_id'] = str(user.id)

redirect_url = reverse('two-factor-authenticate')
# Add GET parameters to the URL if they exist.
if request.GET:
redirect_url += '?' + urlencode(request.GET)

raise ImmediateHttpResponse(response=HttpResponseRedirect(redirect_url))

# Otherwise defer to the original allauth adapter.
return super().login(request, user)

def authentication_error(
self, request, provider_id, error=None, exception=None, extra_context=None
):
Expand All @@ -264,15 +211,37 @@ def authentication_error(
log_error(path, error_name=error, error_data=exception)
logger.error("SSO error for provider '%s' - check admin error log", provider_id)

def get_connect_redirect_url(self, request, socialaccount):
"""Redirect to the frontend after connecting an account."""
return request.build_absolute_uri(f'/{settings.FRONTEND_URL_BASE}/')

# override dj-rest-auth
class RegisterSerializer(DjRestRegisterSerializer):
"""Registration requires email, password (twice) and username."""

email = serializers.EmailField()
class CustomHeadlessAdapter(DefaultHeadlessAdapter):
"""Override of adapter to use dynamic settings."""

def save(self, request):
"""Override to check if registration is open."""
if registration_enabled():
return super().save(request)
raise forms.ValidationError(_('Registration is disabled.'))
def get_frontend_url(self, urlname, **kwargs):
"""Get the frontend URL for the given URL name respecting the request."""
HEADLESS_FRONTEND_URLS = {
'account_confirm_email': 'verify-email/{key}',
'account_reset_password': 'reset-password',
'account_reset_password_from_key': 'set-password?key={key}',
'account_signup': 'register',
'socialaccount_login_error': 'social-login-error',
}
if urlname not in HEADLESS_FRONTEND_URLS:
raise ValueError(
f'URL name "{urlname}" not found in HEADLESS_FRONTEND_URLS'
)

return self.request.build_absolute_uri(
f'/{settings.FRONTEND_URL_BASE}/{HEADLESS_FRONTEND_URLS[urlname].format(**kwargs)}'
)


class DRFTokenStrategy(SessionTokenStrategy):
"""Strategy that InvenTrees own included Token model."""

def create_access_token(self, request):
"""Create a new access token for the user."""
token, _ = ApiToken.objects.get_or_create(user=request.user)
return token.key
33 changes: 1 addition & 32 deletions src/backend/InvenTree/InvenTree/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,13 @@
from django.contrib.auth.middleware import PersistentRemoteUserMiddleware
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import Resolver404, include, path, resolve, reverse_lazy
from django.urls import resolve, reverse_lazy
from django.utils.deprecation import MiddlewareMixin

import structlog
from allauth_2fa.middleware import AllauthTwoFactorMiddleware, BaseRequire2FAMiddleware
from error_report.middleware import ExceptionProcessor

from common.settings import get_global_setting
from InvenTree.cache import create_session_cache, delete_session_cache
from InvenTree.urls import frontendpatterns
from users.models import ApiToken

logger = structlog.get_logger('inventree')
Expand Down Expand Up @@ -137,34 +134,6 @@ def __call__(self, request):
return response


url_matcher = path('', include(frontendpatterns))


class Check2FAMiddleware(BaseRequire2FAMiddleware):
"""Check if user is required to have MFA enabled."""

def require_2fa(self, request):
"""Use setting to check if MFA should be enforced for frontend page."""
try:
if url_matcher.resolve(request.path[1:]):
return get_global_setting('LOGIN_ENFORCE_MFA')
except Resolver404:
pass
return False


class CustomAllauthTwoFactorMiddleware(AllauthTwoFactorMiddleware):
"""This function ensures only frontend code triggers the MFA auth cycle."""

def process_request(self, request):
"""Check if requested url is frontend and enforce MFA check."""
try:
if not url_matcher.resolve(request.path[1:]):
super().process_request(request)
except Resolver404:
pass


class InvenTreeRemoteUserMiddleware(PersistentRemoteUserMiddleware):
"""Middleware to check if HTTP-header based auth is enabled and to set it up."""

Expand Down
Loading
Loading