bazaar-contrib-server-github 0.3.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ """Logging in to the server with a GitHub account, through the OAuth App set on
2
+ the login methods part of the settings page."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from contextlib import asynccontextmanager
7
+ lazy import asyncio
8
+ lazy import ssl
9
+ lazy from collections.abc import AsyncIterator
10
+ lazy from importlib.resources import files
11
+ lazy from pathlib import Path
12
+
13
+ from bazaar_contrib_server import SERVER
14
+ from bazaar_contrib_server_access import ACCESS
15
+ from bazaar_contrib_server_database import SERVER_DB, SERVER_SCHEMA
16
+ from bazaar_contrib_server_migrations import SERVER_MIGRATIONS
17
+ from bazaar_core import Context, Contrib
18
+ lazy import aiohttp
19
+
20
+ lazy from .client import GitHub
21
+ lazy from .method import GitHubLogin
22
+ lazy from .schema import MODULE
23
+ lazy from .settings import Settings
24
+
25
+ __all__ = ["github"]
26
+
27
+ SITE = "https://github.com"
28
+ API = "https://api.github.com"
29
+
30
+
31
+ @asynccontextmanager
32
+ async def _github(
33
+ ctx: Context,
34
+ *,
35
+ site: str = SITE,
36
+ api: str = API,
37
+ context: ssl.SSLContext | None = None,
38
+ ) -> AsyncIterator[None]:
39
+ server = ctx.accept(SERVER)
40
+ access = ctx.accept(ACCESS)
41
+ database = ctx.accept(SERVER_DB)
42
+ async with ctx.accept(SERVER_SCHEMA).register(MODULE):
43
+ resources = Path(str(files(__name__))) / "resources"
44
+ icon = await asyncio.to_thread(
45
+ (resources / "templates" / "github" / "github.svg").read_text,
46
+ encoding="utf-8",
47
+ )
48
+ pages = await server.pages("github", __name__)
49
+ verified = context or await asyncio.to_thread(ssl.create_default_context)
50
+ async with aiohttp.ClientSession(
51
+ connector=aiohttp.TCPConnector(ssl=verified)
52
+ ) as session:
53
+ login = GitHubLogin(access, database, GitHub(session, site, api), icon)
54
+ async with (
55
+ server.module(
56
+ "github",
57
+ ui=Settings(pages, access, database).app,
58
+ static=resources / "static",
59
+ locales=resources / "locales",
60
+ ),
61
+ access.method(login),
62
+ ):
63
+ yield
64
+
65
+
66
+ github = Contrib(
67
+ accepts=[SERVER, SERVER_DB, SERVER_SCHEMA, SERVER_MIGRATIONS, ACCESS],
68
+ lifespan=_github,
69
+ )
@@ -0,0 +1,145 @@
1
+ """GitHub as a login sees it: where a person approves the login, and what the
2
+ site answers for a code and its API for a token."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ lazy from typing import Any
8
+ lazy from urllib.parse import urlencode
9
+
10
+ lazy import aiohttp
11
+ lazy from bazaar_contrib_server_access import Refused, Unavailable
12
+
13
+ # the API version the answers below are read as
14
+ _API = {
15
+ "Accept": "application/vnd.github+json",
16
+ "X-GitHub-Api-Version": "2022-11-28",
17
+ }
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class Grant:
22
+ """What GitHub hands over for a code or a refresh token: the access token
23
+ and, when the app's tokens expire, the token that renews it."""
24
+
25
+ access: str
26
+ refresh: str | None
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class User:
31
+ id: str
32
+ login: str
33
+ # the profile's name, or the login when it has none
34
+ name: str
35
+ avatar: str | None
36
+
37
+
38
+ class GitHub:
39
+ """github.com and its API, at the addresses it is given."""
40
+
41
+ def __init__(self, session: aiohttp.ClientSession, site: str, api: str) -> None:
42
+ self._session = session
43
+ self._site = site
44
+ self._api = api
45
+
46
+ def authorize(
47
+ self, client_id: str, redirect_uri: str, state: str, challenge: str
48
+ ) -> str:
49
+ return f"{self._site}/login/oauth/authorize?" + urlencode(
50
+ {
51
+ "client_id": client_id,
52
+ "redirect_uri": redirect_uri,
53
+ "scope": "read:user user:email",
54
+ "state": state,
55
+ "code_challenge": challenge,
56
+ "code_challenge_method": "S256",
57
+ }
58
+ )
59
+
60
+ async def token(
61
+ self,
62
+ client_id: str,
63
+ client_secret: str,
64
+ code: str,
65
+ redirect_uri: str,
66
+ verifier: str,
67
+ ) -> Grant:
68
+ return await self._grant(
69
+ {
70
+ "client_id": client_id,
71
+ "client_secret": client_secret,
72
+ "code": code,
73
+ "redirect_uri": redirect_uri,
74
+ "code_verifier": verifier,
75
+ }
76
+ )
77
+
78
+ async def refresh(self, client_id: str, client_secret: str, refresh: str) -> Grant:
79
+ """A new access token, and a new refresh token in place of this one."""
80
+ return await self._grant(
81
+ {
82
+ "client_id": client_id,
83
+ "client_secret": client_secret,
84
+ "grant_type": "refresh_token",
85
+ "refresh_token": refresh,
86
+ }
87
+ )
88
+
89
+ async def _grant(self, data: dict[str, str]) -> Grant:
90
+ try:
91
+ async with self._session.post(
92
+ f"{self._site}/login/oauth/access_token",
93
+ data=data,
94
+ headers={"Accept": "application/json"},
95
+ ) as response:
96
+ if response.status >= 500:
97
+ raise Unavailable
98
+ answer = await response.json(content_type=None)
99
+ except aiohttp.ClientError, ValueError:
100
+ raise Unavailable from None
101
+ # what is wrong, used or expired is answered 200 with an error
102
+ access = answer.get("access_token") if isinstance(answer, dict) else None
103
+ if not isinstance(access, str) or not access:
104
+ raise Refused
105
+ refresh = answer.get("refresh_token")
106
+ return Grant(access, refresh if isinstance(refresh, str) and refresh else None)
107
+
108
+ async def user(self, token: str) -> User | None:
109
+ """Whom the token is for; nothing once it no longer holds."""
110
+ answer = await self._get("/user", token)
111
+ if answer is None:
112
+ return None
113
+ login = str(answer["login"])
114
+ return User(
115
+ id=str(answer["id"]),
116
+ login=login,
117
+ name=str(answer.get("name") or login),
118
+ avatar=answer.get("avatar_url") or None,
119
+ )
120
+
121
+ async def email(self, token: str) -> str | None:
122
+ """The primary address, once verified."""
123
+ answer = await self._get("/user/emails", token)
124
+ return next(
125
+ (
126
+ str(entry["email"])
127
+ for entry in answer or ()
128
+ if entry.get("primary") and entry.get("verified")
129
+ ),
130
+ None,
131
+ )
132
+
133
+ async def _get(self, path: str, token: str) -> Any:
134
+ try:
135
+ async with self._session.get(
136
+ f"{self._api}{path}",
137
+ headers=_API | {"Authorization": f"Bearer {token}"},
138
+ ) as response:
139
+ if response.status == 401:
140
+ return None
141
+ if response.status != 200:
142
+ raise Unavailable
143
+ return await response.json()
144
+ except aiohttp.ClientError, ValueError:
145
+ raise Unavailable from None
@@ -0,0 +1,261 @@
1
+ """Logging in with GitHub: setting off to approve on GitHub, coming back with a
2
+ code, the account each GitHub user logs in as, and asking GitHub again when a
3
+ session runs out."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ lazy import asyncio
9
+ lazy from collections.abc import Awaitable, Mapping
10
+ lazy from time import time_ns
11
+ lazy from typing import cast
12
+
13
+ from bazaar_contrib_http import redact
14
+ from starlette.applications import Starlette
15
+ from starlette.requests import Request
16
+ from starlette.responses import Response
17
+ from starlette.routing import Route
18
+ from starlette.types import ASGIApp
19
+ lazy from bazaar_contrib_server_access import (
20
+ Access,
21
+ Authorization,
22
+ Confirmed,
23
+ Refused,
24
+ Unavailable,
25
+ )
26
+ lazy from bazaar_contrib_storage import (
27
+ Column,
28
+ Compare,
29
+ Database,
30
+ Insert,
31
+ Select,
32
+ Session,
33
+ Update,
34
+ Value,
35
+ )
36
+
37
+ lazy from .client import GitHub, Grant, User
38
+ lazy from .settings import Configured, configured
39
+
40
+ KEY = "github"
41
+
42
+
43
+ @dataclass
44
+ class GitHubLogin:
45
+ access: Access
46
+ database: Database
47
+ github: GitHub
48
+ icon: str
49
+
50
+ app: ASGIApp = field(init=False)
51
+ # GitHub takes a refresh token back once it is used: the requests that
52
+ # find an account's access token out of date at the same time wait for one
53
+ # refresh between them
54
+ _refreshing: dict[str, asyncio.Future[str | None]] = field(
55
+ init=False, default_factory=dict
56
+ )
57
+
58
+ key = KEY
59
+ name = "github.name"
60
+ description = "github.description"
61
+ settings = "/ui/github/"
62
+
63
+ def __post_init__(self) -> None:
64
+ self.app = Starlette(
65
+ routes=[Route("/", self._start), Route("/callback", self._callback)]
66
+ )
67
+
68
+ async def ready(self) -> bool:
69
+ return await configured(self.database) is not None
70
+
71
+ async def roles(self) -> set[str]:
72
+ settings = await configured(self.database)
73
+ return (
74
+ {settings.default_role_id}
75
+ if settings is not None and settings.default_role_id is not None
76
+ else set()
77
+ )
78
+
79
+ async def renew(self, account_id: str) -> Confirmed | None:
80
+ held = await self._held(account_id)
81
+ settings = await configured(self.database)
82
+ if held is None or settings is None:
83
+ return None
84
+ user = await self.github.user(cast(str, held["token"]))
85
+ if user is None and held["refresh_token"] is not None:
86
+ token = await self._refreshed(
87
+ settings, account_id, cast(str, held["token"])
88
+ )
89
+ user = None if token is None else await self.github.user(token)
90
+ if user is None or user.id != held["github_id"]:
91
+ return None
92
+ await self.database.write(
93
+ lambda session: session.update(
94
+ Update(
95
+ table="github_accounts",
96
+ values={
97
+ "login": Value(value=user.login),
98
+ "name": Value(value=user.name),
99
+ "avatar_url": Value(value=user.avatar),
100
+ "updated_at_ms": Value(value=time_ns() // 1_000_000),
101
+ },
102
+ where=_equals("github_id", user.id),
103
+ )
104
+ )
105
+ )
106
+ return Confirmed(account_id, user.name, user.avatar, settings.session_minutes)
107
+
108
+ async def _held(self, account_id: str) -> Mapping[str, object] | None:
109
+ rows = await self.database.read(
110
+ lambda session: session.select(
111
+ Select(table="github_accounts", where=_equals("account_id", account_id))
112
+ )
113
+ )
114
+ return rows[0] if rows else None
115
+
116
+ def _refreshed(
117
+ self, settings: Configured, account_id: str, stale: str
118
+ ) -> Awaitable[str | None]:
119
+ """The access token in place of the stale one; nothing once GitHub
120
+ takes the authorization back."""
121
+ refreshing = self._refreshing.get(account_id)
122
+ if refreshing is None:
123
+ refreshing = self._refreshing[account_id] = asyncio.ensure_future(
124
+ self._refresh(settings, account_id, stale)
125
+ )
126
+ refreshing.add_done_callback(
127
+ lambda _: self._refreshing.pop(account_id, None)
128
+ )
129
+ # one waiting request given up leaves the refresh to the others
130
+ return asyncio.shield(refreshing)
131
+
132
+ async def _refresh(
133
+ self, settings: Configured, account_id: str, stale: str
134
+ ) -> str | None:
135
+ held = await self._held(account_id)
136
+ if held is None:
137
+ return None
138
+ # refreshed by a request before this one
139
+ if held["token"] != stale:
140
+ return cast(str, held["token"])
141
+ try:
142
+ grant = await self.github.refresh(
143
+ settings.client_id,
144
+ settings.client_secret,
145
+ cast(str, held["refresh_token"]),
146
+ )
147
+ except Refused:
148
+ return None
149
+ await self.database.write(
150
+ lambda session: session.update(
151
+ Update(
152
+ table="github_accounts",
153
+ values={
154
+ "token": Value(value=grant.access),
155
+ "refresh_token": Value(value=grant.refresh),
156
+ "updated_at_ms": Value(value=time_ns() // 1_000_000),
157
+ },
158
+ where=_equals("account_id", account_id),
159
+ )
160
+ )
161
+ )
162
+ return grant.access
163
+
164
+ async def _start(self, request: Request) -> Response:
165
+ async def authorize(authorization: Authorization) -> str:
166
+ settings = await configured(self.database)
167
+ if settings is None:
168
+ raise Unavailable
169
+ return self.github.authorize(
170
+ settings.client_id,
171
+ settings.redirect_uri,
172
+ authorization.state,
173
+ authorization.challenge,
174
+ )
175
+
176
+ return await self.access.start(request, KEY, authorize)
177
+
178
+ @redact("code", "state")
179
+ async def _callback(self, request: Request) -> Response:
180
+ return await self.access.finish(request, KEY, self._confirm)
181
+
182
+ async def _confirm(
183
+ self, authorization: Authorization, query: Mapping[str, str]
184
+ ) -> Confirmed:
185
+ # declined on GitHub, or nothing to redeem
186
+ code = query.get("code", "")
187
+ if "error" in query or not code:
188
+ raise Refused
189
+ settings = await configured(self.database)
190
+ if settings is None:
191
+ raise Unavailable
192
+ grant = await self.github.token(
193
+ settings.client_id,
194
+ settings.client_secret,
195
+ code,
196
+ settings.redirect_uri,
197
+ authorization.verifier,
198
+ )
199
+ user = await self.github.user(grant.access)
200
+ if user is None:
201
+ raise Refused
202
+ email = await self.github.email(grant.access)
203
+
204
+ async def remember(session: Session) -> str:
205
+ return await self._remember(session, settings, user, email, grant)
206
+
207
+ account_id = await self.database.transaction(remember)
208
+ return Confirmed(account_id, user.name, user.avatar, settings.session_minutes)
209
+
210
+ async def _remember(
211
+ self,
212
+ session: Session,
213
+ settings: Configured,
214
+ user: User,
215
+ email: str | None,
216
+ grant: Grant,
217
+ ) -> str:
218
+ """The account the GitHub user logs in as, made on the first login."""
219
+ now = time_ns() // 1_000_000
220
+ known = await session.select(
221
+ Select(table="github_accounts", where=_equals("github_id", user.id))
222
+ )
223
+ profile = {
224
+ "login": user.login,
225
+ "name": user.name,
226
+ "email": email,
227
+ "avatar_url": user.avatar,
228
+ "token": grant.access,
229
+ "refresh_token": grant.refresh,
230
+ "updated_at_ms": now,
231
+ }
232
+ if known:
233
+ await session.update(
234
+ Update(
235
+ table="github_accounts",
236
+ values={
237
+ name: Value(value=value) for name, value in profile.items()
238
+ },
239
+ where=_equals("github_id", user.id),
240
+ )
241
+ )
242
+ return cast(str, known[0]["account_id"])
243
+ account_id = await self.access.enroll(session, KEY, settings.default_role_id)
244
+ await session.insert(
245
+ Insert(
246
+ table="github_accounts",
247
+ rows=(
248
+ {
249
+ "github_id": user.id,
250
+ "account_id": account_id,
251
+ "created_at_ms": now,
252
+ }
253
+ | profile,
254
+ ),
255
+ )
256
+ )
257
+ return account_id
258
+
259
+
260
+ def _equals(column: str, value: str) -> Compare:
261
+ return Compare(left=Column(name=column), operator="=", right=Value(value=value))
@@ -0,0 +1,6 @@
1
+ # Third-party assets
2
+
3
+ ## Simple Icons 16.31.0
4
+ - Source: https://registry.npmjs.org/simple-icons/-/simple-icons-16.31.0.tgz (`icons/github.svg`)
5
+ - License: CC0-1.0; the GitHub mark is GitHub's
6
+ - Used in: `templates/github/github.svg`, the mark drawn on a dark tile
@@ -0,0 +1,20 @@
1
+ "github.name" = "GitHub"
2
+ "github.description" = "Log in with a GitHub account"
3
+ "github.client_id.hint" = "Copy it from the OAuth App's page"
4
+ "github.client_secret.hint" = "Generate one on the OAuth App's page"
5
+ "github.client_secret.kept" = "Set · leave empty to keep it"
6
+ "github.client_secret.show" = "Show or hide the Client Secret"
7
+ "github.role" = "Default role"
8
+ "github.role.global" = "The global default role ({{ role }})"
9
+ "github.role.none" = "The global default role (none yet)"
10
+ "github.minutes" = "Session length"
11
+ "github.minutes.same" = "As long as a password login ({{ minutes }})"
12
+ "github.minutes.unit" = "minutes"
13
+ "github.callback" = "Callback URL"
14
+ "github.callback.hint" = "On GitHub, create an app under Settings › Developer settings › OAuth Apps with the address above as its Authorization callback URL, then fill in its Client ID and a Client Secret generated there."
15
+ "github.copy" = "Copy"
16
+ "github.copied" = "Copied"
17
+ "github.offer" = "Once saved, the login page offers logging in with GitHub."
18
+ "github.offered" = "Offered on the login page"
19
+ "github.invalid" = "Not saved: check the required fields and the callback URL."
20
+ "github.save" = "Save"
@@ -0,0 +1,20 @@
1
+ "github.name" = "GitHub"
2
+ "github.description" = "用 GitHub 账号登录"
3
+ "github.client_id.hint" = "从 OAuth App 页面复制"
4
+ "github.client_secret.hint" = "在 OAuth App 页面生成后填入"
5
+ "github.client_secret.kept" = "已设置 · 留空保持不变"
6
+ "github.client_secret.show" = "显示或隐藏 Client Secret"
7
+ "github.role" = "默认角色"
8
+ "github.role.global" = "使用全局默认角色({{ role }})"
9
+ "github.role.none" = "使用全局默认角色(尚未设置)"
10
+ "github.minutes" = "会话时长"
11
+ "github.minutes.same" = "与账号密码登录相同({{ minutes }})"
12
+ "github.minutes.unit" = "分钟"
13
+ "github.callback" = "回调地址"
14
+ "github.callback.hint" = "在 GitHub 的 Settings › Developer settings › OAuth Apps 里新建应用,Authorization callback URL 填上面的回调地址;创建后把 Client ID 和生成的 Client Secret 填到这里。"
15
+ "github.copy" = "复制"
16
+ "github.copied" = "已复制"
17
+ "github.offer" = "保存后,登录页出现「用 GitHub 账号登录」。"
18
+ "github.offered" = "已出现在登录页"
19
+ "github.invalid" = "没有保存:请检查必填项和回调地址。"
20
+ "github.save" = "保存"
@@ -0,0 +1,26 @@
1
+ /* The GitHub login's settings, folded open under its row in the login methods part. */
2
+
3
+ body { background: transparent; }
4
+ [x-cloak] { display: none !important; }
5
+ .github { display: grid; gap: 18px; padding: 18px; }
6
+ .fields { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
7
+ .fields > * { min-width: 0; }
8
+ .fields .wide { grid-column: 1 / -1; }
9
+ .req { color: var(--crimson); margin-left: 3px; }
10
+ input.input { width: 100%; font: inherit; }
11
+ .input > input { flex: 1; min-width: 0; height: 100%; padding: 0; border: 0; background: none; color: inherit; font: inherit; outline: none; }
12
+ .input:has(> input:focus-visible) { border-color: var(--saffron); box-shadow: 0 0 0 4px var(--saffron-soft); }
13
+ /* the callback: its beginning shows, a long end gives way */
14
+ .input.ro { background: var(--surface-2); }
15
+ .input.ro > input { text-overflow: ellipsis; }
16
+ .copy, .eye { flex: none; padding: 0; border: 0; background: none; font: inherit; cursor: pointer; }
17
+ .eye span { display: flex; }
18
+ .eye svg { width: 16px; height: 16px; }
19
+ footer { display: flex; align-items: center; gap: 12px; }
20
+ footer .btn { margin-left: auto; }
21
+ .outcome { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12.5px; }
22
+ .outcome .i svg { width: 14px; height: 14px; }
23
+ .outcome.done { color: var(--jade); }
24
+ .outcome.wrong { color: var(--crimson); }
25
+
26
+ :root[data-layout="narrow"] .fields { grid-template-columns: 1fr; }
@@ -0,0 +1 @@
1
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><rect width="24" height="24" rx="6.5" fill="#24292f"/><path fill="#fff" transform="translate(4.5 4.5) scale(.625)" d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
@@ -0,0 +1 @@
1
+ <!-- @license lucide-static v1.46.0 - ISC --><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" /><path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" /><path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" /><path d="m2 2 20 20" /></svg>
@@ -0,0 +1 @@
1
+ <!-- @license lucide-static v1.46.0 - ISC --><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" /><circle cx="12" cy="12" r="3" /></svg>
@@ -0,0 +1,61 @@
1
+ {% extends "server/base.html" %}
2
+ {% import "server/icons.html" as icons %}
3
+ {# folded open under the GitHub row of the login methods part #}
4
+ {% block top %}{% endblock %}
5
+ {% block title %}{{ t.text("github.name") }}{% endblock %}
6
+ {% block head %}<link rel="stylesheet" href="{{ asset('github.css') }}">{% endblock %}
7
+ {% block body %}
8
+ {# once saved, the part around it is drawn again to show GitHub set up #}
9
+ <form class="github" method="post" action="/ui/github/"{% if saved %} x-data x-init="window.parent !== window && window.parent.location.reload()"{% endif %}>
10
+ <div class="fields">
11
+ <div class="field">
12
+ <label for="client_id">Client ID<span class="req">*</span></label>
13
+ <input class="input mono" id="client_id" name="client_id" value="{{ configured.client_id if configured else '' }}" placeholder="{{ t.text('github.client_id.hint') }}" autocomplete="off" spellcheck="false" required>
14
+ </div>
15
+ {# what is typed may be shown; the secret saved before never comes back to the page #}
16
+ <div class="field" x-data="{ shown: false }">
17
+ <label for="client_secret">Client Secret<span class="req">*</span></label>
18
+ <span class="input">
19
+ <input class="mono" id="client_secret" name="client_secret" type="password" :type="shown ? 'text' : 'password'" placeholder="{{ t.text('github.client_secret.kept' if configured else 'github.client_secret.hint') }}" autocomplete="new-password" spellcheck="false"{% if not configured %} required{% endif %}>
20
+ <button class="suffix eye" type="button" @click="shown = !shown" :aria-pressed="shown" aria-label="{{ t.text('github.client_secret.show') }}">
21
+ <span x-show="!shown">{% include "github/icons/eye.svg" %}</span><span x-show="shown" x-cloak>{% include "github/icons/eye-off.svg" %}</span>
22
+ </button>
23
+ </span>
24
+ </div>
25
+ <div class="field">
26
+ <label for="default_role">{{ t.text("github.role") }}</label>
27
+ <span class="input select">
28
+ <select id="default_role" name="default_role">
29
+ <option value="">{{ t.text("github.role.global", {"role": default.name}) if default else t.text("github.role.none") }}</option>
30
+ {% for role in roles %}<option value="{{ role.id }}"{% if configured and configured.default_role_id == role.id %} selected{% endif %}>{{ role.name }}</option>{% endfor %}
31
+ </select>
32
+ {{ icons.icon("chevron-down") }}
33
+ </span>
34
+ </div>
35
+ <div class="field">
36
+ <label for="session_minutes">{{ t.text("github.minutes") }}</label>
37
+ <span class="input">
38
+ <input id="session_minutes" name="session_minutes" type="number" min="1" inputmode="numeric" value="{{ configured.session_minutes or '' if configured else '' }}" placeholder="{{ t.text('github.minutes.same', {'minutes': minutes}) }}">
39
+ <span class="suffix">{{ t.text("github.minutes.unit") }}</span>
40
+ </span>
41
+ </div>
42
+ {# where GitHub sends the browser back: under the address this page is seen at, not the one the server hears #}
43
+ <div class="field wide" x-data="{ copied: false }">
44
+ <label for="redirect_uri">{{ t.text("github.callback") }}</label>
45
+ <span class="input ro">
46
+ <input class="mono" id="redirect_uri" name="redirect_uri" x-ref="callback" readonly x-init="$el.value = location.origin + '{{ callback }}'">
47
+ <button class="suffix copy" type="button" @click="$refs.callback.select(); navigator.clipboard?.writeText($refs.callback.value); copied = true">
48
+ <span x-show="!copied">{{ t.text("github.copy") }}</span><span x-show="copied" x-cloak>{{ t.text("github.copied") }}</span>
49
+ </button>
50
+ </span>
51
+ <span class="hint">{{ t.text("github.callback.hint") }}</span>
52
+ </div>
53
+ </div>
54
+ <footer>
55
+ {% if error %}<span class="outcome wrong" role="alert">{{ t.text("github.invalid") }}</span>
56
+ {% elif configured %}<span class="outcome done">{{ icons.icon("check") }}{{ t.text("github.offered") }}</span>
57
+ {% else %}<span class="outcome">{{ t.text("github.offer") }}</span>{% endif %}
58
+ <button class="btn sm primary" type="submit">{{ t.text("github.save") }}</button>
59
+ </footer>
60
+ </form>
61
+ {% endblock %}
@@ -0,0 +1,52 @@
1
+ """What the GitHub login keeps: its one set of settings, and which GitHub user
2
+ each account came from, with the token renewing the account's sessions."""
3
+
4
+ import bazaar_contrib_storage as s
5
+ from bazaar_contrib_schema import Migration, ModuleSchema
6
+
7
+ SETTINGS = s.Table(
8
+ name="github_settings",
9
+ columns=(
10
+ s.ColumnDefinition(
11
+ name="id",
12
+ type="integer",
13
+ check=s.Compare(
14
+ left=s.Column(name="id"), operator="=", right=s.Value(value=1)
15
+ ),
16
+ ),
17
+ s.ColumnDefinition(name="client_id", type="text"),
18
+ s.ColumnDefinition(name="client_secret", type="text"),
19
+ s.ColumnDefinition(name="redirect_uri", type="text"),
20
+ s.ColumnDefinition(name="default_role_id", type="text", nullable=True),
21
+ s.ColumnDefinition(name="session_minutes", type="integer", nullable=True),
22
+ s.ColumnDefinition(name="updated_at_ms", type="integer"),
23
+ ),
24
+ primary_key=("id",),
25
+ )
26
+ ACCOUNTS = s.Table(
27
+ name="github_accounts",
28
+ columns=(
29
+ s.ColumnDefinition(name="github_id", type="text"),
30
+ s.ColumnDefinition(name="account_id", type="text", unique=True),
31
+ s.ColumnDefinition(name="login", type="text"),
32
+ s.ColumnDefinition(name="name", type="text"),
33
+ s.ColumnDefinition(name="email", type="text", nullable=True),
34
+ s.ColumnDefinition(name="avatar_url", type="text", nullable=True),
35
+ s.ColumnDefinition(name="token", type="text"),
36
+ s.ColumnDefinition(name="refresh_token", type="text", nullable=True),
37
+ s.ColumnDefinition(name="created_at_ms", type="integer"),
38
+ s.ColumnDefinition(name="updated_at_ms", type="integer"),
39
+ ),
40
+ primary_key=("github_id",),
41
+ )
42
+
43
+ MODULE = ModuleSchema(
44
+ tables=("github_settings", "github_accounts"),
45
+ migrations=(
46
+ Migration(
47
+ version=1,
48
+ name="github_login",
49
+ operations=(s.CreateTable(table=SETTINGS), s.CreateTable(table=ACCOUNTS)),
50
+ ),
51
+ ),
52
+ )
@@ -0,0 +1,181 @@
1
+ """The GitHub login's settings: the OAuth App it logs in through, the role it
2
+ gives the people logging in for the first time and how long their sessions
3
+ last, kept in one row and set on its own page inside the login methods part
4
+ of the settings page."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ lazy from time import time_ns
10
+ lazy from typing import Annotated, cast
11
+ lazy from urllib.parse import urlsplit
12
+
13
+ lazy from bazaar_contrib_server import Account, Pages
14
+ lazy from bazaar_contrib_server_access import METHODS, Access
15
+ lazy from bazaar_contrib_storage import (
16
+ Column,
17
+ Compare,
18
+ Conflict,
19
+ Database,
20
+ Insert,
21
+ Select,
22
+ Value,
23
+ )
24
+ lazy from pydantic import (
25
+ BaseModel,
26
+ BeforeValidator,
27
+ Field,
28
+ StringConstraints,
29
+ ValidationError,
30
+ field_validator,
31
+ )
32
+ lazy from starlette.exceptions import HTTPException
33
+ lazy from starlette.requests import Request
34
+ lazy from starlette.responses import RedirectResponse, Response
35
+ lazy from starlette.routing import Route
36
+
37
+ # where GitHub sends the browser back to, under the address the page is seen at
38
+ CALLBACK = "/login/github/callback"
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class Configured:
43
+ client_id: str
44
+ client_secret: str
45
+ redirect_uri: str
46
+ # nothing for the global default role, and for as long as a password login
47
+ default_role_id: str | None
48
+ session_minutes: int | None
49
+
50
+
51
+ async def configured(database: Database) -> Configured | None:
52
+ rows = await database.read(
53
+ lambda session: session.select(
54
+ Select(
55
+ table="github_settings",
56
+ where=Compare(
57
+ left=Column(name="id"), operator="=", right=Value(value=1)
58
+ ),
59
+ )
60
+ )
61
+ )
62
+ if not rows:
63
+ return None
64
+ row = rows[0]
65
+ return Configured(
66
+ client_id=cast(str, row["client_id"]),
67
+ client_secret=cast(str, row["client_secret"]),
68
+ redirect_uri=cast(str, row["redirect_uri"]),
69
+ default_role_id=cast(str | None, row["default_role_id"]),
70
+ session_minutes=cast(int | None, row["session_minutes"]),
71
+ )
72
+
73
+
74
+ def _blank(value: object) -> object:
75
+ return None if value == "" else value
76
+
77
+
78
+ type _Text = Annotated[
79
+ str, StringConstraints(strip_whitespace=True, min_length=1, max_length=255)
80
+ ]
81
+
82
+
83
+ class _Given(BaseModel):
84
+ client_id: _Text
85
+ # left empty, the secret saved before stays
86
+ client_secret: Annotated[_Text | None, BeforeValidator(_blank)] = None
87
+ default_role: Annotated[str | None, BeforeValidator(_blank)] = None
88
+ session_minutes: Annotated[
89
+ Annotated[int, Field(ge=1)] | None, BeforeValidator(_blank)
90
+ ] = None
91
+ redirect_uri: str = Field(max_length=2048)
92
+
93
+ @field_validator("redirect_uri")
94
+ @classmethod
95
+ def callback(cls, value: str) -> str:
96
+ parts = urlsplit(value)
97
+ if parts.scheme not in ("http", "https") or not parts.netloc:
98
+ raise ValueError("redirect_uri is an address of this site")
99
+ if parts.path != CALLBACK or parts.query or parts.fragment:
100
+ raise ValueError("redirect_uri is the GitHub login's callback")
101
+ return value
102
+
103
+
104
+ class Settings:
105
+ def __init__(self, pages: Pages, access: Access, database: Database) -> None:
106
+ self._pages = pages
107
+ self._access = access
108
+ self._database = database
109
+ self.app = pages.application(
110
+ [Route("/", self._page), Route("/", self._save, methods=["POST"])]
111
+ )
112
+
113
+ async def _page(
114
+ self, request: Request, *, error: bool = False, status_code: int = 200
115
+ ) -> Response:
116
+ _allow(request)
117
+ return await self._pages.render(
118
+ request,
119
+ "github/settings.html",
120
+ status_code=status_code,
121
+ configured=await configured(self._database),
122
+ roles=await self._access.roles(),
123
+ default=await self._access.default_role(),
124
+ minutes=self._access.minutes,
125
+ callback=CALLBACK,
126
+ saved="saved" in request.query_params,
127
+ error=error,
128
+ )
129
+
130
+ async def _save(self, request: Request) -> Response:
131
+ _allow(request)
132
+ form = await request.form()
133
+ try:
134
+ given = _Given.model_validate(
135
+ {name: form.get(name, "") for name in _Given.model_fields}
136
+ )
137
+ except ValidationError:
138
+ return await self._page(request, error=True, status_code=422)
139
+ stored = await configured(self._database)
140
+ secret = given.client_secret or (
141
+ None if stored is None else stored.client_secret
142
+ )
143
+ roles = {role.id for role in await self._access.roles()}
144
+ if secret is None or given.default_role not in roles | {None}:
145
+ return await self._page(request, error=True, status_code=422)
146
+ await self._database.write(
147
+ lambda session: session.insert(
148
+ Insert(
149
+ table="github_settings",
150
+ rows=(
151
+ {
152
+ "id": 1,
153
+ "client_id": given.client_id,
154
+ "client_secret": secret,
155
+ "redirect_uri": given.redirect_uri,
156
+ "default_role_id": given.default_role,
157
+ "session_minutes": given.session_minutes,
158
+ "updated_at_ms": time_ns() // 1_000_000,
159
+ },
160
+ ),
161
+ conflict=Conflict(
162
+ columns=("id",),
163
+ update=(
164
+ "client_id",
165
+ "client_secret",
166
+ "redirect_uri",
167
+ "default_role_id",
168
+ "session_minutes",
169
+ "updated_at_ms",
170
+ ),
171
+ ),
172
+ )
173
+ )
174
+ )
175
+ return RedirectResponse("/ui/github/?saved", status_code=303)
176
+
177
+
178
+ def _allow(request: Request) -> None:
179
+ account: Account = request.state.account
180
+ if not account.allows(METHODS):
181
+ raise HTTPException(status_code=403)
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: bazaar-contrib-server-github
3
+ Version: 0.3.0rc1
4
+ Summary: Logging in to the Bazaar Compute server with a GitHub account
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: aiohttp>=3.12.0
8
+ Requires-Dist: bazaar-core~=0.3.0rc1
9
+ Requires-Dist: bazaar-contrib-http~=0.3.0rc1
10
+ Requires-Dist: bazaar-contrib-schema~=0.3.0rc1
11
+ Requires-Dist: bazaar-contrib-storage~=0.3.0rc1
12
+ Requires-Dist: bazaar-contrib-server~=0.3.0rc3
13
+ Requires-Dist: bazaar-contrib-server-access~=0.3.0rc2
14
+ Requires-Dist: bazaar-contrib-server-database~=0.3.0rc1
15
+ Requires-Dist: pydantic>=2.12.0
16
+ Requires-Dist: python-multipart>=0.0.32
17
+ Requires-Dist: starlette>=0.48.0
18
+ Requires-Python: >=3.15
19
+ Project-URL: Repository, https://github.com/open-bazaar/contrib-server-github
20
+ Description-Content-Type: text/markdown
21
+
22
+ # bazaar-contrib-server-github
23
+
24
+ Logging in to the Bazaar Compute server with a GitHub account.
25
+
26
+ ```toml
27
+ [[contribs]]
28
+ package = "bazaar-contrib-server-github~=0.3.0rc1"
29
+ [[contribs.enabled]]
30
+ entry = "server-github"
31
+ ```
32
+
33
+ Create an OAuth App on GitHub, then fill in its Client ID and Client Secret under Settings › Login methods, where the callback URL to give the app is shown.
@@ -0,0 +1,18 @@
1
+ bazaar_contrib_server_github/__init__.py,sha256=6ItoFWk7JA2UeZwFdF9BIli4MXxx__QiBrOmXEHTWfg,2223
2
+ bazaar_contrib_server_github/client.py,sha256=QcHo-DAPjhW3ilMNu1fyyP7hVI4D57bVfk_ziu2vrTY,4762
3
+ bazaar_contrib_server_github/method.py,sha256=9yf3PMO7AEbFb7C75gtfiacRQvTJNbV2HraU3i5xX9M,8902
4
+ bazaar_contrib_server_github/resources/THIRD_PARTY.md,sha256=RaFkKfE9Bqpe_LDGt_edQucuxyrhL-co9qby3j-jBlc,264
5
+ bazaar_contrib_server_github/resources/locales/en.toml,sha256=FWQ2C8GFAwsjX4MTdOy8NtT4sVJgiXT5SM2MO8CvQ-U,1165
6
+ bazaar_contrib_server_github/resources/locales/zh-CN.toml,sha256=mIO9Qnqt5fAfFVfeiF7_Uz0Od_9ts3q0byZHG8Ztz74,1163
7
+ bazaar_contrib_server_github/resources/static/github.css,sha256=8Ygl2bAQoV00sygCUKfGs-tZm8lMKSmkty1e_J0ycQE,1421
8
+ bazaar_contrib_server_github/resources/templates/github/github.svg,sha256=f7tb7k57vPtPOKCVg1l-09KUIzpFGllC7sSn9JzDh6U,900
9
+ bazaar_contrib_server_github/resources/templates/github/icons/eye-off.svg,sha256=0AZQin4GA8g83IrfTMgMZLjQq82kHBkoo8x_yXzaaRs,495
10
+ bazaar_contrib_server_github/resources/templates/github/icons/eye.svg,sha256=6V7r5izltbaa7lW26KfX8doRPKKZBjVwZ3Xco0uk55k,357
11
+ bazaar_contrib_server_github/resources/templates/github/settings.html,sha256=YzuJcZ22oSNOb2oU--9WT1pnApSXJhq8d-9u9S6zr8E,4133
12
+ bazaar_contrib_server_github/schema.py,sha256=AKvtr6g56ovk0tnkPYKB203FEbnUSxZPPYZTkogwzEw,1999
13
+ bazaar_contrib_server_github/settings.py,sha256=5AH10TCtUdbun3XvKZ5vD5k2dEibO-Np5m2lFTkUjvM,6199
14
+ bazaar_contrib_server_github-0.3.0rc1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
15
+ bazaar_contrib_server_github-0.3.0rc1.dist-info/WHEEL,sha256=xTCBFIZIIyRSxyowOv5Wqg_jFU6KsdIffuulBB09Ph8,80
16
+ bazaar_contrib_server_github-0.3.0rc1.dist-info/entry_points.txt,sha256=0aPW_DhrDP2RqSKFqUOUtlZOcgO0Pd1CQSWZYm8Wkas,84
17
+ bazaar_contrib_server_github-0.3.0rc1.dist-info/METADATA,sha256=59DQ_hKQD58sS33N7WO_6FVb3YNCplpgmaB6rAMEGS8,1189
18
+ bazaar_contrib_server_github-0.3.0rc1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [bazaar_compute_node.contribs]
2
+ server-github = bazaar_contrib_server_github:github
3
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.