Release v1.0.0
Some checks failed
CI / Checks (push) Failing after 13m2s

This commit is contained in:
2025-08-20 21:00:50 +02:00
commit b4338e2769
401 changed files with 23576 additions and 0 deletions

View File

@@ -0,0 +1 @@
from .account import AccountAdmin # noqa: F401

View File

@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from hotpocket_backend.apps.accounts.models import Account
class AccountAdmin(UserAdmin):
list_display = (*UserAdmin.list_display, 'is_active')
def has_delete_permission(self, request, obj=None):
return request.user.is_superuser
admin.site.register(Account, AccountAdmin)

View File

@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
label = 'accounts'
name = 'hotpocket_backend.apps.accounts'
verbose_name = _('Accounts')

View File

@@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from hotpocket_backend.apps.accounts.types import PAccount
def is_authenticated_and_active_account(account: PAccount) -> bool:
return all((
account.is_authenticated,
account.is_active,
))

View File

@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from django.http import HttpRequest
from hotpocket_backend.apps.core.conf import settings
def hotpocket_oidc(request: HttpRequest) -> dict:
return {
'HOTPOCKET_OIDC_IS_ENABLED': settings.SECRETS.OIDC.is_enabled,
'HOTPOCKET_OIDC_DISPLAY_NAME': settings.SECRETS.OIDC.display_name,
}
def auth_settings(request: HttpRequest) -> dict:
return {
'MODEL_AUTH_IS_DISABLED': settings.MODEL_AUTH_IS_DISABLED,
}

View File

@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from .checks import is_authenticated_and_active_account
def account_required(function=None,
redirect_field_name=REDIRECT_FIELD_NAME,
login_url=None,
):
actual_decorator = user_passes_test(
is_authenticated_and_active_account,
login_url=login_url,
redirect_field_name=redirect_field_name,
)
if function:
return actual_decorator(function)
return actual_decorator

View File

@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from argparse import ArgumentParser
import logging
from django.core.management import BaseCommand
import django.db
from hotpocket_backend.apps.accounts.models import Account
LOGGER = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Create initial Account'
def add_arguments(self, parser: ArgumentParser):
parser.add_argument(
'username',
help='Username for the Account',
)
parser.add_argument(
'password',
help='Password for the Account',
)
parser.add_argument(
'-d', '--dry-run', action='store_true', default=False,
help='Dry run',
)
def handle(self, *args, **options):
LOGGER.debug('args=`%s` options=`%s`', args, options)
username = options.get('username')
password = options.get('password')
dry_run = options.get('dry_run', False)
with django.db.transaction.atomic():
current_account = Account.objects.filter(username=username).first()
if current_account is not None:
LOGGER.info(
'Account already exists: account=`%s`', current_account,
)
return
account = Account.objects.create(
username=username,
first_name=username,
is_superuser=True,
is_staff=True,
)
account.set_password(password)
account.save()
LOGGER.info(
'Account created: account=`%s`', account,
)
if dry_run is True:
raise RuntimeError('DRY RUN')

View File

@@ -0,0 +1,44 @@
# Generated by Django 5.2.3 on 2025-06-30 20:37
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
import uuid6
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='Account',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('id', models.UUIDField(default=uuid6.uuid7, primary_key=True, serialize=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='account_set', related_query_name='account', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='account_set', related_query_name='account', to='auth.permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'Account',
'verbose_name_plural': 'Accounts',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 5.2.3 on 2025-07-10 19:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='account',
name='settings',
field=models.JSONField(default=dict),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 5.2.3 on 2025-08-02 19:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_account_settings'),
]
operations = [
migrations.AddField(
model_name='account',
name='updated_at',
field=models.DateTimeField(auto_now=True),
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 5.2.3 on 2025-08-08 19:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_account_updated_at'),
]
operations = [
migrations.AlterField(
model_name='account',
name='settings',
field=models.JSONField(db_column='settings', default=dict),
),
migrations.RenameField(
model_name='account',
old_name='settings',
new_name='raw_settings',
),
]

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from django.contrib.auth.mixins import AccessMixin
from .checks import is_authenticated_and_active_account
class AccountRequiredMixin(AccessMixin):
def dispatch(self, request, *args, **kwargs):
if is_authenticated_and_active_account(self.request.user) is False:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)

View File

@@ -0,0 +1 @@
from .account import Account # noqa: F401

View File

@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from django.contrib.auth.models import (
AbstractUser,
Group,
Permission,
UserManager,
)
from django.db import models
from django.utils.translation import gettext_lazy as _
import uuid6
class ActiveAccountsManager(models.Manager):
def get_queryset(self) -> models.QuerySet:
return super().get_queryset().filter(
is_active=True,
is_staff=False,
)
class Account(AbstractUser):
id = models.UUIDField(
null=False, blank=False, default=uuid6.uuid7, primary_key=True,
)
groups = models.ManyToManyField(
Group,
verbose_name=_('groups'),
blank=True,
help_text=_(
(
'The groups this user belongs to. A user will get all '
'permissions granted to each of their groups.'
),
),
related_name='account_set',
related_query_name='account',
)
user_permissions = models.ManyToManyField(
Permission,
verbose_name=_('user permissions'),
blank=True,
help_text=_('Specific permissions for this user.'),
related_name='account_set',
related_query_name='account',
)
raw_settings = models.JSONField(default=dict, db_column='settings')
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
active_accounts = ActiveAccountsManager()
class Meta:
verbose_name = _('Account')
verbose_name_plural = _('Accounts')
def __str__(self) -> str:
return f'<Account pk={self.pk} username={self.username}>'
@property
def settings(self) -> dict:
result = {**self.raw_settings}
auto_load_embeds = result.get('auto_load_embeds', None)
if isinstance(auto_load_embeds, str) is True:
result['auto_load_embeds'] = (auto_load_embeds == 'True')
else:
result['auto_load_embeds'] = auto_load_embeds
return result

View File

@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from social_core.backends.open_id_connect import OpenIdConnectAuth
LOGGER = logging.getLogger(__name__)
class HotPocketOpenIdConnectAuth(OpenIdConnectAuth):
name = 'hotpocket_oidc'
def _get_roles_from_response(response) -> list[str]:
from hotpocket_backend.apps.core.conf import settings
return response.\
get('resource_access', {}).\
get(settings.SECRETS.OIDC.key, {}).\
get('roles', [])
def set_user_is_staff(strategy, details, response, user=None, *args, **kwargs):
if user is None:
return None
roles = _get_roles_from_response(response)
user.is_staff = 'staff' in roles
strategy.storage.user.changed(user)
def set_user_is_superuser(strategy, details, response, user=None, *args, **kwargs):
if user is None:
return None
roles = _get_roles_from_response(response)
user.is_superuser = 'superuser' in roles
strategy.storage.user.changed(user)

View File

@@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import typing
import uuid
class PAccount(typing.Protocol):
id: uuid.UUID
username: str
first_name: str
last_name: str
email: str
is_active: bool
is_anonymous: bool
is_authenticated: bool
pk: uuid.UUID