Debian Codegraph @

allauth/headless/spec/internal/schema.py

raw
1 from __future__ import annotations
2
3 from pathlib import Path
4
5 from django.urls import reverse
6 from django.urls.exceptions import Resolver404
7
8 from allauth.account import app_settings as account_settings
9 from allauth.account.internal.flows.signup import base_signup_form_class
10 from allauth.core.internal.urlkit import script_aware_resolve
11 from allauth.headless import app_settings
12 from allauth.headless.adapter import get_adapter
13 from allauth.headless.spec.internal.openapikit import spec_for_dataclass, spec_for_field
14
15
16 def get_schema() -> dict:
17 import yaml
18
19 path = Path(__file__).parent.parent / "doc/openapi.yaml"
20 with open(path, "rb") as f:
21 spec = yaml.safe_load(f)
22
23 path = Path(__file__).parent.parent / "doc/description.md"
24 with open(path, "rb") as f:
25 description = f.read().decode("utf8")
26
27 spec["info"]["description"] = description
28
29 specify_user(spec)
30 chroot(spec)
31 pin_client(spec)
32 drop_unused_client_parameter(spec)
33 used_tags = drop_unused_paths(spec)
34 drop_unused_tags(spec, used_tags)
35 drop_unused_tag_groups(spec, used_tags)
36 specify_signup_fields(spec)
37 specify_custom_signup_form(spec)
38 return spec
39
40
41 def chroot(spec: dict) -> None:
42 url = reverse("headless:openapi_yaml")
43 root = url.rpartition("/")[0]
44 paths = spec["paths"].items()
45 spec["paths"] = {}
46 for path, path_spec in paths:
47 new_path = path.replace("/_allauth", root)
48 spec["paths"][new_path] = path_spec
49
50
51 def pin_client(spec: dict) -> None:
52 if len(app_settings.CLIENTS) != 1:
53 return
54
55 processed_paths = {}
56 client_value = app_settings.CLIENTS[0]
57 http_methods = [
58 "get",
59 "post",
60 "put",
61 "delete",
62 "options",
63 "head",
64 "patch",
65 "trace",
66 ]
67
68 def remove_client_param(parameters: list) -> list | None:
69 filtered = [
70 p
71 for p in parameters
72 if not (
73 isinstance(p, dict)
74 and p.get("$ref") == "#/components/parameters/Client"
75 )
76 ]
77 return filtered or None
78
79 for path_key, path_item in spec["paths"].items():
80 current_path_item = dict(path_item)
81 processed_path_key = path_key.replace("{client}", client_value)
82
83 if "parameters" in current_path_item:
84 new_params = remove_client_param(current_path_item["parameters"])
85 if new_params:
86 current_path_item["parameters"] = new_params
87 else:
88 current_path_item.pop("parameters")
89
90 for method_name in http_methods:
91 if method_name in current_path_item:
92 operation_item = current_path_item[method_name]
93 if isinstance(operation_item, dict) and "parameters" in operation_item:
94 new_params = remove_client_param(operation_item["parameters"])
95 if new_params:
96 operation_item["parameters"] = new_params
97 else:
98 operation_item.pop("parameters")
99
100 processed_paths[processed_path_key] = current_path_item
101
102 spec["paths"] = processed_paths
103
104
105 def drop_unused_client_parameter(spec: dict) -> None:
106 if len(app_settings.CLIENTS) != 1:
107 return
108
109 if components := spec.get("components"):
110 if parameters := components.get("parameters"):
111 parameters.pop("Client", None)
112
113
114 def drop_unused_paths(spec: dict) -> set:
115 paths = spec["paths"]
116 used_tags = set()
117 for path, path_spec in list(paths.items()):
118 found_path = False
119 for client in app_settings.CLIENTS:
120 try:
121 script_aware_resolve(path.replace("{client}", client))
122 found_path = True
123 break
124 except Resolver404:
125 pass
126 if found_path:
127 for method, method_spec in path_spec.items():
128 used_tags.update(method_spec["tags"])
129 else:
130 paths.pop(path)
131 return used_tags
132
133
134 def drop_unused_tags(spec: dict, used_tags: set) -> None:
135 tags = spec["tags"]
136 spec["tags"] = []
137 for tag in tags:
138 if tag["name"] not in used_tags:
139 continue
140 spec["tags"].append(tag)
141
142
143 def drop_unused_tag_groups(spec: dict, used_tags: set) -> None:
144 tag_groups = spec["x-tagGroups"]
145 spec["x-tagGroups"] = []
146 for tag_group in tag_groups:
147 if any([t in used_tags for t in tag_group["tags"]]):
148 spec["x-tagGroups"].append(tag_group)
149
150
151 def specify_signup_fields(spec: dict) -> None:
152 base_signup = spec["components"]["schemas"]["BaseSignup"]
153 signup = spec["components"]["schemas"]["Signup"]
154 properties = base_signup["properties"]
155 required_fields = []
156 for field_name in ("email", "phone", "username"):
157 field = account_settings.SIGNUP_FIELDS.get(field_name)
158 if not field:
159 properties.pop(field_name)
160 elif field["required"]:
161 required_fields.append(field_name)
162 base_signup["required"] = required_fields
163 password_field = account_settings.SIGNUP_FIELDS.get("password1")
164 if not password_field:
165 signup["allOf"] = signup["allOf"][:1]
166 elif not password_field["required"]:
167 signup["allOf"][1]["required"].remove("password")
168
169
170 def specify_custom_signup_form(spec: dict) -> None:
171 form_class = base_signup_form_class()
172 base_signup = spec["components"]["schemas"]["BaseSignup"]
173 for field_name, field in form_class.base_fields.items():
174 is_required = hasattr(field, "required") and field.required
175 field_spec = spec_for_field(field)
176 if is_required:
177 base_signup["required"].append(field_name)
178 base_signup["properties"][field_name] = field_spec
179
180
181 def specify_user(spec: dict) -> None:
182 dc = get_adapter().get_user_dataclass()
183 schema, example = spec_for_dataclass(dc)
184 spec["components"]["schemas"]["User"] = schema
185 example_value = spec["components"]["examples"]["User"]["value"]
186 example_value.clear()
187 example_value.update(example)