authentik.sources.telegram.models

Telegram source

  1"""Telegram source"""
  2
  3from typing import Any
  4from urllib.parse import urlencode
  5
  6from django.db import models
  7from django.http import HttpRequest
  8from django.templatetags.static import static
  9from django.urls import reverse
 10from django.utils.translation import gettext_lazy as _
 11from rest_framework.serializers import BaseSerializer, Serializer
 12
 13from authentik.core.models import (
 14    GroupSourceConnection,
 15    PropertyMapping,
 16    Source,
 17    UserSourceConnection,
 18)
 19from authentik.core.types import UILoginButton, UserSettingSerializer
 20from authentik.flows.challenge import RedirectChallenge
 21from authentik.flows.models import Flow
 22
 23
 24class TelegramSource(Source):
 25    """Log in with Telegram."""
 26
 27    bot_username = models.TextField(help_text=_("Telegram bot username"))
 28    bot_token = models.TextField(help_text=_("Telegram bot token"))
 29
 30    request_message_access = models.BooleanField(
 31        default=False, help_text=_("Request access to send messages from your bot.")
 32    )
 33
 34    pre_authentication_flow = models.ForeignKey(
 35        Flow,
 36        on_delete=models.CASCADE,
 37        help_text=_("Flow used before authentication."),
 38        related_name="telegram_source_pre_authentication",
 39    )
 40
 41    @property
 42    def component(self) -> str:
 43        return "ak-source-telegram-form"
 44
 45    @property
 46    def icon_url(self) -> str | None:
 47        icon = super().icon_url
 48        if not icon:
 49            icon = static("authentik/sources/telegram/light.svg")
 50        return icon
 51
 52    @property
 53    def serializer(self) -> type[BaseSerializer]:
 54        from authentik.sources.telegram.api.source import TelegramSourceSerializer
 55
 56        return TelegramSourceSerializer
 57
 58    def ui_login_button(self, request: HttpRequest) -> UILoginButton:
 59        return UILoginButton(
 60            challenge=RedirectChallenge(
 61                data={
 62                    "to": reverse(
 63                        "authentik_sources_telegram:start",
 64                        kwargs={"source_slug": self.slug},
 65                    ),
 66                }
 67            ),
 68            name=self.name,
 69            icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url,
 70            icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False),
 71            promoted=self.promoted,
 72        )
 73
 74    def ui_user_settings(self) -> UserSettingSerializer | None:
 75        return UserSettingSerializer(
 76            data={
 77                "title": self.name,
 78                "component": "ak-user-settings-source-telegram",
 79                "icon_url": self.icon_url,
 80                "icon_themed_urls": self.icon_themed_urls,
 81                "configure_url": urlencode(
 82                    {
 83                        "bot_username": self.bot_username,
 84                        "request_message_access": str(self.request_message_access),
 85                    }
 86                ),
 87            }
 88        )
 89
 90    @property
 91    def property_mapping_type(self) -> type[PropertyMapping]:
 92        return TelegramSourcePropertyMapping
 93
 94    def get_base_user_properties(
 95        self, info: dict[str, Any] | None = None, **kwargs
 96    ) -> dict[str, Any | dict[str, Any]]:
 97        info = info or {}
 98        name = info.get("first_name", "")
 99        if "last_name" in info:
100            name += " " + info["last_name"]
101        return {
102            "username": info.get("username", None),
103            "email": None,
104            "name": name if name else None,
105        }
106
107    def get_base_group_properties(self, group_id: str, **kwargs):
108        return {
109            "name": group_id,
110        }
111
112    class Meta:
113        verbose_name = _("Telegram Source")
114        verbose_name_plural = _("Telegram Sources")
115
116
117class TelegramSourcePropertyMapping(PropertyMapping):
118    """Map Telegram properties to User or Group object attributes"""
119
120    expression_allowed_types = [dict]
121
122    @property
123    def component(self) -> str:
124        return "ak-property-mapping-source-telegram-form"
125
126    @property
127    def serializer(self) -> type[Serializer]:
128        from authentik.sources.telegram.api.property_mappings import (
129            TelegramSourcePropertyMappingSerializer,
130        )
131
132        return TelegramSourcePropertyMappingSerializer
133
134    class Meta:
135        verbose_name = _("Telegram Source Property Mapping")
136        verbose_name_plural = _("Telegram Source Property Mappings")
137
138
139class UserTelegramSourceConnection(UserSourceConnection):
140    """Connect user and Telegram source"""
141
142    @property
143    def serializer(self) -> type[Serializer]:
144        from authentik.sources.telegram.api.source_connection import (
145            UserTelegramSourceConnectionSerializer,
146        )
147
148        return UserTelegramSourceConnectionSerializer
149
150    class Meta:
151        verbose_name = _("User Telegram Source Connection")
152        verbose_name_plural = _("User Telegram Source Connections")
153
154
155class GroupTelegramSourceConnection(GroupSourceConnection):
156    """Group-source connection for Telegram"""
157
158    @property
159    def serializer(self) -> type[Serializer]:
160        from authentik.sources.telegram.api.source_connection import (
161            GroupTelegramSourceConnectionSerializer,
162        )
163
164        return GroupTelegramSourceConnectionSerializer
165
166    class Meta:
167        verbose_name = _("Group Telegram Source Connection")
168        verbose_name_plural = _("Group Telegram Source Connections")
class TelegramSource(authentik.core.models.Source):
 25class TelegramSource(Source):
 26    """Log in with Telegram."""
 27
 28    bot_username = models.TextField(help_text=_("Telegram bot username"))
 29    bot_token = models.TextField(help_text=_("Telegram bot token"))
 30
 31    request_message_access = models.BooleanField(
 32        default=False, help_text=_("Request access to send messages from your bot.")
 33    )
 34
 35    pre_authentication_flow = models.ForeignKey(
 36        Flow,
 37        on_delete=models.CASCADE,
 38        help_text=_("Flow used before authentication."),
 39        related_name="telegram_source_pre_authentication",
 40    )
 41
 42    @property
 43    def component(self) -> str:
 44        return "ak-source-telegram-form"
 45
 46    @property
 47    def icon_url(self) -> str | None:
 48        icon = super().icon_url
 49        if not icon:
 50            icon = static("authentik/sources/telegram/light.svg")
 51        return icon
 52
 53    @property
 54    def serializer(self) -> type[BaseSerializer]:
 55        from authentik.sources.telegram.api.source import TelegramSourceSerializer
 56
 57        return TelegramSourceSerializer
 58
 59    def ui_login_button(self, request: HttpRequest) -> UILoginButton:
 60        return UILoginButton(
 61            challenge=RedirectChallenge(
 62                data={
 63                    "to": reverse(
 64                        "authentik_sources_telegram:start",
 65                        kwargs={"source_slug": self.slug},
 66                    ),
 67                }
 68            ),
 69            name=self.name,
 70            icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url,
 71            icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False),
 72            promoted=self.promoted,
 73        )
 74
 75    def ui_user_settings(self) -> UserSettingSerializer | None:
 76        return UserSettingSerializer(
 77            data={
 78                "title": self.name,
 79                "component": "ak-user-settings-source-telegram",
 80                "icon_url": self.icon_url,
 81                "icon_themed_urls": self.icon_themed_urls,
 82                "configure_url": urlencode(
 83                    {
 84                        "bot_username": self.bot_username,
 85                        "request_message_access": str(self.request_message_access),
 86                    }
 87                ),
 88            }
 89        )
 90
 91    @property
 92    def property_mapping_type(self) -> type[PropertyMapping]:
 93        return TelegramSourcePropertyMapping
 94
 95    def get_base_user_properties(
 96        self, info: dict[str, Any] | None = None, **kwargs
 97    ) -> dict[str, Any | dict[str, Any]]:
 98        info = info or {}
 99        name = info.get("first_name", "")
100        if "last_name" in info:
101            name += " " + info["last_name"]
102        return {
103            "username": info.get("username", None),
104            "email": None,
105            "name": name if name else None,
106        }
107
108    def get_base_group_properties(self, group_id: str, **kwargs):
109        return {
110            "name": group_id,
111        }
112
113    class Meta:
114        verbose_name = _("Telegram Source")
115        verbose_name_plural = _("Telegram Sources")

Log in with Telegram.

def bot_username(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def bot_token(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def request_message_access(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

pre_authentication_flow

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

component: str
42    @property
43    def component(self) -> str:
44        return "ak-source-telegram-form"

Return component used to edit this object

icon_url: str | None
46    @property
47    def icon_url(self) -> str | None:
48        icon = super().icon_url
49        if not icon:
50            icon = static("authentik/sources/telegram/light.svg")
51        return icon

Get the URL to the source icon

serializer: type[rest_framework.serializers.BaseSerializer]
53    @property
54    def serializer(self) -> type[BaseSerializer]:
55        from authentik.sources.telegram.api.source import TelegramSourceSerializer
56
57        return TelegramSourceSerializer

Get serializer for this model

def ui_login_button( self, request: django.http.request.HttpRequest) -> authentik.core.types.UILoginButton:
59    def ui_login_button(self, request: HttpRequest) -> UILoginButton:
60        return UILoginButton(
61            challenge=RedirectChallenge(
62                data={
63                    "to": reverse(
64                        "authentik_sources_telegram:start",
65                        kwargs={"source_slug": self.slug},
66                    ),
67                }
68            ),
69            name=self.name,
70            icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url,
71            icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False),
72            promoted=self.promoted,
73        )

If source uses a http-based flow, return UI Information about the login button. If source doesn't use http-based flow, return None.

def ui_user_settings(self) -> authentik.core.types.UserSettingSerializer | None:
75    def ui_user_settings(self) -> UserSettingSerializer | None:
76        return UserSettingSerializer(
77            data={
78                "title": self.name,
79                "component": "ak-user-settings-source-telegram",
80                "icon_url": self.icon_url,
81                "icon_themed_urls": self.icon_themed_urls,
82                "configure_url": urlencode(
83                    {
84                        "bot_username": self.bot_username,
85                        "request_message_access": str(self.request_message_access),
86                    }
87                ),
88            }
89        )

Entrypoint to integrate with User settings. Can either return None if no user settings are available, or UserSettingSerializer.

property_mapping_type: type[authentik.core.models.PropertyMapping]
91    @property
92    def property_mapping_type(self) -> type[PropertyMapping]:
93        return TelegramSourcePropertyMapping

Return property mapping type used by this object

def get_base_user_properties( self, info: dict[str, Any] | None = None, **kwargs) -> dict[str, typing.Any | dict[str, typing.Any]]:
 95    def get_base_user_properties(
 96        self, info: dict[str, Any] | None = None, **kwargs
 97    ) -> dict[str, Any | dict[str, Any]]:
 98        info = info or {}
 99        name = info.get("first_name", "")
100        if "last_name" in info:
101            name += " " + info["last_name"]
102        return {
103            "username": info.get("username", None),
104            "email": None,
105            "name": name if name else None,
106        }

Get base properties for a user to build final properties upon.

def get_base_group_properties(self, group_id: str, **kwargs):
108    def get_base_group_properties(self, group_id: str, **kwargs):
109        return {
110            "name": group_id,
111        }

Get base properties for a group to build final properties upon.

pre_authentication_flow_id
source_ptr_id
source_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class TelegramSource.DoesNotExist(authentik.core.models.Source.DoesNotExist):

The requested object does not exist

class TelegramSource.MultipleObjectsReturned(authentik.core.models.Source.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class TelegramSourcePropertyMapping(authentik.core.models.PropertyMapping):
118class TelegramSourcePropertyMapping(PropertyMapping):
119    """Map Telegram properties to User or Group object attributes"""
120
121    expression_allowed_types = [dict]
122
123    @property
124    def component(self) -> str:
125        return "ak-property-mapping-source-telegram-form"
126
127    @property
128    def serializer(self) -> type[Serializer]:
129        from authentik.sources.telegram.api.property_mappings import (
130            TelegramSourcePropertyMappingSerializer,
131        )
132
133        return TelegramSourcePropertyMappingSerializer
134
135    class Meta:
136        verbose_name = _("Telegram Source Property Mapping")
137        verbose_name_plural = _("Telegram Source Property Mappings")

Map Telegram properties to User or Group object attributes

expression_allowed_types = [<class 'dict'>]
component: str
123    @property
124    def component(self) -> str:
125        return "ak-property-mapping-source-telegram-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
127    @property
128    def serializer(self) -> type[Serializer]:
129        from authentik.sources.telegram.api.property_mappings import (
130            TelegramSourcePropertyMappingSerializer,
131        )
132
133        return TelegramSourcePropertyMappingSerializer

Get serializer for this model

propertymapping_ptr_id
propertymapping_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class TelegramSourcePropertyMapping.DoesNotExist(authentik.core.models.PropertyMapping.DoesNotExist):

The requested object does not exist

class TelegramSourcePropertyMapping.MultipleObjectsReturned(authentik.core.models.PropertyMapping.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class UserTelegramSourceConnection(authentik.core.models.UserSourceConnection):
140class UserTelegramSourceConnection(UserSourceConnection):
141    """Connect user and Telegram source"""
142
143    @property
144    def serializer(self) -> type[Serializer]:
145        from authentik.sources.telegram.api.source_connection import (
146            UserTelegramSourceConnectionSerializer,
147        )
148
149        return UserTelegramSourceConnectionSerializer
150
151    class Meta:
152        verbose_name = _("User Telegram Source Connection")
153        verbose_name_plural = _("User Telegram Source Connections")

Connect user and Telegram source

serializer: type[rest_framework.serializers.Serializer]
143    @property
144    def serializer(self) -> type[Serializer]:
145        from authentik.sources.telegram.api.source_connection import (
146            UserTelegramSourceConnectionSerializer,
147        )
148
149        return UserTelegramSourceConnectionSerializer

Get serializer for this model

usersourceconnection_ptr_id
usersourceconnection_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class UserTelegramSourceConnection.DoesNotExist(authentik.core.models.UserSourceConnection.DoesNotExist):

The requested object does not exist

class UserTelegramSourceConnection.MultipleObjectsReturned(authentik.core.models.UserSourceConnection.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class GroupTelegramSourceConnection(authentik.core.models.GroupSourceConnection):
156class GroupTelegramSourceConnection(GroupSourceConnection):
157    """Group-source connection for Telegram"""
158
159    @property
160    def serializer(self) -> type[Serializer]:
161        from authentik.sources.telegram.api.source_connection import (
162            GroupTelegramSourceConnectionSerializer,
163        )
164
165        return GroupTelegramSourceConnectionSerializer
166
167    class Meta:
168        verbose_name = _("Group Telegram Source Connection")
169        verbose_name_plural = _("Group Telegram Source Connections")

Group-source connection for Telegram

serializer: type[rest_framework.serializers.Serializer]
159    @property
160    def serializer(self) -> type[Serializer]:
161        from authentik.sources.telegram.api.source_connection import (
162            GroupTelegramSourceConnectionSerializer,
163        )
164
165        return GroupTelegramSourceConnectionSerializer

Get serializer for this model

groupsourceconnection_ptr_id
groupsourceconnection_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class GroupTelegramSourceConnection.DoesNotExist(authentik.core.models.GroupSourceConnection.DoesNotExist):

The requested object does not exist

class GroupTelegramSourceConnection.MultipleObjectsReturned(authentik.core.models.GroupSourceConnection.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.