mirror of
https://github.com/inventree/InvenTree.git
synced 2025-12-17 12:25:04 -06:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec67f10fc8 | ||
|
|
a6693d3bf8 | ||
|
|
421081b8f6 | ||
|
|
a41efb31b6 | ||
|
|
78b559306b | ||
|
|
8708ec9bac | ||
|
|
864236b27a | ||
|
|
5a06e00159 | ||
|
|
cb7b4cbc1a | ||
|
|
74e8f92be5 | ||
|
|
264b560f37 | ||
|
|
9f8ee5a095 | ||
|
|
79fdf9243b | ||
|
|
35266b80f4 | ||
|
|
05d3458f67 |
@@ -19,6 +19,9 @@ class InvenTreeResource(ModelResource):
|
||||
MAX_IMPORT_ROWS = 1000
|
||||
MAX_IMPORT_COLS = 100
|
||||
|
||||
# List of fields which should be converted to empty strings if they are null
|
||||
CONVERT_NULL_FIELDS = []
|
||||
|
||||
def import_data_inner(
|
||||
self,
|
||||
dataset,
|
||||
@@ -79,6 +82,13 @@ class InvenTreeResource(ModelResource):
|
||||
|
||||
return [f for f in fields if f.column_name not in fields_to_exclude]
|
||||
|
||||
def before_import_row(self, row, row_number=None, **kwargs):
|
||||
"""Run custom code before importing each row"""
|
||||
|
||||
for field in self.CONVERT_NULL_FIELDS:
|
||||
if field in row and row[field] is None:
|
||||
row[field] = ''
|
||||
|
||||
|
||||
class CustomRateAdmin(RateAdmin):
|
||||
"""Admin interface for the Rate class"""
|
||||
|
||||
@@ -12,10 +12,9 @@ from django.db import transaction
|
||||
from django.db.utils import IntegrityError, OperationalError
|
||||
|
||||
import InvenTree.conversion
|
||||
import InvenTree.ready
|
||||
import InvenTree.tasks
|
||||
from InvenTree.config import get_setting
|
||||
from InvenTree.ready import (canAppAccessDatabase, isInMainThread,
|
||||
isInTestMode, isPluginRegistryLoaded)
|
||||
|
||||
logger = logging.getLogger("inventree")
|
||||
|
||||
@@ -37,17 +36,21 @@ class InvenTreeConfig(AppConfig):
|
||||
- Adding users set in the current environment
|
||||
"""
|
||||
# skip loading if plugin registry is not loaded or we run in a background thread
|
||||
if not isPluginRegistryLoaded() or not isInMainThread():
|
||||
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
|
||||
return
|
||||
|
||||
if canAppAccessDatabase() or settings.TESTING_ENV:
|
||||
# Skip if running migrations
|
||||
if InvenTree.ready.isRunningMigrations():
|
||||
return
|
||||
|
||||
if InvenTree.ready.canAppAccessDatabase() or settings.TESTING_ENV:
|
||||
|
||||
self.remove_obsolete_tasks()
|
||||
|
||||
self.collect_tasks()
|
||||
self.start_background_tasks()
|
||||
|
||||
if not isInTestMode(): # pragma: no cover
|
||||
if not InvenTree.ready.isInTestMode(): # pragma: no cover
|
||||
self.update_exchange_rates()
|
||||
# Let the background worker check for migrations
|
||||
InvenTree.tasks.offload_task(InvenTree.tasks.check_for_migrations)
|
||||
@@ -58,7 +61,7 @@ class InvenTreeConfig(AppConfig):
|
||||
# Ensure the unit registry is loaded
|
||||
InvenTree.conversion.get_unit_registry()
|
||||
|
||||
if canAppAccessDatabase() or settings.TESTING_ENV:
|
||||
if InvenTree.ready.canAppAccessDatabase() or settings.TESTING_ENV:
|
||||
self.add_user_on_startup()
|
||||
|
||||
def remove_obsolete_tasks(self):
|
||||
|
||||
@@ -62,7 +62,7 @@ def reload_unit_registry():
|
||||
pass
|
||||
|
||||
dt = time.time() - t_start
|
||||
logger.debug('Loaded unit registry in %s.3f s', dt)
|
||||
logger.debug('Loaded unit registry in %.3f s', dt)
|
||||
|
||||
return reg
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from allauth.account.adapter import DefaultAccountAdapter
|
||||
from allauth.account.forms import LoginForm, SignupForm, set_form_field_order
|
||||
from allauth.exceptions import ImmediateHttpResponse
|
||||
from allauth.core.exceptions import ImmediateHttpResponse
|
||||
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
|
||||
from allauth_2fa.adapter import OTPAdapter
|
||||
from allauth_2fa.utils import user_has_valid_totp_device
|
||||
@@ -24,6 +24,7 @@ from crispy_forms.layout import Field, Layout
|
||||
from dj_rest_auth.registration.serializers import RegisterSerializer
|
||||
from rest_framework import serializers
|
||||
|
||||
import InvenTree.sso
|
||||
from common.models import InvenTreeSetting
|
||||
from InvenTree.exceptions import log_error
|
||||
|
||||
@@ -228,7 +229,7 @@ class CustomSignupForm(SignupForm):
|
||||
|
||||
def registration_enabled():
|
||||
"""Determine whether user registration is enabled."""
|
||||
if InvenTreeSetting.get_setting('LOGIN_ENABLE_REG') or InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'):
|
||||
if InvenTreeSetting.get_setting('LOGIN_ENABLE_REG') or InvenTree.sso.registration_enabled():
|
||||
if settings.EMAIL_HOST:
|
||||
return True
|
||||
else:
|
||||
@@ -358,6 +359,13 @@ class CustomSocialAccountAdapter(CustomUrlMixin, RegistratonMixin, DefaultSocial
|
||||
# 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):
|
||||
"""Callback method for authentication errors."""
|
||||
|
||||
# Log the error to the database
|
||||
log_error(request.path if request else 'sso')
|
||||
logger.error("SSO error for provider '%s' - check admin error log", provider_id)
|
||||
|
||||
|
||||
# override dj-rest-auth
|
||||
class CustomRegisterSerializer(RegisterSerializer):
|
||||
|
||||
@@ -840,3 +840,8 @@ def inheritors(cls):
|
||||
subcls.add(child)
|
||||
work.append(child)
|
||||
return subcls
|
||||
|
||||
|
||||
def is_ajax(request):
|
||||
"""Check if the current request is an AJAX request."""
|
||||
return request.headers.get('x-requested-with') == 'XMLHttpRequest'
|
||||
|
||||
@@ -16,7 +16,11 @@ def isImportingData():
|
||||
|
||||
def isRunningMigrations():
|
||||
"""Return True if the database is currently running migrations."""
|
||||
return 'migrate' in sys.argv or 'makemigrations' in sys.argv
|
||||
return any((x in sys.argv for x in [
|
||||
'migrate',
|
||||
'makemigrations',
|
||||
'showmigrations'
|
||||
]))
|
||||
|
||||
|
||||
def isInMainThread():
|
||||
|
||||
@@ -288,6 +288,7 @@ MIDDLEWARE = CONFIG.get('middleware', [
|
||||
'InvenTree.middleware.InvenTreeRemoteUserMiddleware', # Remote / proxy auth
|
||||
'django_otp.middleware.OTPMiddleware', # MFA support
|
||||
'InvenTree.middleware.CustomAllauthTwoFactorMiddleware', # Flow control for allauth
|
||||
'allauth.account.middleware.AccountMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
'InvenTree.middleware.AuthRequiredMiddleware',
|
||||
@@ -956,6 +957,13 @@ SITE_ID = 1
|
||||
SOCIAL_BACKENDS = get_setting('INVENTREE_SOCIAL_BACKENDS', 'social_backends', [], typecast=list)
|
||||
|
||||
for app in SOCIAL_BACKENDS:
|
||||
|
||||
# Ensure that the app starts with 'allauth.socialaccount.providers'
|
||||
social_prefix = 'allauth.socialaccount.providers.'
|
||||
|
||||
if not app.startswith(social_prefix): # pragma: no cover
|
||||
app = social_prefix + app
|
||||
|
||||
INSTALLED_APPS.append(app) # pragma: no cover
|
||||
|
||||
SOCIALACCOUNT_PROVIDERS = get_setting('INVENTREE_SOCIAL_PROVIDERS', 'social_providers', None, typecast=dict)
|
||||
|
||||
@@ -2,13 +2,10 @@
|
||||
import logging
|
||||
from importlib import import_module
|
||||
|
||||
from django.urls import include, path, reverse
|
||||
from django.urls import NoReverseMatch, include, path, reverse
|
||||
|
||||
from allauth.account.models import EmailAddress
|
||||
from allauth.socialaccount import providers
|
||||
from allauth.socialaccount.models import SocialApp
|
||||
from allauth.socialaccount.providers.keycloak.views import \
|
||||
KeycloakOAuth2Adapter
|
||||
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
|
||||
OAuth2LoginView)
|
||||
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
||||
@@ -16,6 +13,7 @@ from rest_framework.exceptions import NotFound
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
|
||||
import InvenTree.sso
|
||||
from common.models import InvenTreeSetting
|
||||
from InvenTree.mixins import CreateAPI, ListAPI, ListCreateAPI
|
||||
from InvenTree.serializers import InvenTreeModelSerializer
|
||||
@@ -51,14 +49,6 @@ def handle_oauth2(adapter: OAuth2Adapter):
|
||||
]
|
||||
|
||||
|
||||
def handle_keycloak():
|
||||
"""Define urls for keycloak."""
|
||||
return [
|
||||
path('login/', GenericOAuth2ApiLoginView.adapter_view(KeycloakOAuth2Adapter), name='keycloak_api_login'),
|
||||
path('connect/', GenericOAuth2ApiConnectView.adapter_view(KeycloakOAuth2Adapter), name='keycloak_api_connet'),
|
||||
]
|
||||
|
||||
|
||||
legacy = {
|
||||
'twitter': 'twitter_oauth2',
|
||||
'bitbucket': 'bitbucket_oauth2',
|
||||
@@ -72,10 +62,13 @@ legacy = {
|
||||
social_auth_urlpatterns = []
|
||||
|
||||
provider_urlpatterns = []
|
||||
for provider in providers.registry.get_list():
|
||||
|
||||
for name, provider in providers.registry.provider_map.items():
|
||||
|
||||
try:
|
||||
prov_mod = import_module(provider.get_package() + ".views")
|
||||
except ImportError:
|
||||
logger.exception("Could not import authentication provider %s", name)
|
||||
continue
|
||||
|
||||
# Try to extract the adapter class
|
||||
@@ -89,8 +82,6 @@ for provider in providers.registry.get_list():
|
||||
if provider.id in legacy:
|
||||
logger.warning('`%s` is not supported on platform UI. Use `%s` instead.', provider.id, legacy[provider.id])
|
||||
continue
|
||||
elif provider.id == 'keycloak':
|
||||
urls = handle_keycloak()
|
||||
else:
|
||||
logger.error('Found handler that is not yet ready for platform UI: `%s`. Open an feature request on GitHub if you need it implemented.', provider.id)
|
||||
continue
|
||||
@@ -107,26 +98,31 @@ class SocialProviderListView(ListAPI):
|
||||
def get(self, request, *args, **kwargs):
|
||||
"""Get the list of providers."""
|
||||
provider_list = []
|
||||
for provider in providers.registry.get_list():
|
||||
for provider in providers.registry.provider_map.values():
|
||||
provider_data = {
|
||||
'id': provider.id,
|
||||
'name': provider.name,
|
||||
'login': request.build_absolute_uri(reverse(f'{provider.id}_api_login')),
|
||||
'connect': request.build_absolute_uri(reverse(f'{provider.id}_api_connect')),
|
||||
'configured': False
|
||||
}
|
||||
|
||||
try:
|
||||
provider_app = provider.get_app(request)
|
||||
provider_data['display_name'] = provider_app.name
|
||||
provider_data['configured'] = True
|
||||
except SocialApp.DoesNotExist:
|
||||
provider_data['display_name'] = provider.name
|
||||
provider_data['login'] = request.build_absolute_uri(reverse(f'{provider.id}_api_login'))
|
||||
except NoReverseMatch:
|
||||
provider_data['login'] = None
|
||||
|
||||
try:
|
||||
provider_data['connect'] = request.build_absolute_uri(reverse(f'{provider.id}_api_connect'))
|
||||
except NoReverseMatch:
|
||||
provider_data['connect'] = None
|
||||
|
||||
provider_data['configured'] = InvenTree.sso.check_provider(provider)
|
||||
provider_data['display_name'] = InvenTree.sso.provider_display_name(provider)
|
||||
|
||||
provider_list.append(provider_data)
|
||||
|
||||
data = {
|
||||
'sso_enabled': InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO'),
|
||||
'sso_registration': InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'),
|
||||
'sso_enabled': InvenTree.sso.login_enabled(),
|
||||
'sso_registration': InvenTree.sso.registration_enabled(),
|
||||
'mfa_required': InvenTreeSetting.get_setting('LOGIN_ENFORCE_MFA'),
|
||||
'providers': provider_list
|
||||
}
|
||||
|
||||
81
InvenTree/InvenTree/sso.py
Normal file
81
InvenTree/InvenTree/sso.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""Helper functions for Single Sign On functionality"""
|
||||
|
||||
|
||||
import logging
|
||||
|
||||
from common.models import InvenTreeSetting
|
||||
from InvenTree.helpers import str2bool
|
||||
|
||||
logger = logging.getLogger('inventree')
|
||||
|
||||
|
||||
def get_provider_app(provider):
|
||||
"""Return the SocialApp object for the given provider"""
|
||||
|
||||
from allauth.socialaccount.models import SocialApp
|
||||
|
||||
try:
|
||||
apps = SocialApp.objects.filter(provider__iexact=provider.id)
|
||||
except SocialApp.DoesNotExist:
|
||||
logger.warning("SSO SocialApp not found for provider '%s'", provider.id)
|
||||
return None
|
||||
|
||||
if apps.count() > 1:
|
||||
logger.warning("Multiple SocialApps found for provider '%s'", provider.id)
|
||||
|
||||
if apps.count() == 0:
|
||||
logger.warning("SSO SocialApp not found for provider '%s'", provider.id)
|
||||
|
||||
return apps.first()
|
||||
|
||||
|
||||
def check_provider(provider, raise_error=False):
|
||||
"""Check if the given provider is correctly configured.
|
||||
|
||||
To be correctly configured, the following must be true:
|
||||
|
||||
- Provider must either have a registered SocialApp
|
||||
- Must have at least one site enabled
|
||||
"""
|
||||
|
||||
import allauth.app_settings
|
||||
|
||||
# First, check that the provider is enabled
|
||||
app = get_provider_app(provider)
|
||||
|
||||
if not app:
|
||||
return False
|
||||
|
||||
if allauth.app_settings.SITES_ENABLED:
|
||||
# At least one matching site must be specified
|
||||
if not app.sites.exists():
|
||||
logger.error("SocialApp %s has no sites configured", app)
|
||||
return False
|
||||
|
||||
# At this point, we assume that the provider is correctly configured
|
||||
return True
|
||||
|
||||
|
||||
def provider_display_name(provider):
|
||||
"""Return the 'display name' for the given provider"""
|
||||
|
||||
if app := get_provider_app(provider):
|
||||
return app.name
|
||||
|
||||
# Fallback value if app not found
|
||||
return provider.name
|
||||
|
||||
|
||||
def login_enabled() -> bool:
|
||||
"""Return True if SSO login is enabled"""
|
||||
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO'))
|
||||
|
||||
|
||||
def registration_enabled() -> bool:
|
||||
"""Return True if SSO registration is enabled"""
|
||||
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'))
|
||||
|
||||
|
||||
def auto_registration_enabled() -> bool:
|
||||
"""Return True if SSO auto-registration is enabled"""
|
||||
return str2bool(InvenTreeSetting.get_setting('LOGIN_SIGNUP_SSO_AUTO'))
|
||||
@@ -19,7 +19,7 @@ from dulwich.repo import NotGitRepository, Repo
|
||||
from .api_version import INVENTREE_API_TEXT, INVENTREE_API_VERSION
|
||||
|
||||
# InvenTree software version
|
||||
INVENTREE_SW_VERSION = "0.13.0"
|
||||
INVENTREE_SW_VERSION = "0.13.1"
|
||||
|
||||
# Discover git
|
||||
try:
|
||||
@@ -105,7 +105,7 @@ def inventreeDocUrl():
|
||||
|
||||
def inventreeAppUrl():
|
||||
"""Return URL for InvenTree app site."""
|
||||
return f'{inventreeDocUrl()}/app/app',
|
||||
return f'{inventreeDocUrl()}/app/app/'
|
||||
|
||||
|
||||
def inventreeCreditsUrl():
|
||||
|
||||
@@ -33,7 +33,7 @@ from part.models import PartCategory
|
||||
from users.models import RuleSet, check_user_role
|
||||
|
||||
from .forms import EditUserForm, SetPasswordForm
|
||||
from .helpers import remove_non_printable_characters, strip_html_tags
|
||||
from .helpers import is_ajax, remove_non_printable_characters, strip_html_tags
|
||||
|
||||
|
||||
def auth_request(request):
|
||||
@@ -258,7 +258,7 @@ class AjaxMixin(InvenTreeRoleMixin):
|
||||
if not data:
|
||||
data = {}
|
||||
|
||||
if not request.is_ajax():
|
||||
if not is_ajax(request):
|
||||
return HttpResponseRedirect('/')
|
||||
|
||||
if context is None:
|
||||
|
||||
@@ -4,7 +4,7 @@ import logging
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
from InvenTree.ready import isImportingData
|
||||
import InvenTree.ready
|
||||
|
||||
logger = logging.getLogger('inventree')
|
||||
|
||||
@@ -19,6 +19,10 @@ class CommonConfig(AppConfig):
|
||||
|
||||
def ready(self):
|
||||
"""Initialize restart flag clearance on startup."""
|
||||
|
||||
if InvenTree.ready.isRunningMigrations():
|
||||
return
|
||||
|
||||
self.clear_restart_flag()
|
||||
|
||||
def clear_restart_flag(self):
|
||||
@@ -29,7 +33,7 @@ class CommonConfig(AppConfig):
|
||||
if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED', backup_value=False, create=False, cache=False):
|
||||
logger.info("Clearing SERVER_RESTART_REQUIRED flag")
|
||||
|
||||
if not isImportingData():
|
||||
if not InvenTree.ready.isImportingData():
|
||||
common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -233,13 +233,13 @@ remote_login_header: HTTP_REMOTE_USER
|
||||
# social_backends:
|
||||
# - 'allauth.socialaccount.providers.google'
|
||||
# - 'allauth.socialaccount.providers.github'
|
||||
# - 'allauth.socialaccount.providers.keycloak'
|
||||
|
||||
# Add specific settings for social account providers (if required)
|
||||
# Refer to the djngo-allauth documentation for more details:
|
||||
# https://docs.allauth.org/en/latest/socialaccount/provider_configuration.html
|
||||
# social_providers:
|
||||
# keycloak:
|
||||
# KEYCLOAK_URL: 'https://keycloak.custom/auth'
|
||||
# KEYCLOAK_REALM: 'master'
|
||||
# github:
|
||||
# VERIFIED_EMAIL: true
|
||||
|
||||
# Add LDAP support
|
||||
# ldap:
|
||||
|
||||
@@ -12,8 +12,7 @@ from django.conf import settings
|
||||
from django.core.exceptions import AppRegistryNotReady
|
||||
from django.db.utils import IntegrityError, OperationalError, ProgrammingError
|
||||
|
||||
from InvenTree.ready import (canAppAccessDatabase, isImportingData,
|
||||
isInMainThread, isPluginRegistryLoaded)
|
||||
import InvenTree.ready
|
||||
|
||||
logger = logging.getLogger("inventree")
|
||||
|
||||
@@ -37,10 +36,13 @@ class LabelConfig(AppConfig):
|
||||
def ready(self):
|
||||
"""This function is called whenever the label app is loaded."""
|
||||
# skip loading if plugin registry is not loaded or we run in a background thread
|
||||
if not isPluginRegistryLoaded() or not isInMainThread():
|
||||
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
|
||||
return
|
||||
|
||||
if canAppAccessDatabase(allow_test=False) and not isImportingData():
|
||||
if InvenTree.ready.isRunningMigrations():
|
||||
return
|
||||
|
||||
if InvenTree.ready.canAppAccessDatabase(allow_test=False) and not InvenTree.ready.isImportingData():
|
||||
try:
|
||||
self.create_labels() # pragma: no cover
|
||||
except (AppRegistryNotReady, IntegrityError, OperationalError, ProgrammingError):
|
||||
|
||||
@@ -7,6 +7,7 @@ from import_export import widgets
|
||||
from import_export.admin import ImportExportModelAdmin
|
||||
from import_export.fields import Field
|
||||
|
||||
import stock.models
|
||||
from InvenTree.admin import InvenTreeResource
|
||||
from order import models
|
||||
|
||||
@@ -79,9 +80,30 @@ class PurchaseOrderLineItemInlineAdmin(admin.StackedInline):
|
||||
extra = 0
|
||||
|
||||
|
||||
class PurchaseOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
|
||||
"""Class for managing import / export of PurchaseOrder data."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass"""
|
||||
model = models.PurchaseOrder
|
||||
skip_unchanged = True
|
||||
clean_model_instances = True
|
||||
exclude = [
|
||||
'metadata',
|
||||
]
|
||||
|
||||
# Add number of line items
|
||||
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
|
||||
|
||||
# Is this order overdue?
|
||||
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
|
||||
|
||||
|
||||
class PurchaseOrderAdmin(ImportExportModelAdmin):
|
||||
"""Admin class for the PurchaseOrder model"""
|
||||
|
||||
resource_class = PurchaseOrderResource
|
||||
|
||||
exclude = [
|
||||
'reference_int',
|
||||
]
|
||||
@@ -107,9 +129,30 @@ class PurchaseOrderAdmin(ImportExportModelAdmin):
|
||||
autocomplete_fields = ('supplier',)
|
||||
|
||||
|
||||
class SalesOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
|
||||
"""Class for managing import / export of SalesOrder data."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options"""
|
||||
model = models.SalesOrder
|
||||
skip_unchanged = True
|
||||
clean_model_instances = True
|
||||
exclude = [
|
||||
'metadata',
|
||||
]
|
||||
|
||||
# Add number of line items
|
||||
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
|
||||
|
||||
# Is this order overdue?
|
||||
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
|
||||
|
||||
|
||||
class SalesOrderAdmin(ImportExportModelAdmin):
|
||||
"""Admin class for the SalesOrder model"""
|
||||
|
||||
resource_class = SalesOrderResource
|
||||
|
||||
exclude = [
|
||||
'reference_int',
|
||||
]
|
||||
@@ -131,25 +174,6 @@ class SalesOrderAdmin(ImportExportModelAdmin):
|
||||
autocomplete_fields = ('customer',)
|
||||
|
||||
|
||||
class PurchaseOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
|
||||
"""Class for managing import / export of PurchaseOrder data."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass"""
|
||||
model = models.PurchaseOrder
|
||||
skip_unchanged = True
|
||||
clean_model_instances = True
|
||||
exclude = [
|
||||
'metadata',
|
||||
]
|
||||
|
||||
# Add number of line items
|
||||
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
|
||||
|
||||
# Is this order overdue?
|
||||
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
|
||||
|
||||
|
||||
class PurchaseOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
|
||||
"""Class for managing import / export of PurchaseOrderLineItem data."""
|
||||
|
||||
@@ -168,6 +192,11 @@ class PurchaseOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
|
||||
|
||||
SKU = Field(attribute='part__SKU', readonly=True)
|
||||
|
||||
destination = Field(
|
||||
attribute='destination',
|
||||
widget=widgets.ForeignKeyWidget(stock.models.StockLocation),
|
||||
)
|
||||
|
||||
def dehydrate_purchase_price(self, line):
|
||||
"""Return a string value of the 'purchase_price' field, rather than the 'Money' object"""
|
||||
if line.purchase_price:
|
||||
@@ -184,25 +213,6 @@ class PurchaseOrderExtraLineResource(PriceResourceMixin, InvenTreeResource):
|
||||
model = models.PurchaseOrderExtraLine
|
||||
|
||||
|
||||
class SalesOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
|
||||
"""Class for managing import / export of SalesOrder data."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options"""
|
||||
model = models.SalesOrder
|
||||
skip_unchanged = True
|
||||
clean_model_instances = True
|
||||
exclude = [
|
||||
'metadata',
|
||||
]
|
||||
|
||||
# Add number of line items
|
||||
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
|
||||
|
||||
# Is this order overdue?
|
||||
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
|
||||
|
||||
|
||||
class SalesOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
|
||||
"""Class for managing import / export of SalesOrderLineItem data."""
|
||||
|
||||
@@ -334,6 +344,8 @@ class ReturnOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, Inv
|
||||
class ReturnOrderAdmin(ImportExportModelAdmin):
|
||||
"""Admin class for the ReturnOrder model"""
|
||||
|
||||
resource_class = ReturnOrderResource
|
||||
|
||||
exclude = [
|
||||
'reference_int',
|
||||
]
|
||||
|
||||
@@ -1926,6 +1926,7 @@ class ReturnOrder(TotalPriceMixin, Order):
|
||||
stock_item.customer = None
|
||||
stock_item.sales_order = None
|
||||
stock_item.save(add_note=False)
|
||||
stock_item.clearAllocations()
|
||||
|
||||
# Add a tracking entry to the StockItem
|
||||
stock_item.add_tracking_entry(
|
||||
|
||||
@@ -247,7 +247,7 @@ class PurchaseOrderCancelSerializer(serializers.Serializer):
|
||||
self.order = self.context['order']
|
||||
|
||||
return {
|
||||
'can_cancel': self.order.can_cancel(),
|
||||
'can_cancel': self.order.can_cancel,
|
||||
}
|
||||
|
||||
def save(self):
|
||||
@@ -1219,7 +1219,7 @@ class SalesOrderCancelSerializer(serializers.Serializer):
|
||||
order = self.context['order']
|
||||
|
||||
return {
|
||||
'can_cancel': order.can_cancel(),
|
||||
'can_cancel': order.can_cancel,
|
||||
}
|
||||
|
||||
def save(self):
|
||||
|
||||
@@ -356,9 +356,32 @@ class BomItemAdmin(ImportExportModelAdmin):
|
||||
autocomplete_fields = ('part', 'sub_part',)
|
||||
|
||||
|
||||
class ParameterTemplateResource(InvenTreeResource):
|
||||
"""Class for managing ParameterTemplate import/export"""
|
||||
|
||||
# The following fields will be converted from None to ''
|
||||
CONVERT_NULL_FIELDS = [
|
||||
'choices',
|
||||
'units'
|
||||
]
|
||||
|
||||
class Meta:
|
||||
"""Metaclass definition"""
|
||||
model = models.PartParameterTemplate
|
||||
skip_unchanged = True
|
||||
report_skipped = False
|
||||
clean_model_instances = True
|
||||
|
||||
exclude = [
|
||||
'metadata',
|
||||
]
|
||||
|
||||
|
||||
class ParameterTemplateAdmin(ImportExportModelAdmin):
|
||||
"""Admin class for the PartParameterTemplate model"""
|
||||
|
||||
resource_class = ParameterTemplateResource
|
||||
|
||||
list_display = ('name', 'units')
|
||||
|
||||
search_fields = ('name', 'units')
|
||||
|
||||
@@ -22,8 +22,8 @@ from InvenTree.api import (APIDownloadMixin, AttachmentMixin,
|
||||
from InvenTree.filters import (ORDER_FILTER, SEARCH_ORDER_FILTER,
|
||||
SEARCH_ORDER_FILTER_ALIAS, InvenTreeDateFilter,
|
||||
InvenTreeSearchFilter)
|
||||
from InvenTree.helpers import (DownloadFile, increment_serial_number, isNull,
|
||||
str2bool, str2int)
|
||||
from InvenTree.helpers import (DownloadFile, increment_serial_number, is_ajax,
|
||||
isNull, str2bool, str2int)
|
||||
from InvenTree.mixins import (CreateAPI, CustomRetrieveUpdateDestroyAPI,
|
||||
ListAPI, ListCreateAPI, RetrieveAPI,
|
||||
RetrieveUpdateAPI, RetrieveUpdateDestroyAPI,
|
||||
@@ -1069,7 +1069,7 @@ class PartList(PartMixin, APIDownloadMixin, ListCreateAPI):
|
||||
"""
|
||||
if page is not None:
|
||||
return self.get_paginated_response(data)
|
||||
elif request.is_ajax():
|
||||
elif is_ajax(request):
|
||||
return JsonResponse(data, safe=False)
|
||||
return Response(data)
|
||||
|
||||
@@ -1740,7 +1740,7 @@ class BomList(BomMixin, ListCreateDestroyAPIView):
|
||||
"""
|
||||
if page is not None:
|
||||
return self.get_paginated_response(data)
|
||||
elif request.is_ajax():
|
||||
elif is_ajax(request):
|
||||
return JsonResponse(data, safe=False)
|
||||
return Response(data)
|
||||
|
||||
|
||||
@@ -5,8 +5,7 @@ import logging
|
||||
from django.apps import AppConfig
|
||||
from django.db.utils import OperationalError, ProgrammingError
|
||||
|
||||
from InvenTree.ready import (canAppAccessDatabase, isImportingData,
|
||||
isInMainThread, isPluginRegistryLoaded)
|
||||
import InvenTree.ready
|
||||
|
||||
logger = logging.getLogger("inventree")
|
||||
|
||||
@@ -18,10 +17,13 @@ class PartConfig(AppConfig):
|
||||
def ready(self):
|
||||
"""This function is called whenever the Part app is loaded."""
|
||||
# skip loading if plugin registry is not loaded or we run in a background thread
|
||||
if not isPluginRegistryLoaded() or not isInMainThread():
|
||||
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
|
||||
return
|
||||
|
||||
if canAppAccessDatabase():
|
||||
if InvenTree.ready.isRunningMigrations():
|
||||
return
|
||||
|
||||
if InvenTree.ready.canAppAccessDatabase():
|
||||
self.update_trackable_status()
|
||||
self.reset_part_pricing_flags()
|
||||
|
||||
@@ -51,7 +53,7 @@ class PartConfig(AppConfig):
|
||||
"""
|
||||
from .models import PartPricing
|
||||
|
||||
if isImportingData():
|
||||
if InvenTree.ready.isImportingData():
|
||||
return
|
||||
|
||||
try:
|
||||
|
||||
@@ -3346,7 +3346,10 @@ class PartParameterTemplate(MetadataMixin, models.Model):
|
||||
})
|
||||
|
||||
# Check that 'choices' are in fact valid
|
||||
self.choices = self.choices.strip()
|
||||
if self.choices is None:
|
||||
self.choices = ''
|
||||
else:
|
||||
self.choices = str(self.choices).strip()
|
||||
|
||||
if self.choices:
|
||||
choice_set = set()
|
||||
|
||||
@@ -539,8 +539,11 @@ def authorized_owners(group):
|
||||
@register.simple_tag()
|
||||
def object_link(url_name, pk, ref):
|
||||
"""Return highlighted link to object."""
|
||||
ref_url = reverse(url_name, kwargs={'pk': pk})
|
||||
return mark_safe(f'<b><a href="{ref_url}">{ref}</a></b>')
|
||||
try:
|
||||
ref_url = reverse(url_name, kwargs={'pk': pk})
|
||||
return mark_safe(f'<b><a href="{ref_url}">{ref}</a></b>')
|
||||
except NoReverseMatch:
|
||||
return None
|
||||
|
||||
|
||||
@register.simple_tag()
|
||||
|
||||
@@ -1,58 +1,32 @@
|
||||
"""This module provides template tags pertaining to SSO functionality"""
|
||||
|
||||
import logging
|
||||
|
||||
from django import template
|
||||
|
||||
from common.models import InvenTreeSetting
|
||||
from InvenTree.helpers import str2bool
|
||||
import InvenTree.sso
|
||||
|
||||
register = template.Library()
|
||||
logger = logging.getLogger('inventree')
|
||||
|
||||
|
||||
@register.simple_tag()
|
||||
def sso_login_enabled():
|
||||
"""Return True if single-sign-on is enabled"""
|
||||
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO'))
|
||||
return InvenTree.sso.login_enabled()
|
||||
|
||||
|
||||
@register.simple_tag()
|
||||
def sso_reg_enabled():
|
||||
"""Return True if single-sign-on is enabled for self-registration"""
|
||||
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'))
|
||||
return InvenTree.sso.registration_enabled()
|
||||
|
||||
|
||||
@register.simple_tag()
|
||||
def sso_auto_enabled():
|
||||
"""Return True if single-sign-on is enabled for auto-registration"""
|
||||
return str2bool(InvenTreeSetting.get_setting('LOGIN_SIGNUP_SSO_AUTO'))
|
||||
return InvenTree.sso.auto_registration_enabled()
|
||||
|
||||
|
||||
@register.simple_tag()
|
||||
def sso_check_provider(provider):
|
||||
"""Return True if the given provider is correctly configured"""
|
||||
import allauth.app_settings
|
||||
from allauth.socialaccount.models import SocialApp
|
||||
|
||||
# First, check that the provider is enabled
|
||||
apps = SocialApp.objects.filter(provider__iexact=provider.id)
|
||||
|
||||
if not apps.exists():
|
||||
logging.error(
|
||||
"SSO SocialApp %s does not exist (known providers: %s)",
|
||||
provider.id, [obj.provider for obj in SocialApp.objects.all()]
|
||||
)
|
||||
return False
|
||||
|
||||
# Next, check that the provider is correctly configured
|
||||
app = apps.first()
|
||||
|
||||
if allauth.app_settings.SITES_ENABLED:
|
||||
# At least one matching site must be specified
|
||||
if not app.sites.exists():
|
||||
logger.error("SocialApp %s has no sites configured", app)
|
||||
return False
|
||||
|
||||
# At this point, we assume that the provider is correctly configured
|
||||
return True
|
||||
return InvenTree.sso.check_provider(provider)
|
||||
|
||||
@@ -528,7 +528,7 @@ report_api_urls = [
|
||||
path(r'<int:pk>/', include([
|
||||
re_path(r'print/?', BuildReportPrint.as_view(), name='api-build-report-print'),
|
||||
re_path(r'metadata/', MetadataView.as_view(), {'model': BuildReport}, name='api-build-report-metadata'),
|
||||
re_path(r'^.$', BuildReportDetail.as_view(), name='api-build-report-detail'),
|
||||
re_path(r'^.*$', BuildReportDetail.as_view(), name='api-build-report-detail'),
|
||||
])),
|
||||
|
||||
# List view
|
||||
|
||||
@@ -20,11 +20,13 @@ class ReportConfig(AppConfig):
|
||||
|
||||
def ready(self):
|
||||
"""This function is called whenever the report app is loaded."""
|
||||
from InvenTree.ready import (canAppAccessDatabase, isImportingData,
|
||||
isInMainThread, isPluginRegistryLoaded)
|
||||
import InvenTree.ready
|
||||
|
||||
# skip loading if plugin registry is not loaded or we run in a background thread
|
||||
if not isPluginRegistryLoaded() or not isInMainThread():
|
||||
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
|
||||
return
|
||||
|
||||
if InvenTree.ready.isRunningMigrations():
|
||||
return
|
||||
|
||||
# Configure logging for PDF generation (disable "info" messages)
|
||||
@@ -32,7 +34,7 @@ class ReportConfig(AppConfig):
|
||||
logging.getLogger('weasyprint').setLevel(logging.WARNING)
|
||||
|
||||
# Create entries for default report templates
|
||||
if canAppAccessDatabase(allow_test=False) and not isImportingData():
|
||||
if InvenTree.ready.canAppAccessDatabase(allow_test=False) and not InvenTree.ready.isImportingData():
|
||||
|
||||
try:
|
||||
self.create_default_test_reports()
|
||||
|
||||
@@ -27,8 +27,8 @@ from InvenTree.api import (APIDownloadMixin, AttachmentMixin,
|
||||
ListCreateDestroyAPIView, MetadataView)
|
||||
from InvenTree.filters import (ORDER_FILTER, SEARCH_ORDER_FILTER,
|
||||
SEARCH_ORDER_FILTER_ALIAS, InvenTreeDateFilter)
|
||||
from InvenTree.helpers import (DownloadFile, extract_serial_numbers, isNull,
|
||||
str2bool, str2int)
|
||||
from InvenTree.helpers import (DownloadFile, extract_serial_numbers, is_ajax,
|
||||
isNull, str2bool, str2int)
|
||||
from InvenTree.mixins import (CreateAPI, CustomRetrieveUpdateDestroyAPI,
|
||||
ListAPI, ListCreateAPI, RetrieveAPI,
|
||||
RetrieveUpdateDestroyAPI)
|
||||
@@ -963,7 +963,7 @@ class StockList(APIDownloadMixin, ListCreateDestroyAPIView):
|
||||
|
||||
if page is not None:
|
||||
return self.get_paginated_response(data)
|
||||
elif request.is_ajax():
|
||||
elif is_ajax(request):
|
||||
return JsonResponse(data, safe=False)
|
||||
return Response(data)
|
||||
|
||||
@@ -1346,7 +1346,7 @@ class StockTrackingList(ListAPI):
|
||||
|
||||
if page is not None:
|
||||
return self.get_paginated_response(data)
|
||||
if request.is_ajax():
|
||||
if is_ajax(request):
|
||||
return JsonResponse(data, safe=False)
|
||||
return Response(data)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends "socialaccount/base.html" %}
|
||||
{% extends "account/base.html" %}
|
||||
|
||||
{% load i18n %}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends "socialaccount/base.html" %}
|
||||
{% extends "account/base.html" %}
|
||||
{% load i18n %}
|
||||
{% load sso %}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends "socialaccount/base.html" %}
|
||||
{% extends "account/base.html" %}
|
||||
|
||||
{% load i18n crispy_forms_tags inventree_extras %}
|
||||
|
||||
|
||||
@@ -5,8 +5,7 @@ import logging
|
||||
from django.apps import AppConfig
|
||||
from django.db.utils import OperationalError, ProgrammingError
|
||||
|
||||
from InvenTree.ready import (canAppAccessDatabase, isInMainThread,
|
||||
isPluginRegistryLoaded)
|
||||
import InvenTree.ready
|
||||
|
||||
logger = logging.getLogger('inventree')
|
||||
|
||||
@@ -19,10 +18,14 @@ class UsersConfig(AppConfig):
|
||||
def ready(self):
|
||||
"""Called when the 'users' app is loaded at runtime"""
|
||||
# skip loading if plugin registry is not loaded or we run in a background thread
|
||||
if not isPluginRegistryLoaded() or not isInMainThread():
|
||||
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
|
||||
return
|
||||
|
||||
if canAppAccessDatabase(allow_test=True):
|
||||
# Skip if running migrations
|
||||
if InvenTree.ready.isRunningMigrations():
|
||||
return
|
||||
|
||||
if InvenTree.ready.canAppAccessDatabase(allow_test=True):
|
||||
|
||||
try:
|
||||
self.assign_permissions()
|
||||
|
||||
@@ -236,7 +236,7 @@ function update_or_install() {
|
||||
# Run update as app user
|
||||
echo "# Updating InvenTree"
|
||||
sudo -u ${APP_USER} --preserve-env=$SETUP_ENVS bash -c "cd ${APP_HOME} && pip install wheel"
|
||||
sudo -u ${APP_USER} --preserve-env=$SETUP_ENVS bash -c "cd ${APP_HOME} && invoke update --no-frontend | sed -e 's/^/# inv update| /;'"
|
||||
sudo -u ${APP_USER} --preserve-env=$SETUP_ENVS bash -c "cd ${APP_HOME} && invoke update | sed -e 's/^/# inv update| /;'"
|
||||
|
||||
# Make sure permissions are correct again
|
||||
echo "# Set permissions for data dir and media: ${DATA_DIR}"
|
||||
|
||||
@@ -9,6 +9,9 @@ InvenTree provides the possibility to use 3rd party services to authenticate use
|
||||
!!! tip "Provider Documentation"
|
||||
There are a lot of technical considerations when configuring a particular SSO provider. A good starting point is the [django-allauth documentation](https://django-allauth.readthedocs.io/en/latest/socialaccount/providers/index.html)
|
||||
|
||||
!!! warning "Advanced Users"
|
||||
The SSO functionality provided by django-allauth is powerful, but can prove challenging to configure. Please ensure that you understand the implications of enabling SSO for your InvenTree instance. Specific technical details of each available SSO provider are beyond the scope of this documentation - please refer to the [django-allauth documentation](https://django-allauth.readthedocs.io/en/latest/socialaccount/providers/index.html) for more information.
|
||||
|
||||
## SSO Configuration
|
||||
|
||||
The basic requirements for configuring SSO are outlined below:
|
||||
@@ -131,3 +134,7 @@ Make sure all users with admin privileges have sufficient passwords - they can r
|
||||
|
||||
!!! warning "It's a secret!"
|
||||
Never share the secret key associated with your InvenTree install!
|
||||
|
||||
## Error Handling
|
||||
|
||||
If you encounter an error during the SSO process, the error should be logged in the InvenTree database. You can view the [error log](./logs.md) in the [admin interface](./admin.md) to see the details of the error.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Django>=3.2.14,<4 # Django package
|
||||
coreapi # API documentation for djangorestframework
|
||||
cryptography>=40.0.0,!=40.0.2 # Core cryptographic functionality
|
||||
django-allauth<0.55.0 # SSO for external providers via OpenID # FIXED 2023-09-06 due to https://github.com/iMerica/dj-rest-auth/issues/534
|
||||
django-allauth # SSO for external providers via OpenID
|
||||
django-allauth-2fa # MFA / 2FA
|
||||
django-cleanup # Automated deletion of old / unused uploaded files
|
||||
django-cors-headers # CORS headers extension for DRF
|
||||
|
||||
@@ -45,7 +45,7 @@ defusedxml==0.7.1
|
||||
# python3-openid
|
||||
diff-match-patch==20230430
|
||||
# via django-import-export
|
||||
dj-rest-auth==5.0.1
|
||||
dj-rest-auth==5.0.2
|
||||
# via -r requirements.in
|
||||
django==3.2.23
|
||||
# via
|
||||
@@ -81,7 +81,7 @@ django==3.2.23
|
||||
# djangorestframework
|
||||
# djangorestframework-simplejwt
|
||||
# drf-spectacular
|
||||
django-allauth==0.54.0
|
||||
django-allauth==0.59.0
|
||||
# via
|
||||
# -r requirements.in
|
||||
# django-allauth-2fa
|
||||
|
||||
6
tasks.py
6
tasks.py
@@ -347,9 +347,10 @@ def migrate(c):
|
||||
help={
|
||||
'skip_backup': 'Skip database backup step (advanced users)',
|
||||
'frontend': 'Force frontend compilation/download step (ignores INVENTREE_DOCKER)',
|
||||
'no_frontend': 'Skip frontend compilation/download step'
|
||||
}
|
||||
)
|
||||
def update(c, skip_backup=False, frontend: bool = False):
|
||||
def update(c, skip_backup=False, frontend: bool = False, no_frontend: bool = False):
|
||||
"""Update InvenTree installation.
|
||||
|
||||
This command should be invoked after source code has been updated,
|
||||
@@ -378,8 +379,7 @@ def update(c, skip_backup=False, frontend: bool = False):
|
||||
# If:
|
||||
# - INVENTREE_DOCKER is set (by the docker image eg.) and not overridden by `--frontend` flag
|
||||
# - `--no-frontend` flag is set
|
||||
# if (os.environ.get('INVENTREE_DOCKER', False) and not frontend) or no_frontend:
|
||||
if not frontend:
|
||||
if (os.environ.get('INVENTREE_DOCKER', False) and not frontend) or no_frontend:
|
||||
return
|
||||
|
||||
# Decide if we should compile the frontend or try to download it
|
||||
|
||||
Reference in New Issue
Block a user