authentik.admin.files.backends.base
1import mimetypes 2from collections.abc import Callable, Generator, Iterator 3from contextvars import ContextVar 4from typing import cast 5 6from django.core.cache import cache 7from django.http.request import HttpRequest 8from structlog.stdlib import get_logger 9 10from authentik.admin.files.usage import FileUsage 11 12CACHE_PREFIX = "goauthentik.io/admin/files" 13LOGGER = get_logger() 14 15# Theme variable placeholder for theme-specific files like logo-%(theme)s.png 16THEME_VARIABLE = "%(theme)s" 17 18# Cached URLs that FileManager.prefetch_urls() read in one query, by cache key 19PREFETCHED_URLS = ContextVar[dict[str, str] | None]("authentik_files_prefetched_urls", default=None) 20 21 22def get_content_type(name: str) -> str: 23 """Get MIME type for a file based on its extension.""" 24 content_type, _ = mimetypes.guess_type(name) 25 return content_type or "application/octet-stream" 26 27 28def get_valid_themes() -> list[str]: 29 """Get valid themes that can be substituted for %(theme)s.""" 30 from authentik.brands.api import Themes 31 32 return [t.value for t in Themes if t != Themes.AUTOMATIC] 33 34 35def has_theme_variable(name: str) -> bool: 36 """Check if filename contains %(theme)s variable.""" 37 return THEME_VARIABLE in name 38 39 40def substitute_theme(name: str, theme: str) -> str: 41 """Replace %(theme)s with the given theme.""" 42 return name.replace(THEME_VARIABLE, theme) 43 44 45class Backend: 46 """ 47 Base class for file storage backends. 48 49 Class attributes: 50 allowed_usages: List of usages that can be used with this backend 51 """ 52 53 allowed_usages: list[FileUsage] 54 55 def __init__(self, usage: FileUsage): 56 """ 57 Initialize backend for the given usage type. 58 59 Args: 60 usage: FileUsage type enum value 61 """ 62 self.usage = usage 63 LOGGER.debug( 64 "Initializing storage backend", 65 backend=self.__class__.__name__, 66 usage=usage.value, 67 ) 68 69 def supports_file(self, name: str) -> bool: 70 """ 71 Check if this backend can handle the given file path. 72 73 Args: 74 name: File path to check 75 76 Returns: 77 True if this backend supports this file path 78 """ 79 raise NotImplementedError 80 81 def list_files(self) -> Generator[str]: 82 """ 83 List all files stored in this backend. 84 85 Yields: 86 Relative file paths 87 """ 88 raise NotImplementedError 89 90 def file_url( 91 self, 92 name: str, 93 request: HttpRequest | None = None, 94 use_cache: bool = True, 95 ) -> str: 96 """ 97 Get URL for accessing the file. 98 99 Args: 100 file_path: Relative file path 101 request: Optional Django HttpRequest for fully qualified URL building 102 use_cache: whether to retrieve the URL from cache 103 104 Returns: 105 URL to access the file (may be relative or absolute depending on backend) 106 """ 107 raise NotImplementedError 108 109 def themed_urls( 110 self, 111 name: str, 112 request: HttpRequest | None = None, 113 use_cache: bool = True, 114 ) -> dict[str, str] | None: 115 """ 116 Get URLs for each theme variant when filename contains %(theme)s. 117 118 Args: 119 name: File path potentially containing %(theme)s 120 request: Optional Django HttpRequest for URL building 121 122 Returns: 123 Dict mapping theme to URL if %(theme)s present, None otherwise 124 """ 125 if not has_theme_variable(name): 126 return None 127 128 return { 129 theme: self.file_url(substitute_theme(name, theme), request, use_cache=use_cache) 130 for theme in get_valid_themes() 131 } 132 133 134class ManageableBackend(Backend): 135 """ 136 Base class for manageable file storage backends. 137 138 Class attributes: 139 name: Canonical name of the storage backend, for use in configuration. 140 """ 141 142 name: str 143 144 @property 145 def manageable(self) -> bool: 146 """ 147 Whether this backend can actually be used for management. 148 149 Used only for management check, not for created the backend 150 """ 151 raise NotImplementedError 152 153 def save_file(self, name: str, content: bytes) -> None: 154 """ 155 Save file content to storage. 156 157 Args: 158 file_path: Relative file path 159 content: File content as bytes 160 """ 161 raise NotImplementedError 162 163 def save_file_stream(self, name: str) -> Iterator: 164 """ 165 Context manager for streaming file writes. 166 167 Args: 168 file_path: Relative file path 169 170 Returns: 171 Context manager that yields a writable file-like object 172 173 FileUsage: 174 with backend.save_file_stream("output.csv") as f: 175 f.write(b"data...") 176 """ 177 raise NotImplementedError 178 179 def delete_file(self, name: str) -> None: 180 """ 181 Delete file from storage. 182 183 Args: 184 file_path: Relative file path 185 """ 186 raise NotImplementedError 187 188 def file_exists(self, name: str) -> bool: 189 """ 190 Check if a file exists. 191 192 Args: 193 file_path: Relative file path 194 195 Returns: 196 True if file exists, False otherwise 197 """ 198 raise NotImplementedError 199 200 def cache_key(self, name: str, request: HttpRequest | None) -> str: 201 request_key = "None" 202 if request is not None: 203 request_key = f"{request.build_absolute_uri('/')}" 204 return f"{CACHE_PREFIX}/{self.name}/{self.usage}/{request_key}/{name}" 205 206 def _cache_get_or_set( 207 self, 208 name: str, 209 request: HttpRequest | None, 210 default: Callable[[str, HttpRequest | None], str], 211 timeout: int, 212 ) -> str: 213 timeout_ignore = 60 214 timeout = int(timeout * 0.67) 215 if timeout < timeout_ignore: 216 timeout = 0 217 218 cache_key = self.cache_key(name, request) 219 prefetched = PREFETCHED_URLS.get() 220 if prefetched is not None and cache_key in prefetched: 221 return prefetched[cache_key] 222 return cast(str, cache.get_or_set(cache_key, lambda: default(name, request), timeout))
23def get_content_type(name: str) -> str: 24 """Get MIME type for a file based on its extension.""" 25 content_type, _ = mimetypes.guess_type(name) 26 return content_type or "application/octet-stream"
Get MIME type for a file based on its extension.
29def get_valid_themes() -> list[str]: 30 """Get valid themes that can be substituted for %(theme)s.""" 31 from authentik.brands.api import Themes 32 33 return [t.value for t in Themes if t != Themes.AUTOMATIC]
Get valid themes that can be substituted for %(theme)s.
36def has_theme_variable(name: str) -> bool: 37 """Check if filename contains %(theme)s variable.""" 38 return THEME_VARIABLE in name
Check if filename contains %(theme)s variable.
41def substitute_theme(name: str, theme: str) -> str: 42 """Replace %(theme)s with the given theme.""" 43 return name.replace(THEME_VARIABLE, theme)
Replace %(theme)s with the given theme.
46class Backend: 47 """ 48 Base class for file storage backends. 49 50 Class attributes: 51 allowed_usages: List of usages that can be used with this backend 52 """ 53 54 allowed_usages: list[FileUsage] 55 56 def __init__(self, usage: FileUsage): 57 """ 58 Initialize backend for the given usage type. 59 60 Args: 61 usage: FileUsage type enum value 62 """ 63 self.usage = usage 64 LOGGER.debug( 65 "Initializing storage backend", 66 backend=self.__class__.__name__, 67 usage=usage.value, 68 ) 69 70 def supports_file(self, name: str) -> bool: 71 """ 72 Check if this backend can handle the given file path. 73 74 Args: 75 name: File path to check 76 77 Returns: 78 True if this backend supports this file path 79 """ 80 raise NotImplementedError 81 82 def list_files(self) -> Generator[str]: 83 """ 84 List all files stored in this backend. 85 86 Yields: 87 Relative file paths 88 """ 89 raise NotImplementedError 90 91 def file_url( 92 self, 93 name: str, 94 request: HttpRequest | None = None, 95 use_cache: bool = True, 96 ) -> str: 97 """ 98 Get URL for accessing the file. 99 100 Args: 101 file_path: Relative file path 102 request: Optional Django HttpRequest for fully qualified URL building 103 use_cache: whether to retrieve the URL from cache 104 105 Returns: 106 URL to access the file (may be relative or absolute depending on backend) 107 """ 108 raise NotImplementedError 109 110 def themed_urls( 111 self, 112 name: str, 113 request: HttpRequest | None = None, 114 use_cache: bool = True, 115 ) -> dict[str, str] | None: 116 """ 117 Get URLs for each theme variant when filename contains %(theme)s. 118 119 Args: 120 name: File path potentially containing %(theme)s 121 request: Optional Django HttpRequest for URL building 122 123 Returns: 124 Dict mapping theme to URL if %(theme)s present, None otherwise 125 """ 126 if not has_theme_variable(name): 127 return None 128 129 return { 130 theme: self.file_url(substitute_theme(name, theme), request, use_cache=use_cache) 131 for theme in get_valid_themes() 132 }
Base class for file storage backends.
Class attributes: allowed_usages: List of usages that can be used with this backend
56 def __init__(self, usage: FileUsage): 57 """ 58 Initialize backend for the given usage type. 59 60 Args: 61 usage: FileUsage type enum value 62 """ 63 self.usage = usage 64 LOGGER.debug( 65 "Initializing storage backend", 66 backend=self.__class__.__name__, 67 usage=usage.value, 68 )
Initialize backend for the given usage type.
Args: usage: FileUsage type enum value
70 def supports_file(self, name: str) -> bool: 71 """ 72 Check if this backend can handle the given file path. 73 74 Args: 75 name: File path to check 76 77 Returns: 78 True if this backend supports this file path 79 """ 80 raise NotImplementedError
Check if this backend can handle the given file path.
Args: name: File path to check
Returns: True if this backend supports this file path
82 def list_files(self) -> Generator[str]: 83 """ 84 List all files stored in this backend. 85 86 Yields: 87 Relative file paths 88 """ 89 raise NotImplementedError
List all files stored in this backend.
Yields: Relative file paths
91 def file_url( 92 self, 93 name: str, 94 request: HttpRequest | None = None, 95 use_cache: bool = True, 96 ) -> str: 97 """ 98 Get URL for accessing the file. 99 100 Args: 101 file_path: Relative file path 102 request: Optional Django HttpRequest for fully qualified URL building 103 use_cache: whether to retrieve the URL from cache 104 105 Returns: 106 URL to access the file (may be relative or absolute depending on backend) 107 """ 108 raise NotImplementedError
Get URL for accessing the file.
Args: file_path: Relative file path request: Optional Django HttpRequest for fully qualified URL building use_cache: whether to retrieve the URL from cache
Returns: URL to access the file (may be relative or absolute depending on backend)
110 def themed_urls( 111 self, 112 name: str, 113 request: HttpRequest | None = None, 114 use_cache: bool = True, 115 ) -> dict[str, str] | None: 116 """ 117 Get URLs for each theme variant when filename contains %(theme)s. 118 119 Args: 120 name: File path potentially containing %(theme)s 121 request: Optional Django HttpRequest for URL building 122 123 Returns: 124 Dict mapping theme to URL if %(theme)s present, None otherwise 125 """ 126 if not has_theme_variable(name): 127 return None 128 129 return { 130 theme: self.file_url(substitute_theme(name, theme), request, use_cache=use_cache) 131 for theme in get_valid_themes() 132 }
Get URLs for each theme variant when filename contains %(theme)s.
Args: name: File path potentially containing %(theme)s request: Optional Django HttpRequest for URL building
Returns: Dict mapping theme to URL if %(theme)s present, None otherwise
135class ManageableBackend(Backend): 136 """ 137 Base class for manageable file storage backends. 138 139 Class attributes: 140 name: Canonical name of the storage backend, for use in configuration. 141 """ 142 143 name: str 144 145 @property 146 def manageable(self) -> bool: 147 """ 148 Whether this backend can actually be used for management. 149 150 Used only for management check, not for created the backend 151 """ 152 raise NotImplementedError 153 154 def save_file(self, name: str, content: bytes) -> None: 155 """ 156 Save file content to storage. 157 158 Args: 159 file_path: Relative file path 160 content: File content as bytes 161 """ 162 raise NotImplementedError 163 164 def save_file_stream(self, name: str) -> Iterator: 165 """ 166 Context manager for streaming file writes. 167 168 Args: 169 file_path: Relative file path 170 171 Returns: 172 Context manager that yields a writable file-like object 173 174 FileUsage: 175 with backend.save_file_stream("output.csv") as f: 176 f.write(b"data...") 177 """ 178 raise NotImplementedError 179 180 def delete_file(self, name: str) -> None: 181 """ 182 Delete file from storage. 183 184 Args: 185 file_path: Relative file path 186 """ 187 raise NotImplementedError 188 189 def file_exists(self, name: str) -> bool: 190 """ 191 Check if a file exists. 192 193 Args: 194 file_path: Relative file path 195 196 Returns: 197 True if file exists, False otherwise 198 """ 199 raise NotImplementedError 200 201 def cache_key(self, name: str, request: HttpRequest | None) -> str: 202 request_key = "None" 203 if request is not None: 204 request_key = f"{request.build_absolute_uri('/')}" 205 return f"{CACHE_PREFIX}/{self.name}/{self.usage}/{request_key}/{name}" 206 207 def _cache_get_or_set( 208 self, 209 name: str, 210 request: HttpRequest | None, 211 default: Callable[[str, HttpRequest | None], str], 212 timeout: int, 213 ) -> str: 214 timeout_ignore = 60 215 timeout = int(timeout * 0.67) 216 if timeout < timeout_ignore: 217 timeout = 0 218 219 cache_key = self.cache_key(name, request) 220 prefetched = PREFETCHED_URLS.get() 221 if prefetched is not None and cache_key in prefetched: 222 return prefetched[cache_key] 223 return cast(str, cache.get_or_set(cache_key, lambda: default(name, request), timeout))
Base class for manageable file storage backends.
Class attributes: name: Canonical name of the storage backend, for use in configuration.
145 @property 146 def manageable(self) -> bool: 147 """ 148 Whether this backend can actually be used for management. 149 150 Used only for management check, not for created the backend 151 """ 152 raise NotImplementedError
Whether this backend can actually be used for management.
Used only for management check, not for created the backend
154 def save_file(self, name: str, content: bytes) -> None: 155 """ 156 Save file content to storage. 157 158 Args: 159 file_path: Relative file path 160 content: File content as bytes 161 """ 162 raise NotImplementedError
Save file content to storage.
Args: file_path: Relative file path content: File content as bytes
164 def save_file_stream(self, name: str) -> Iterator: 165 """ 166 Context manager for streaming file writes. 167 168 Args: 169 file_path: Relative file path 170 171 Returns: 172 Context manager that yields a writable file-like object 173 174 FileUsage: 175 with backend.save_file_stream("output.csv") as f: 176 f.write(b"data...") 177 """ 178 raise NotImplementedError
Context manager for streaming file writes.
Args: file_path: Relative file path
Returns: Context manager that yields a writable file-like object
FileUsage: with backend.save_file_stream("output.csv") as f: f.write(b"data...")
180 def delete_file(self, name: str) -> None: 181 """ 182 Delete file from storage. 183 184 Args: 185 file_path: Relative file path 186 """ 187 raise NotImplementedError
Delete file from storage.
Args: file_path: Relative file path
189 def file_exists(self, name: str) -> bool: 190 """ 191 Check if a file exists. 192 193 Args: 194 file_path: Relative file path 195 196 Returns: 197 True if file exists, False otherwise 198 """ 199 raise NotImplementedError
Check if a file exists.
Args: file_path: Relative file path
Returns: True if file exists, False otherwise