Skip to content

Commit

Permalink
store MatrixCredential on login
Browse files Browse the repository at this point in the history
  • Loading branch information
thebalaa committed Jul 25, 2024
1 parent 3be1d3a commit 8b2981e
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 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 use_django
from nio import LoginError, WhoamiError


Expand All @@ -22,24 +24,30 @@ class AuthController:
TOKEN_FILE = "matrix.creds.yaml"

@cli_method
# @use_django move to store credential login to _login so we can still login without initing
def login(
self,
matrix_id: str,
password: Optional[str] = None,
homeserver_url: Optional[str] = None,
access_token: Optional[str] = None,
store_credential: bool = False,
**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.
store_credential: Create a MatrixCredential in the local database.
"""
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 +70,28 @@ def login(
},
self.TOKEN_FILE,
)
if store_credential:
from fractal_database.models import Device
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

0 comments on commit 8b2981e

Please sign in to comment.