openswx-collab-server 0.1.0__tar.gz

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.
Files changed (35) hide show
  1. openswx_collab_server-0.1.0/LICENSE +202 -0
  2. openswx_collab_server-0.1.0/PKG-INFO +57 -0
  3. openswx_collab_server-0.1.0/README.md +17 -0
  4. openswx_collab_server-0.1.0/openswx_collab_server/__init__.py +2 -0
  5. openswx_collab_server-0.1.0/openswx_collab_server/__main__.py +107 -0
  6. openswx_collab_server-0.1.0/openswx_collab_server/access.py +98 -0
  7. openswx_collab_server-0.1.0/openswx_collab_server/app.py +108 -0
  8. openswx_collab_server-0.1.0/openswx_collab_server/assemblies.py +181 -0
  9. openswx_collab_server-0.1.0/openswx_collab_server/auth.py +474 -0
  10. openswx_collab_server-0.1.0/openswx_collab_server/config.py +66 -0
  11. openswx_collab_server-0.1.0/openswx_collab_server/db.py +241 -0
  12. openswx_collab_server-0.1.0/openswx_collab_server/documents.py +402 -0
  13. openswx_collab_server-0.1.0/openswx_collab_server/hooks.py +46 -0
  14. openswx_collab_server-0.1.0/openswx_collab_server/hub.py +870 -0
  15. openswx_collab_server-0.1.0/openswx_collab_server/lifecycle.py +204 -0
  16. openswx_collab_server-0.1.0/openswx_collab_server/mail.py +73 -0
  17. openswx_collab_server-0.1.0/openswx_collab_server/migrate.py +77 -0
  18. openswx_collab_server-0.1.0/openswx_collab_server/migrations/__init__.py +0 -0
  19. openswx_collab_server-0.1.0/openswx_collab_server/migrations/env.py +22 -0
  20. openswx_collab_server-0.1.0/openswx_collab_server/migrations/script.py.mako +24 -0
  21. openswx_collab_server-0.1.0/openswx_collab_server/migrations/versions/0001_baseline.py +265 -0
  22. openswx_collab_server-0.1.0/openswx_collab_server/migrations/versions/0002_users_deleted_at.py +28 -0
  23. openswx_collab_server-0.1.0/openswx_collab_server/migrations/versions/0003_password_resets.py +36 -0
  24. openswx_collab_server-0.1.0/openswx_collab_server/migrations/versions/__init__.py +0 -0
  25. openswx_collab_server-0.1.0/openswx_collab_server/orgs.py +339 -0
  26. openswx_collab_server-0.1.0/openswx_collab_server/security.py +85 -0
  27. openswx_collab_server-0.1.0/openswx_collab_server/storage.py +123 -0
  28. openswx_collab_server-0.1.0/openswx_collab_server.egg-info/PKG-INFO +57 -0
  29. openswx_collab_server-0.1.0/openswx_collab_server.egg-info/SOURCES.txt +33 -0
  30. openswx_collab_server-0.1.0/openswx_collab_server.egg-info/dependency_links.txt +1 -0
  31. openswx_collab_server-0.1.0/openswx_collab_server.egg-info/entry_points.txt +2 -0
  32. openswx_collab_server-0.1.0/openswx_collab_server.egg-info/requires.txt +25 -0
  33. openswx_collab_server-0.1.0/openswx_collab_server.egg-info/top_level.txt +1 -0
  34. openswx_collab_server-0.1.0/pyproject.toml +50 -0
  35. openswx_collab_server-0.1.0/setup.cfg +4 -0
@@ -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.
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: openswx-collab-server
3
+ Version: 0.1.0
4
+ Summary: Live collaboration server for openswx: accounts, organisations, cloud documents, real-time editing
5
+ Author: the openswx authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/DukeOfCheese/openswx-collab
8
+ Project-URL: Documentation, https://github.com/DukeOfCheese/openswx-collab/tree/main/docs
9
+ Project-URL: Issues, https://github.com/DukeOfCheese/openswx-collab/issues
10
+ Keywords: cad,collaboration,real-time,openswx
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: openswx-collab-protocol==0.1.0
19
+ Requires-Dist: fastapi>=0.110
20
+ Requires-Dist: uvicorn[standard]>=0.29
21
+ Requires-Dist: sqlalchemy[asyncio]>=2.0
22
+ Requires-Dist: aiosqlite>=0.20
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: alembic>=1.13
25
+ Provides-Extra: postgres
26
+ Requires-Dist: asyncpg>=0.29; extra == "postgres"
27
+ Provides-Extra: s3
28
+ Requires-Dist: boto3>=1.34; extra == "s3"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Provides-Extra: test
32
+ Requires-Dist: pytest>=8; extra == "test"
33
+ Requires-Dist: asyncpg>=0.29; extra == "test"
34
+ Requires-Dist: boto3>=1.34; extra == "test"
35
+ Requires-Dist: moto[server]>=5; extra == "test"
36
+ Requires-Dist: pixeltable-pgserver>=0.7; extra == "test"
37
+ Requires-Dist: pyyaml>=6; extra == "test"
38
+ Requires-Dist: websockets>=12; extra == "test"
39
+ Dynamic: license-file
40
+
41
+ # openswx-collab-server
42
+
43
+ Self-hostable live collaboration server for [openswx](https://github.com/DukeOfCheese/openswx): several
44
+ people editing one CAD model at once, with cursors, feature locks, edit history, named versions and
45
+ assemblies that pin part versions. The server never runs a geometry kernel.
46
+
47
+ ```
48
+ pip install openswx-collab-server
49
+ openswx-collab-server serve
50
+ ```
51
+
52
+ PostgreSQL: `pip install "openswx-collab-server[postgres]"`; S3 storage: `[s3]`. A Docker image is at
53
+ `ghcr.io/dukeofcheese/openswx-collab-server`.
54
+
55
+ Documentation, self-hosting guide and the protocol reference: https://github.com/DukeOfCheese/openswx-collab
56
+
57
+ Apache-2.0. openswx-collab is an independent open-source project, not affiliated with Dassault Systemes.
@@ -0,0 +1,17 @@
1
+ # openswx-collab-server
2
+
3
+ Self-hostable live collaboration server for [openswx](https://github.com/DukeOfCheese/openswx): several
4
+ people editing one CAD model at once, with cursors, feature locks, edit history, named versions and
5
+ assemblies that pin part versions. The server never runs a geometry kernel.
6
+
7
+ ```
8
+ pip install openswx-collab-server
9
+ openswx-collab-server serve
10
+ ```
11
+
12
+ PostgreSQL: `pip install "openswx-collab-server[postgres]"`; S3 storage: `[s3]`. A Docker image is at
13
+ `ghcr.io/dukeofcheese/openswx-collab-server`.
14
+
15
+ Documentation, self-hosting guide and the protocol reference: https://github.com/DukeOfCheese/openswx-collab
16
+
17
+ Apache-2.0. openswx-collab is an independent open-source project, not affiliated with Dassault Systemes.
@@ -0,0 +1,2 @@
1
+ """openswx collaboration server: accounts, organisations, cloud documents and live editing."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,107 @@
1
+ """Command line: `openswx-collab-server serve`, and account tools for the operator.
2
+
3
+ serve [--host 0.0.0.0] [--port 8787]
4
+ migrate upgrade the database schema (take a backup first)
5
+ db-status which schema the database is at, and which this server needs
6
+ create-admin <email> [name] make (or promote) a server admin; asks for a password
7
+ reset-password <email> set a new password and end the account's sessions
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import asyncio
13
+ import getpass
14
+ import os
15
+ import sys
16
+
17
+ from sqlalchemy import delete, select
18
+ from sqlalchemy.ext.asyncio import async_sessionmaker
19
+
20
+ from .config import Settings
21
+ from .db import Session, User, init_db, make_engine
22
+ from .hooks import load_hooks
23
+ from .migrate import SchemaError, current, upgrade
24
+ from .security import clean_email, hash_password
25
+
26
+
27
+ def _ask_password() -> str:
28
+ pw = os.environ.get("OSWX_COLLAB_PASSWORD") or getpass.getpass("New password: ")
29
+ if len(pw) < 8:
30
+ sys.exit("the password needs at least 8 characters")
31
+ return pw
32
+
33
+
34
+ async def _account(settings: Settings, email: str, name: str | None, admin: bool) -> str:
35
+ email = clean_email(email) or sys.exit("not an email address")
36
+ engine = make_engine(settings.database_url)
37
+ await init_db(engine, settings.auto_migrate, load_hooks())
38
+ async with async_sessionmaker(engine, expire_on_commit=False)() as s:
39
+ user = (await s.execute(select(User).where(User.email == email))).scalar_one_or_none()
40
+ if user is None and not admin:
41
+ sys.exit(f"no account {email}")
42
+ pw = hash_password(_ask_password())
43
+ if user is None:
44
+ user = User(email=email, name=name or email.split("@")[0], password_hash=pw, is_server_admin=True,
45
+ email_verified=True)
46
+ s.add(user)
47
+ done = f"created server admin {email}"
48
+ else:
49
+ user.password_hash = pw
50
+ user.is_server_admin = user.is_server_admin or admin
51
+ await s.execute(delete(Session).where(Session.user_id == user.id))
52
+ done = f"password set for {email}" + (" (server admin)" if user.is_server_admin else "")
53
+ await s.commit()
54
+ await engine.dispose()
55
+ return done
56
+
57
+
58
+ async def _schema(settings: Settings, do_upgrade: bool) -> str:
59
+ engine = make_engine(settings.database_url)
60
+ try:
61
+ if do_upgrade:
62
+ before, _ = await current(engine)
63
+ after = await upgrade(engine, allow=True)
64
+ async with engine.begin() as conn:
65
+ await conn.run_sync(load_hooks().prepare_db)
66
+ return f"schema {before or 'none'} -> {after}" if before != after else f"schema {after}: up to date"
67
+ at, head = await current(engine)
68
+ return f"database at {at or 'none (or made before migrations)'}; this server needs {head}"
69
+ except SchemaError as exc:
70
+ sys.exit(str(exc))
71
+ finally:
72
+ await engine.dispose()
73
+
74
+
75
+ def main(argv: list[str] | None = None) -> None:
76
+ p = argparse.ArgumentParser(prog="openswx-collab-server", description=__doc__,
77
+ formatter_class=argparse.RawDescriptionHelpFormatter)
78
+ sub = p.add_subparsers(dest="cmd", required=True)
79
+ s = sub.add_parser("serve")
80
+ s.add_argument("--host", default="127.0.0.1")
81
+ s.add_argument("--port", type=int, default=8787)
82
+ a = sub.add_parser("create-admin")
83
+ a.add_argument("email")
84
+ a.add_argument("name", nargs="?")
85
+ r = sub.add_parser("reset-password")
86
+ r.add_argument("email")
87
+ sub.add_parser("migrate")
88
+ sub.add_parser("db-status")
89
+ args = p.parse_args(argv)
90
+ settings = Settings.from_env()
91
+ if args.cmd in ("migrate", "db-status"):
92
+ print(asyncio.run(_schema(settings, args.cmd == "migrate")))
93
+ return
94
+ if args.cmd == "serve":
95
+ import uvicorn
96
+
97
+ from .app import create_app
98
+ # one process: open documents live in this process's memory
99
+ uvicorn.run(create_app(settings), host=args.host, port=args.port, workers=1, ws_max_size=settings.max_change_bytes + 65536)
100
+ elif args.cmd == "create-admin":
101
+ print(asyncio.run(_account(settings, args.email, args.name, True)))
102
+ else:
103
+ print(asyncio.run(_account(settings, args.email, None, False)))
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
@@ -0,0 +1,98 @@
1
+ """Who is asking, and what they may do.
2
+
3
+ Organisation roles: owner > admin > member. Project roles: owner > editor > viewer.
4
+ Organisation owners and admins are owners of every project; everyone else has the role they were given
5
+ in a project, or cannot see it at all. Files inherit from their project.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import AsyncIterator
10
+
11
+ from fastapi import Depends, HTTPException, Request
12
+ from sqlalchemy import select
13
+ from sqlalchemy.ext.asyncio import AsyncSession
14
+
15
+ from .db import Document, OrgMember, Project, ProjectMember, Session, User, now
16
+ from .security import ORG_ROLES, PROJECT_ROLES, token_hash
17
+
18
+
19
+ async def get_db(request: Request) -> AsyncIterator[AsyncSession]:
20
+ async with request.app.state.db() as s:
21
+ yield s
22
+
23
+
24
+ async def user_for_token(db: AsyncSession, token: str) -> User | None:
25
+ if not token:
26
+ return None
27
+ sess = await db.get(Session, token_hash(token))
28
+ if sess is None or sess.expires_at < now():
29
+ return None
30
+ user = await db.get(User, sess.user_id)
31
+ return None if user is None or user.disabled else user
32
+
33
+
34
+ def bearer(request: Request) -> str:
35
+ auth = request.headers.get("authorization", "")
36
+ return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
37
+
38
+
39
+ async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> User:
40
+ user = await user_for_token(db, bearer(request))
41
+ if user is None:
42
+ raise HTTPException(401, "sign in first")
43
+ return user
44
+
45
+
46
+ async def org_role(db: AsyncSession, user: User, org_id: str) -> str | None:
47
+ m = await db.get(OrgMember, (org_id, user.id))
48
+ return m.role if m else None
49
+
50
+
51
+ async def need_org(db: AsyncSession, user: User, org_id: str, minimum: str = "member") -> str:
52
+ role = await org_role(db, user, org_id)
53
+ if role is None:
54
+ raise HTTPException(404, "no such organisation")
55
+ if ORG_ROLES[role] < ORG_ROLES[minimum]:
56
+ raise HTTPException(403, f"needs the organisation role {minimum}")
57
+ return role
58
+
59
+
60
+ async def project_role(db: AsyncSession, user: User, project: Project) -> str | None:
61
+ role = await org_role(db, user, project.org_id)
62
+ if role is None:
63
+ return None
64
+ if ORG_ROLES[role] >= ORG_ROLES["admin"]:
65
+ return "owner"
66
+ pm = await db.get(ProjectMember, (project.id, user.id))
67
+ return pm.role if pm else None
68
+
69
+
70
+ async def need_project(db: AsyncSession, user: User, project_id: str, minimum: str = "viewer") -> tuple[Project, str]:
71
+ project = await db.get(Project, project_id)
72
+ role = await project_role(db, user, project) if project else None
73
+ if role is None:
74
+ raise HTTPException(404, "no such project") # (not 403: a project you cannot see does not exist for you)
75
+ if PROJECT_ROLES[role] < PROJECT_ROLES[minimum]:
76
+ raise HTTPException(403, f"needs the project role {minimum}")
77
+ return project, role
78
+
79
+
80
+ async def need_document(db: AsyncSession, user: User, document_id: str,
81
+ minimum: str = "viewer") -> tuple[Document, Project, str]:
82
+ doc = await db.get(Document, document_id)
83
+ if doc is None or doc.deleted_at is not None:
84
+ raise HTTPException(404, "no such document")
85
+ try:
86
+ project, role = await need_project(db, user, doc.project_id, minimum)
87
+ except HTTPException as exc:
88
+ raise HTTPException(exc.status_code, "no such document" if exc.status_code == 404 else exc.detail) from exc
89
+ return doc, project, role
90
+
91
+
92
+ async def visible_projects(db: AsyncSession, user: User, org_id: str, role: str) -> list[tuple[Project, str]]:
93
+ projects = (await db.execute(select(Project).where(Project.org_id == org_id).order_by(Project.name))).scalars().all()
94
+ if ORG_ROLES[role] >= ORG_ROLES["admin"]:
95
+ return [(p, "owner") for p in projects]
96
+ mine = {pm.project_id: pm.role for pm in (await db.execute(
97
+ select(ProjectMember).where(ProjectMember.user_id == user.id))).scalars()}
98
+ return [(p, mine[p.id]) for p in projects if p.id in mine]
@@ -0,0 +1,108 @@
1
+ """The collaboration server application."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from contextlib import asynccontextmanager
6
+
7
+ import httpx
8
+ from fastapi import Depends, FastAPI
9
+ from fastapi.responses import HTMLResponse
10
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
11
+
12
+ from openswx_collab_protocol import PROTOCOL_VERSION
13
+
14
+ from . import __version__, assemblies, auth, documents, lifecycle, orgs
15
+ from .access import get_db
16
+ from .config import Settings
17
+ from .db import init_db, make_engine
18
+ from .hooks import Hooks, load_hooks
19
+ from .hub import Hub
20
+ from .mail import Mailer
21
+ from .security import Limiter
22
+ from .storage import make_storage
23
+
24
+
25
+ _RESET_PAGE = """<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width">
26
+ <meta name=referrer content=no-referrer><title>Choose a new password</title>
27
+ <body style="font:16px system-ui;max-width:28em;margin:4em auto;padding:0 1em">
28
+ <h1>Choose a new password</h1>
29
+ <form id=f><p><label>New password<br><input id=p type=password minlength=8 required autocomplete=new-password
30
+ style="width:100%;font:inherit;padding:.4em"></label></p>
31
+ <p><label>Again<br><input id=q type=password minlength=8 required autocomplete=new-password
32
+ style="width:100%;font:inherit;padding:.4em"></label></p>
33
+ <p><button style="font:inherit;padding:.4em 1em">Set password</button></p></form><p id=m role=status></p>
34
+ <script>
35
+ const token = __TOKEN__;
36
+ document.getElementById("f").onsubmit = async (e) => {
37
+ e.preventDefault();
38
+ const m = document.getElementById("m"), p = document.getElementById("p").value;
39
+ if (p !== document.getElementById("q").value) { m.textContent = "The two passwords differ."; return; }
40
+ const r = await fetch("/api/auth/password-reset/confirm", {method: "POST",
41
+ headers: {"content-type": "application/json"}, body: JSON.stringify({token, password: p})});
42
+ const d = await r.json().catch(() => ({}));
43
+ m.textContent = r.ok ? d.message : (typeof d.detail === "string" ? d.detail : "That did not work.");
44
+ if (r.ok) document.getElementById("f").remove();
45
+ };
46
+ </script></body>"""
47
+
48
+
49
+ def create_app(settings: Settings | None = None, hooks: Hooks | None = None, http_client=None) -> FastAPI:
50
+ settings = settings or Settings.from_env()
51
+
52
+ @asynccontextmanager
53
+ async def lifespan(app: FastAPI):
54
+ engine = make_engine(settings.database_url)
55
+ await init_db(engine, settings.auto_migrate, app.state.hooks)
56
+ app.state.db = async_sessionmaker(engine, expire_on_commit=False)
57
+ app.state.hub = Hub(settings, app.state.db, app.state.storage)
58
+ await app.state.hub.start()
59
+ try:
60
+ yield
61
+ finally:
62
+ await app.state.hub.stop()
63
+ await engine.dispose()
64
+
65
+ app = FastAPI(title="openswx collaboration server", version=__version__, lifespan=lifespan)
66
+ app.state.settings = settings
67
+ app.state.hooks = hooks or load_hooks()
68
+ app.state.storage = make_storage(settings.storage_url, settings.s3_endpoint)
69
+ app.state.login_limiter = Limiter()
70
+ app.state.reset_limiter = Limiter(limit=5, window=3600)
71
+ app.state.mailer = Mailer(settings)
72
+ app.state.http_client = http_client or (lambda: httpx.AsyncClient(timeout=15))
73
+
74
+ @app.get("/api/health")
75
+ async def health():
76
+ return {"ok": True}
77
+
78
+ @app.get("/api/server")
79
+ async def server_info(db: AsyncSession = Depends(get_db)):
80
+ """What a client needs to draw its sign-in dialog."""
81
+ return {"name": "openswx-collab", "version": __version__, "protocol": PROTOCOL_VERSION,
82
+ "registration": await auth.registration_mode(db, settings),
83
+ "oauth": settings.oauth_providers(), "email": app.state.mailer.enabled,
84
+ "edition": app.state.hooks.name,
85
+ **app.state.hooks.server_info()}
86
+
87
+ @app.get("/invite/{token}", response_class=HTMLResponse)
88
+ async def invite_page(token: str):
89
+ """Where an invite link lands in a browser: the invite is used from inside openswx."""
90
+ return ("<!doctype html><meta charset=utf-8><title>openswx invite</title>"
91
+ "<body style='font:16px system-ui;max-width:34em;margin:4em auto;padding:0 1em'>"
92
+ "<h1>You have been invited to collaborate in openswx</h1>"
93
+ "<p>Open openswx, choose <b>Collaborate &rsaquo; Join with invite</b>, and paste this page's "
94
+ "address. You can create your account there.</p></body>")
95
+
96
+ @app.get("/reset-password/{token}", response_class=HTMLResponse)
97
+ async def reset_page(token: str):
98
+ """Where a reset link lands: a small form that posts to /api/auth/password-reset/confirm."""
99
+ return _RESET_PAGE.replace("__TOKEN__", json.dumps(token))
100
+
101
+ app.include_router(auth.router)
102
+ app.include_router(orgs.router)
103
+ app.include_router(documents.router)
104
+ app.include_router(assemblies.router)
105
+ app.include_router(lifecycle.router)
106
+ for r in app.state.hooks.routers():
107
+ app.include_router(r)
108
+ return app