File: exceptions.py

package info (click to toggle)
python-djangorestframework-simplejwt 5.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 956 kB
  • sloc: python: 3,783; makefile: 213; javascript: 40; sh: 6
file content (56 lines) | stat: -rw-r--r-- 1,300 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from typing import Any, Optional, Union

from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions, status


class TokenError(Exception):
    pass


class ExpiredTokenError(TokenError):
    pass


class TokenBackendError(Exception):
    pass


class TokenBackendExpiredToken(TokenBackendError):
    pass


class DetailDictMixin:
    default_detail: str
    default_code: str

    def __init__(
        self,
        detail: Union[dict[str, Any], str, None] = None,
        code: Optional[str] = None,
    ) -> None:
        """
        Builds a detail dictionary for the error to give more information to API
        users.
        """
        detail_dict = {"detail": self.default_detail, "code": self.default_code}

        if isinstance(detail, dict):
            detail_dict.update(detail)
        elif detail is not None:
            detail_dict["detail"] = detail

        if code is not None:
            detail_dict["code"] = code

        super().__init__(detail_dict)  # type: ignore


class AuthenticationFailed(DetailDictMixin, exceptions.AuthenticationFailed):
    pass


class InvalidToken(AuthenticationFailed):
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = _("Token is invalid or expired")
    default_code = "token_not_valid"