Metadata-Version: 2.4
Name: django-morest
Version: 0.2.2
Summary: Django api manager and unifier
Author: Sidq
Author-email: abba.dmytro@gmail.com
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: GitHub, https://github.com/sidqdev/django-morest
Project-URL: Telegram, https://t.me/sidqdev
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django
Requires-Dist: djangorestframework
Requires-Dist: PyJWT<3,>=2
Requires-Dist: drf-yasg
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# django-morest

`django-morest` is a small API utility package for Django and Django REST Framework that standardizes:

- JSON response envelopes
- exception handling
- request ids
- reusable query serializers for pagination, search, and ordering
- list/filter API views
- schema and Swagger helpers for `drf-yasg`
- JWT and bearer-token authentication helpers
- a simple encrypted text model field

## Installation

```bash
pip install django-morest
```

If you use `EncryptedTextField`, also install `pycryptodome`.

```bash
pip install pycryptodome
```

## Requirements

- Django
- djangorestframework
- drf-yasg
- PyJWT

## Quick Start

Add `morest` to installed apps and merge the provided presettings into your Django settings.

```python
from morest.core import presettings

INSTALLED_APPS = [
    ...,
    "morest",
    "drf_yasg",
]

MIDDLEWARE = [
    *presettings.MOREST_MIDDLEWARES,
    ...,
]

REST_FRAMEWORK = {
    **presettings.MOREST_REST_FRAMEWORK,
}

LOGGING = presettings.LOGGING
```

If you want the built-in healthcheck endpoint:

```python
from morest.core import presettings

urlpatterns = [
    *presettings.HEALTHCHECK_URLPATTERNS,
    ...,
]
```

If you want the built-in Swagger UI, connect `morest.core.docs.schema_view` in your project URLs.

```python
from django.urls import path
from morest.core import docs

urlpatterns = [
    path("swagger/", docs.schema_view.with_ui("swagger")),
    ...,
]
```

## Presettings

`morest.core.presettings` exposes reusable defaults for Django projects.

### `MOREST_MIDDLEWARES`

```python
MIDDLEWARE = [
    *presettings.MOREST_MIDDLEWARES,
    ...,
]
```

This currently enables:

- `morest.middlewares.RequestIDMiddleware`
- `morest.middlewares.ExceptionMiddleware`

`RequestIDMiddleware` reads the incoming `Request-ID` header when present, otherwise generates one, and adds it to the response headers.

`ExceptionMiddleware` converts unhandled API errors, `Http404`, and plain 404 responses into the standard JSON envelope.

### `MOREST_REST_FRAMEWORK`

```python
REST_FRAMEWORK = {
    **presettings.MOREST_REST_FRAMEWORK,
}
```

This currently sets:

```python
{
    "EXCEPTION_HANDLER": "morest.middlewares.DRFExceptionMiddleware",
}
```

That keeps DRF exceptions inside the same `morest` JSON response format.

### `INSTALLED_APPS`

For the core response, middleware, and view helpers:

```python
INSTALLED_APPS = [
    ...,
    "morest",
]
```

Add `drf_yasg` when you use `morest.core.docs.schema_view`, `docs.schema(...)`, or the Swagger UI.

```python
INSTALLED_APPS = [
    ...,
    "morest",
    "drf_yasg",
]
```

Add `morest.bearertoken` only when you want the bundled database-backed bearer token model.

```python
INSTALLED_APPS = [
    ...,
    "morest",
    "morest.bearertoken",
    "drf_yasg",
]
```

After adding `morest.bearertoken`, run migrations for your project.

### `LOGGING`

```python
LOGGING = presettings.LOGGING
```

The provided logging config:

- logs to console
- only emits through the handler when `DEBUG = False`
- attaches `request_id` to log records through `RequestIDLogFilter`
- exposes ready logger objects in `presettings`: `django_logger`, `django_request_logger`, `django_server_logger`, `morest_logger`

### `HEALTHCHECK_URLPATTERNS`

```python
urlpatterns = [
    *presettings.HEALTHCHECK_URLPATTERNS,
    ...,
]
```

This provides:

- `GET /healthcheck/`

Response:

```json
{
  "data": null,
  "status": "ok",
  "status_code": 200,
  "request_id": "4d06538d2d7b40db8e729757a363fe55",
  "message": "OK"
}
```

## Standard Response Envelope

The central API primitive is `morest.api.Response`.

```python
from morest.api import Response
```

All successful and error responses share the same JSON shape:

```json
{
  "data": {
    "key": "value"
  },
  "status": "ok",
  "status_code": 200,
  "request_id": "4d06538d2d7b40db8e729757a363fe55",
  "message": "OK"
}
```

For non-2xx responses, `error_details` is included.

```json
{
  "data": null,
  "status": "validation_error",
  "status_code": 400,
  "request_id": "4d06538d2d7b40db8e729757a363fe55",
  "message": "Request body or query params validation error",
  "error_details": {
    "email": ["This field is required."]
  }
}
```

## Using `Response`

### Basic success response

```python
from django.http import HttpRequest
from rest_framework.views import APIView
from morest.api import Response


class TestView(APIView):
    def get(self, request: HttpRequest):
        return Response({
            "key": "value",
        })
```

### Explicit status code and message

```python
return Response(
    data={"id": 10},
    status_code=201,
    status="created",
    message="User created",
)
```

### Validation errors from serializers

Use `Response.validation_error(serializer.errors)` whenever request input validation fails.

```python
from rest_framework import serializers
from rest_framework.views import APIView
from morest.api import Response


class CreateUserSerializer(serializers.Serializer):
    email = serializers.EmailField()
    username = serializers.CharField()


class CreateUserView(APIView):
    def post(self, request):
        serializer = CreateUserSerializer(data=request.data)
        if not serializer.is_valid():
            return Response.validation_error(serializer.errors)

        return Response(serializer.validated_data, status_code=201, status="created", message="Created")
```

### Status-only responses

```python
return Response.from_status("ok")
return Response.from_status("fail")
return Response.from_status("error")
```

## Using Errors

The package exposes a base error type plus reusable application errors.

```python
from morest.errors import (
    BaseError,
    InternalError,
    ValidationError,
    NotFoundError,
    AlreadyExistsError,
    InsufficientBalanceError,
    FieldNotFoundError,
)
```

All `BaseError` subclasses can be raised inside views or helper functions. `ExceptionMiddleware` catches them and returns a `Response` automatically.

### Built-in errors

- `InternalError` -> HTTP `500`
- `ValidationError` -> HTTP `400`
- `NotFoundError` -> HTTP `404`
- `AlreadyExistsError` -> HTTP `409`
- `InsufficientBalanceError` -> HTTP `402`
- `FieldNotFoundError` -> HTTP `406`
- `AccessTokenIsInvalidError` -> HTTP `401`
- `RefreshTokenIsInvalidError` -> HTTP `401`

### Raise a built-in error

```python
from morest.errors import NotFoundError


def get_user_or_fail(user_id: int):
    ...
    raise NotFoundError(message="User not found")
```

### Convert an error manually

```python
from morest.errors import ValidationError


error = ValidationError(
    message="Invalid payload",
    error_details={"field": ["This field is required."]},
)
return error.to_response()
```

### Helper constructors

```python
from morest.errors import AlreadyExistsError, InsufficientBalanceError, NotFoundError

raise AlreadyExistsError.with_object_details("User", "email", "john@example.com")
raise InsufficientBalanceError.with_balance_details(current_balance=10, required_balance=25)
raise NotFoundError.with_object_details("User", {"id": 15})
```

### Create your own error type

```python
from morest.errors import BaseError


class PermissionDeniedError(BaseError):
    status_code = 403
    status = "permission_denied"
    message = "You do not have permission to perform this action"
```

## Exception Handling

When you enable both presettings:

```python
MIDDLEWARE = [
    *presettings.MOREST_MIDDLEWARES,
    ...,
]

REST_FRAMEWORK = {
    **presettings.MOREST_REST_FRAMEWORK,
}
```

`morest` normalizes these cases into JSON:

- raised `BaseError`
- DRF `APIException`
- `Http404`
- unresolved routes and plain Django 404 responses
- unexpected exceptions as `InternalError`

Example 404 body:

```json
{
  "data": null,
  "status": "not_found",
  "status_code": 404,
  "request_id": "4d06538d2d7b40db8e729757a363fe55",
  "message": "The requested resource was not found on this server.",
  "error_details": {
    "path": "/missing-url/",
    "method": "GET"
  }
}
```

Note: place `morest.middlewares.ExceptionMiddleware` near the top of `MIDDLEWARE`. Exceptions raised by middleware that runs before it will not be normalized by `morest`.

## List and Filter Views

`morest.views.ListFilterView` is a reusable DRF `APIView` for list endpoints that support:

- plain filtering through serializer fields
- text search
- ordering
- pagination
- generated `drf-yasg` query docs when available

Import it from:

```python
from morest.views import ListFilterView
```

### Basic filtered list view

```python
from rest_framework import serializers
from morest.api import Response
from morest.views import ListFilterView
from morest.utils import PaginationSerializer, SearchSerializer, OrderSerializer
from app.models import Product


class ProductSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    category = serializers.CharField()
    price = serializers.DecimalField(max_digits=10, decimal_places=2)


class ProductListQuerySerializer(PaginationSerializer, SearchSerializer, OrderSerializer):
    category = serializers.CharField(required=False)
    is_active = serializers.BooleanField(required=False)


class ProductListView(ListFilterView):
    queryset = Product.objects.filter(is_deleted=False)
    serializer = ProductSerializer
    filter_serializer = ProductListQuerySerializer
    search_fields = ["name", "category", "=sku", "^name"]
    order_fields = ["id", "name", "price", "created_at"]
    rows_name = "products"
```

This gives you a `GET` endpoint that can accept query params like:

```text
/products/?category=books&is_active=true&page=1&limit=20&q=django&order_by=name&order_by=-created_at
```

### How filtering works

`ListFilterView.get()` executes in this order:

1. load the base queryset from `get_queryset()`
2. validate `request.GET` with `filter_serializer`
3. strip pagination/search/order fields out of the validated data
4. call `filter_queryset()` with the remaining fields
5. apply search through `SearchSerializer`
6. apply ordering through `OrderSerializer`
7. paginate if the query serializer inherits `PaginationSerializer`
8. serialize and return `Response(...)`

### Overriding queryset filtering

By default, `filter_queryset()` performs `qs.filter(**filters).all()`.

Override it when you need custom logic.

```python
class ProductListView(ListFilterView):
    ...

    def filter_queryset(self, request, qs, filters, **kwargs):
        if category := filters.pop("category", None):
            qs = qs.filter(category__slug=category)
        return qs.filter(**filters)
```

### Search behavior

`SearchSerializer` reads the `q` query param and applies `search_in_queryset()` using `search_fields`.

Supported prefixes in `search_fields`:

- `"name"` -> `name__icontains`
- `"^name"` -> `name__istartswith`
- `"=email"` -> `email__iexact`
- `"@body"` -> `body__search`

Example:

```python
search_fields = ["name", "description", "^sku", "=slug"]
```

### Ordering behavior

`OrderSerializer` reads `order_by` as a list.

```text
/products/?order_by=name&order_by=-created_at
```

Restrict allowed fields with `order_fields`:

```python
order_fields = ["name", "created_at", "price"]
```

If a field outside `order_fields` is requested, `FieldNotFoundError` is raised and returned as a `406` JSON error.

### Pagination behavior

`PaginationSerializer` supports:

- `page` with minimum `1`
- `limit` with minimum `1`

Default values:

- `page = 1`
- `limit = 20`

Paginated response shape:

```json
{
  "data": {
    "products": [],
    "rows_count": 0,
    "total_count": 0,
    "pages_count": 0
  },
  "status": "ok",
  "status_code": 200,
  "request_id": "4d06538d2d7b40db8e729757a363fe55",
  "message": "OK"
}
```

Use `rows_name` on the serializer or the view to rename the collection key.

```python
class ProductListQuerySerializer(PaginationSerializer):
    rows_name = "products"
```

or:

```python
class ProductListView(ListFilterView):
    rows_name = "products"
```

### Validation failures in list views

`ListFilterView` already uses `Response.validation_error(...)` for invalid query params.

That means invalid pagination, search, or custom filter serializer input automatically returns a standardized `400` response.

## Query Serializer Utilities

Import these from `morest.utils`:

```python
from morest.utils import PaginationSerializer, SearchSerializer, OrderSerializer, PaginationSearchSerializer
```

### `PaginationSerializer`

Adds:

- `page`
- `limit`
- `.paginate(qs, serializer, rows_name=...)`

### `SearchSerializer`

Adds:

- `q`
- `.filter(qs, search_fields)`

### `OrderSerializer`

Adds:

- `order_by`
- `.order(qs, order_fields=...)`

### `PaginationSearchSerializer`

Convenience serializer that combines:

- `PaginationSerializer`
- `SearchSerializer`

If you need all three features, inherit all three explicitly.

```python
class QuerySerializer(PaginationSerializer, SearchSerializer, OrderSerializer):
    ...
```

## Object Lookup Helpers

Import from:

```python
from morest.generics.get_object import get_object_or_404, get_objects_or_404
```

### `get_object_or_404`

```python
user = get_object_or_404(User.objects, id=user_id)
```

Raises `morest.errors.NotFoundError` instead of Django's default 404 type.

### `get_objects_or_404`

```python
user = get_objects_or_404(User.objects, with_error_details=True, id=user_id)
```

If `with_error_details=True`, the raised `NotFoundError` includes the lookup filters.

## Swagger and Schema Helpers

Import from:

```python
from morest.core import docs
```

### Swagger UI

`morest.core.docs` exposes a ready `drf-yasg` schema view.

```python
from django.urls import path
from morest.core import docs

urlpatterns = [
    path("swagger/", docs.schema_view.with_ui("swagger")),
]
```

Make sure `drf_yasg` is enabled in your Django settings.

```python
INSTALLED_APPS = [
    ...,
    "morest",
    "drf_yasg",
]
```

The built-in `schema_view` is configured with:

- title: `Swagger API`
- version: `v1`
- `SessionAuthentication`
- `IsAdminUser`

That means the Swagger UI is intended for authenticated admin users by default.

### View method schemas

Use `docs.schema(...)` to wrap view methods with a response envelope schema.

```python
from rest_framework import serializers
from rest_framework.views import APIView
from morest.api import Response
from morest.core import docs


class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    username = serializers.CharField()


class CreateUserSerializer(serializers.Serializer):
    username = serializers.CharField()


class UserCreateView(APIView):
    @docs.schema(request_body=CreateUserSerializer, response=UserSerializer)
    def post(self, request):
        ...
        return Response({"id": 1, "username": "john"}, status_code=201, status="created", message="Created")
```

If the request serializer inherits `PaginationSerializer`, `docs.schema()` wraps the response in a paginated envelope automatically.

`ListFilterView.as_view()` also uses `docs.schema(...)` for generated list endpoint docs when `drf-yasg` is installed.

## Authentication

The package ships session auth views, JWT helpers, and an optional database-backed bearer token app.

### Session auth views

Session-based auth views live under `morest.views.auth.session`.

#### `LoginView`

- `GET` returns the current authenticated user serialized by `UserSerializer`
- `POST` expects `username` and `password`

Serializer validation errors are returned via:

```python
Response.validation_error(serializer.errors)
```

#### `LogoutView`

- `POST` logs out the current session user
- returns `Response.from_status("ok")`

### JWT authentication

Import from:

```python
from morest.authentication import JWTAuthentication, get_jwt_manager
from morest.views import RefreshTokenView
```

Configure token secrets in Django settings.

```python
JWT_ACCESS_TOKEN_SECRET = "change-me-access"
JWT_REFRESH_TOKEN_SECRET = "change-me-refresh"

# Optional, in seconds. If omitted, tokens do not expire.
JWT_ACCESS_TOKEN_TTL = 60 * 15
JWT_REFRESH_TOKEN_TTL = 60 * 60 * 24 * 30
```

Use `JWTAuthentication` in DRF settings or on a view.

```python
REST_FRAMEWORK = {
    **presettings.MOREST_REST_FRAMEWORK,
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "morest.authentication.JWTAuthentication",
    ],
}
```

Clients authenticate with:

```text
Authorization: JWT <access_token>
```

Create a token pair for a user:

```python
from morest.authentication import JWTAuthentication


jwt_pair = JWTAuthentication().authorize(user)
```

Expose the refresh endpoint in your URLs:

```python
from django.urls import path
from morest.views import RefreshTokenView

urlpatterns = [
    path("auth/refresh/", RefreshTokenView.as_view()),
]
```

Request body:

```json
{
  "refresh_token": "..."
}
```

Response data:

```json
{
  "access_token": "...",
  "refresh_token": "..."
}
```

Invalid access or refresh tokens raise `AccessTokenIsInvalidError` or `RefreshTokenIsInvalidError` and return a standardized `401` response.

### Bearer token authentication

Import from:

```python
from morest.authentication import BearerTokenAuthentication
```

Enable the bundled token model when you want database-backed bearer tokens.

```python
INSTALLED_APPS = [
    ...,
    "morest",
    "morest.bearertoken",
]
```

Then run migrations.

```bash
python manage.py migrate
```

Use the authentication class in DRF settings or on a view.

```python
REST_FRAMEWORK = {
    **presettings.MOREST_REST_FRAMEWORK,
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "morest.authentication.BearerTokenAuthentication",
    ],
}
```

Clients authenticate with:

```text
Authorization: Bearer <token>
```

`BearerTokenAuthentication` accepts active tokens whose `expires_at` is empty or in the future, and rejects inactive users.

## Admin Form View

`morest.views.AdminFormView` is a DRF `APIView` that renders a Django admin-styled form page.

Use it when you need a custom admin action page backed by a Django form.

```python
from django import forms
from django.http import HttpResponseRedirect
from morest.views import AdminFormView


class SendCreditsForm(forms.Form):
    user_id = forms.IntegerField()
    amount = forms.DecimalField()


class SendCreditsView(AdminFormView):
    form = SendCreditsForm
    action_name = "Send Credits"
    breadcrumbs = (("Home", "/admin/"), ("Send Credits", ""))

    def handle(self, request, form, **kwargs):
        data = form.cleaned_data
        ...
        return HttpResponseRedirect("/admin/")
```

Override these hooks when needed:

- `get_template()`
- `get_action_name()`
- `get_breadcrumbs()`
- `get_context()`
- `handle()`

## Encrypted Text Field

Import from:

```python
from morest.db.fields import EncryptedTextField
```

Example:

```python
from django.db import models
from morest.db.fields import EncryptedTextField


class SecretNote(models.Model):
    title = models.CharField(max_length=255)
    content = EncryptedTextField()
```

You must provide a secret key either:

- per field
- or globally through `DEFAULT_ENCRYPTED_TEXT_FIELD_SECRET_KEY`

Per field:

```python
content = EncryptedTextField(secret_key="your-secret-key")
```

Global setting:

```python
DEFAULT_ENCRYPTED_TEXT_FIELD_SECRET_KEY = "your-secret-key"
```

Behavior:

- values are encrypted before saving to the database
- values are decrypted when loaded from the database
- empty strings are stored as `NULL`

## JSON Encoding

`Response` uses `morest.core.MorestJSONEncoder`, which supports:

- `datetime`
- `date`
- `time`
- `timedelta`
- `decimal.Decimal`
- `uuid.UUID`
- Django lazy `Promise`
- dataclasses

That means you can safely return many Python-native values inside `Response(data=...)` without hand-converting them first.

## Minimal End-to-End Example

```python
from rest_framework import serializers
from morest.api import Response
from morest.views import ListFilterView
from morest.utils import PaginationSerializer, SearchSerializer, OrderSerializer
from morest.errors import NotFoundError
from app.models import Product


class ProductSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    price = serializers.DecimalField(max_digits=10, decimal_places=2)


class ProductQuerySerializer(PaginationSerializer, SearchSerializer, OrderSerializer):
    category = serializers.CharField(required=False)


class ProductListView(ListFilterView):
    queryset = Product.objects.all()
    serializer = ProductSerializer
    filter_serializer = ProductQuerySerializer
    search_fields = ["name", "category"]
    order_fields = ["id", "name", "price"]
    rows_name = "products"


def create_product(request):
    serializer = ProductSerializer(data=request.data)
    if not serializer.is_valid():
        return Response.validation_error(serializer.errors)

    return Response(serializer.validated_data, status_code=201, status="created", message="Created")


def delete_product(product):
    if product is None:
        raise NotFoundError(message="Product not found")
```

## Export Summary

Common imports:

```python
from morest.api import Response
from morest.authentication import BearerTokenAuthentication, JWTAuthentication, get_jwt_manager
from morest.core import JWTManager, JWTPair, docs, get_queryset, search_in_queryset, MorestJSONEncoder, presettings
from morest.errors import *
from morest.utils import PaginationSerializer, SearchSerializer, OrderSerializer, PaginationSearchSerializer
from morest.views import ListFilterView, AdminFormView, RefreshTokenView
```
