Skip to content

Commit

Permalink
Matrix account creation (#6)
Browse files Browse the repository at this point in the history
* store MatrixCredential on login

* Store credentials if fractal db is initialized

* Update pyproject.toml
  • Loading branch information
thebalaa authored Jul 26, 2024
1 parent 3be1d3a commit e26d097
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
32 changes: 29 additions & 3 deletions fractal/cli/controllers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

from asgiref.sync import async_to_sync
from clicz import cli_method
from django.db import transaction
from fractal.cli.utils import read_user_data, write_user_data
from fractal.matrix import MatrixClient, get_homeserver_for_matrix_id
from fractal.matrix.utils import parse_matrix_id, prompt_matrix_password
from fractal_database.utils import is_db_initialized
from nio import LoginError, WhoamiError


Expand All @@ -25,21 +27,24 @@ class AuthController:
def login(
self,
matrix_id: str,
password: Optional[str] = None,
homeserver_url: Optional[str] = None,
access_token: Optional[str] = None,
**kwargs,
):
"""
Login to a Matrix homeserver.
---
Args:
matrix_id: Matrix ID of user to login as
homeserver_url: Homeserver to login to
matrix_id: Matrix ID of user to login as.
password: Password for the Matrix ID.
homeserver_url: Homeserver to login to.
access_token: Access token to use for login.
"""
if not access_token:
homeserver_url, access_token = async_to_sync(self._login_with_password)(
matrix_id, homeserver_url=homeserver_url
matrix_id, homeserver_url=homeserver_url, password=password
)
else:
if not homeserver_url:
Expand All @@ -62,6 +67,27 @@ def login(
},
self.TOKEN_FILE,
)
if is_db_initialized():
from fractal_database_matrix.models import (
MatrixCredentials,
MatrixHomeserver,
)

try:
hs = MatrixHomeserver.objects.get(url=homeserver_url)
MatrixCredentials.objects.create(
matrix_id=matrix_id,
access_token=access_token,
homeserver=hs,
)
except MatrixHomeserver.DoesNotExist:
with transaction.atomic():
hs = MatrixHomeserver.objects.create(url=homeserver_url)
MatrixCredentials.objects.create(
matrix_id=matrix_id,
access_token=access_token,
homeserver=hs,
)

print(f"Successfully logged in as {matrix_id}")

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ appdirs = "^1.4.4"
clicz = ">=0.0.2"
asgiref = ">=3.7.2"
fractal-matrix-client = ">=0.0.1"
fractal-database = ">=0.0.1"
rich = ">=12.6.0"
pytest = { version = "^7.4.3", optional = true }
pytest-asyncio = { version = "^0.21.1", optional = true }
Expand Down

0 comments on commit e26d097

Please sign in to comment.