divbase-cli 0.1.0__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,525 @@
1
+ """
2
+ Manage user authentication with the DivBase server.
3
+
4
+ This includes login/logout and the getting, storing, using, and refreshing of access + refresh JWTs and Personal Access Tokens (PATs).
5
+
6
+ User JWTs and PATs can be stored in the device's OS keyring.
7
+ They fallback to a local file with 0600 permissions if not possible.
8
+ - JWTs stored on login
9
+ - PATs stored when user adds one via the add-pat CLI command.
10
+
11
+ PATs can also be provided via environment variable (which takes precedence over any stored PATs) but not over a logged in session.
12
+ """
13
+
14
+ import contextlib
15
+ import json
16
+ import logging
17
+ import os
18
+ import time
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from json import JSONDecodeError
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import httpx
26
+ import keyring
27
+ import stamina
28
+ import yaml
29
+ from keyring.errors import KeyringError
30
+ from pydantic import SecretStr
31
+
32
+ from divbase_cli import __version__ as cli_version
33
+ from divbase_cli.cli_config import cli_settings
34
+ from divbase_cli.cli_exceptions import AuthenticationError, DivBaseAPIConnectionError, DivBaseAPIError
35
+ from divbase_cli.retries import retry_only_on_retryable_divbase_api_errors
36
+ from divbase_cli.user_config import UserConfig, load_user_config
37
+ from divbase_lib.api_schemas.auth import LogoutRequest
38
+ from divbase_lib.divbase_constants import CLI_VERSION_HEADER_KEY
39
+ from divbase_lib.utils import format_unix_timestamp_for_cli
40
+
41
+ LOGIN_AGAIN_MESSAGE = "Your session has expired. Please log in again with 'divbase-cli auth login [EMAIL]'."
42
+ PERSONAL_ACCESS_TOKEN_EXPIRED_MESSAGE = (
43
+ "Your Personal Access Token (PAT) has expired. \n"
44
+ "Please create a new one and add it with 'divbase-cli auth add-pat'. \n"
45
+ "See https://scilifelabdatacentre.github.io/divbase/user-guides/account-management/#personal-access-tokens for more details."
46
+ )
47
+
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ @dataclass
53
+ class TokenData:
54
+ """Class to hold user JWT data"""
55
+
56
+ access_token: SecretStr
57
+ refresh_token: SecretStr
58
+ access_token_expires_at: int
59
+ refresh_token_expires_at: int
60
+
61
+ def dump_tokens(self, fallback_output_path: Path = cli_settings.TOKENS_FALLBACK_PATH) -> None:
62
+ """Dump the user token data to the OS keyring. If fails, fall back to a local file."""
63
+ token_dict = {
64
+ "access_token": self.access_token.get_secret_value(),
65
+ "refresh_token": self.refresh_token.get_secret_value(),
66
+ "access_token_expires_at": self.access_token_expires_at,
67
+ "refresh_token_expires_at": self.refresh_token_expires_at,
68
+ }
69
+ _dump_to_keyring_or_file(
70
+ data=token_dict,
71
+ keyring_user_name=cli_settings.KEYRING_TOKENS_USERNAME,
72
+ fallback_file_path=fallback_output_path,
73
+ )
74
+
75
+ def is_access_token_expired(self) -> bool:
76
+ """Check if the access token is expired"""
77
+ return time.time() >= (self.access_token_expires_at - 5) # 5 second buffer
78
+
79
+ def is_refresh_token_expired(self) -> bool:
80
+ """Check if the refresh token is expired"""
81
+ return time.time() >= (self.refresh_token_expires_at - 300) # 5 minute buffer
82
+
83
+
84
+ def _delete_stored_jwts(token_path: Path) -> None:
85
+ """Attempt to delete user JWTs from both the keyring and the fallback file."""
86
+ with contextlib.suppress(KeyringError):
87
+ keyring.delete_password(
88
+ service_name=cli_settings.KEYRING_SERVICE, username=cli_settings.KEYRING_TOKENS_USERNAME
89
+ )
90
+ token_path.unlink(missing_ok=True)
91
+
92
+
93
+ @dataclass
94
+ class PATData:
95
+ """Class to hold user PAT data"""
96
+
97
+ name: str
98
+ pat_expires_at: int | None # None means the PAT does not expire
99
+ pat: SecretStr
100
+
101
+ def dump_pat_data(self, fallback_output_path: Path = cli_settings.PATS_FALLBACK_PATH) -> None:
102
+ """Dump the user PAT data to the OS keyring. If fails, fall back to a local file."""
103
+ token_dict = {
104
+ "name": self.name,
105
+ "pat_expires_at": self.pat_expires_at,
106
+ "pat": self.pat.get_secret_value(),
107
+ }
108
+ _dump_to_keyring_or_file(
109
+ data=token_dict,
110
+ keyring_user_name=cli_settings.KEYRING_PATS_USERNAME,
111
+ fallback_file_path=fallback_output_path,
112
+ )
113
+
114
+ def is_pat_expired(self) -> bool:
115
+ """Check if the PAT is expired"""
116
+ if self.pat_expires_at is None:
117
+ return False
118
+ return self.pat_expires_at <= time.time() + 10 # 10 second buffer to account for clock skew or time delay
119
+
120
+ def pat_expiry_formatted(self) -> str:
121
+ """Returns the token's expiry time in a human readable format in user's current timezone."""
122
+ if self.pat_expires_at is None:
123
+ return "Never"
124
+ return format_unix_timestamp_for_cli(unix_timestamp=self.pat_expires_at)
125
+
126
+
127
+ def delete_stored_pat(pat_path: Path = cli_settings.PATS_FALLBACK_PATH) -> None:
128
+ """Attempt to delete user PAT from both the keyring and the fallback file."""
129
+ with contextlib.suppress(KeyringError):
130
+ keyring.delete_password(service_name=cli_settings.KEYRING_SERVICE, username=cli_settings.KEYRING_PATS_USERNAME)
131
+ pat_path.unlink(missing_ok=True)
132
+
133
+
134
+ def check_existing_session(divbase_url: str, config: UserConfig) -> int | None:
135
+ """
136
+ Check if a user is already logged in to DivBase.
137
+ Used to prevent unnecessary multiple logins.
138
+
139
+ Returns the refresh token expiry timestamp if logged in (POSIX time), else None.
140
+ """
141
+ if not config.logged_in_url or config.logged_in_url != divbase_url:
142
+ return None
143
+
144
+ token_data = load_user_tokens()
145
+ if not token_data or token_data.is_refresh_token_expired():
146
+ return None
147
+
148
+ return token_data.refresh_token_expires_at
149
+
150
+
151
+ def _handle_divbase_api_error(response: httpx.Response, http_method: str, url: str) -> None:
152
+ """Handles custom display of a HTTP error response returned by DivBase API."""
153
+ request_id = response.headers.get("X-Request-ID", "unknown")
154
+ try:
155
+ response_body = response.json()
156
+ error_details = response_body.get("detail", "No error message provided.")
157
+ error_type = response_body.get("type", "unknown")
158
+ except (JSONDecodeError, ValueError):
159
+ # most likely situation for this would be if the reverse proxy returns an error, not the server itself.
160
+ error_details = response.text
161
+ error_type = "unexpected_server_error"
162
+
163
+ raise DivBaseAPIError(
164
+ error_details=error_details,
165
+ status_code=response.status_code,
166
+ error_type=error_type,
167
+ http_method=http_method,
168
+ url=url,
169
+ request_id=request_id,
170
+ ) from None
171
+
172
+
173
+ @stamina.retry(on=retry_only_on_retryable_divbase_api_errors, attempts=3)
174
+ def login_to_divbase(email: str, password: SecretStr, divbase_url: str) -> None:
175
+ """Log in to the DivBase server and return user tokens."""
176
+ login_url = f"{divbase_url}/v1/auth/login"
177
+ try:
178
+ response = httpx.post(
179
+ url=login_url,
180
+ data={
181
+ "grant_type": "password",
182
+ "username": email, # OAuth2 uses 'username', not 'email'
183
+ "password": password.get_secret_value(),
184
+ },
185
+ headers={
186
+ "Content-Type": "application/x-www-form-urlencoded",
187
+ CLI_VERSION_HEADER_KEY: cli_version,
188
+ },
189
+ )
190
+ except httpx.ConnectError:
191
+ # We don't raise the full error as it contains the password in the stack trace.
192
+ # a user could unknowingly dump this into e.g. a bug report/GitHub issue.
193
+ raise DivBaseAPIConnectionError() from None
194
+
195
+ try:
196
+ response.raise_for_status()
197
+ except httpx.HTTPStatusError:
198
+ if response.status_code == 401:
199
+ error_message = response.json().get("detail", "Invalid email or password.")
200
+ raise AuthenticationError(error_message) from None
201
+ _handle_divbase_api_error(response=response, http_method="POST", url=login_url)
202
+
203
+ data = response.json()
204
+ token_data = TokenData(
205
+ access_token=SecretStr(data["access_token"]),
206
+ refresh_token=SecretStr(data["refresh_token"]),
207
+ access_token_expires_at=data["access_token_expires_at"],
208
+ refresh_token_expires_at=data["refresh_token_expires_at"],
209
+ )
210
+ token_data.dump_tokens()
211
+
212
+ config = load_user_config()
213
+ config.set_login_status(url=divbase_url, email=email)
214
+
215
+
216
+ def logout_of_divbase(token_path: Path = cli_settings.TOKENS_FALLBACK_PATH) -> None:
217
+ """
218
+ Log out of the DivBase server.
219
+ We send the refresh token to DivBase to be revoked server-side.
220
+ """
221
+ config = load_user_config()
222
+
223
+ # the "if" avoids raising an error on a non logged in user trying to logout
224
+ if config.logged_in_url:
225
+ token_data = load_user_tokens(token_path=token_path)
226
+ if not token_data:
227
+ _delete_stored_jwts(token_path)
228
+ config.set_login_status(url=None, email=None)
229
+ return None
230
+
231
+ request_data = LogoutRequest(refresh_token=token_data.refresh_token.get_secret_value())
232
+ # We don't want logout to fail if server is unreachable or gives an error
233
+ # JWTs are stateless so local logout is sufficient.
234
+ try:
235
+ make_unauthenticated_request(
236
+ method="POST",
237
+ divbase_base_url=config.logged_in_url,
238
+ api_route="v1/auth/logout",
239
+ json=request_data.model_dump(),
240
+ )
241
+ except DivBaseAPIConnectionError as e:
242
+ warnings.warn(
243
+ f"Could not connect to DivBase server to log out fully: '{e}'.\n\n"
244
+ "Continuing local logout.\n"
245
+ "You do not need to do anything, but if you see this message often, please let us know.",
246
+ stacklevel=2,
247
+ category=UserWarning,
248
+ )
249
+ except DivBaseAPIError as e:
250
+ warnings.warn(
251
+ f"Received an error message from DivBase server when attempting to logout:"
252
+ f"'{e.error_message=}'. \n\n"
253
+ "Continuing local logout.\n"
254
+ "You do not need to do anything. If you see this message a lot, please let us know.",
255
+ stacklevel=2,
256
+ category=UserWarning,
257
+ )
258
+
259
+ _delete_stored_jwts(token_path)
260
+ config.set_login_status(url=None, email=None)
261
+
262
+
263
+ def load_user_tokens(token_path: Path = cli_settings.TOKENS_FALLBACK_PATH) -> TokenData | None:
264
+ """
265
+ Load user tokens from the OS keyring. Fallback for this is a local file with 0600 permissions.
266
+ Return None if no tokens found or if tokens are malformed/invalid - user logged out.
267
+ """
268
+ try:
269
+ raw = keyring.get_password(
270
+ service_name=cli_settings.KEYRING_SERVICE, username=cli_settings.KEYRING_TOKENS_USERNAME
271
+ )
272
+ except KeyringError as e:
273
+ raw = None
274
+ logger.debug(f"Keyring read failed with error: {e}, falling back to file storage.")
275
+
276
+ if raw is not None:
277
+ try:
278
+ token_dict = json.loads(raw)
279
+ return TokenData(
280
+ access_token=SecretStr(token_dict["access_token"]),
281
+ refresh_token=SecretStr(token_dict["refresh_token"]),
282
+ access_token_expires_at=token_dict["access_token_expires_at"],
283
+ refresh_token_expires_at=token_dict["refresh_token_expires_at"],
284
+ )
285
+ except (KeyError, json.JSONDecodeError) as e:
286
+ logger.debug(f"Keyring token data malformed: {e}")
287
+
288
+ if not token_path.exists():
289
+ return None
290
+
291
+ with open(token_path, "r") as file:
292
+ token_dict = yaml.safe_load(file)
293
+
294
+ try:
295
+ token_data = TokenData(
296
+ access_token=SecretStr(token_dict["access_token"]),
297
+ refresh_token=SecretStr(token_dict["refresh_token"]),
298
+ access_token_expires_at=token_dict["access_token_expires_at"],
299
+ refresh_token_expires_at=token_dict["refresh_token_expires_at"],
300
+ )
301
+ except (KeyError, TypeError) as e:
302
+ logger.debug(f"User tokens file at {token_path} appears to be malformed: {e}")
303
+ return None
304
+
305
+ return token_data
306
+
307
+
308
+ def load_stored_user_pat(pat_fallback_path: Path = cli_settings.PATS_FALLBACK_PATH) -> PATData | None:
309
+ """
310
+ Attempts to load a user's Personal Access Token (PAT) from:
311
+ 1. OS keyring (if stored there)
312
+ 2. file fallback (if stored there)
313
+
314
+ Returns the PATData if found and valid, else None.
315
+ """
316
+ try:
317
+ raw = keyring.get_password(
318
+ service_name=cli_settings.KEYRING_SERVICE, username=cli_settings.KEYRING_PATS_USERNAME
319
+ )
320
+ except KeyringError as e:
321
+ raw = None
322
+ logger.debug(f"Keyring read failed with error: {e}, falling back to file storage.")
323
+
324
+ if raw is not None:
325
+ try:
326
+ pat_dict = json.loads(raw)
327
+ return PATData(
328
+ name=pat_dict["name"],
329
+ pat=SecretStr(pat_dict["pat"]),
330
+ pat_expires_at=pat_dict["pat_expires_at"],
331
+ )
332
+ except (KeyError, json.JSONDecodeError) as e:
333
+ logger.debug(f"Keyring PAT data malformed: {e}")
334
+
335
+ if not pat_fallback_path.exists():
336
+ return None
337
+
338
+ with open(pat_fallback_path, "r") as file:
339
+ pat_dict = yaml.safe_load(file)
340
+
341
+ try:
342
+ pat_data = PATData(
343
+ name=pat_dict["name"],
344
+ pat=SecretStr(pat_dict["pat"]),
345
+ pat_expires_at=pat_dict["pat_expires_at"],
346
+ )
347
+ except (KeyError, TypeError) as e:
348
+ logger.debug(f"User PAT file at {pat_fallback_path} appears to be malformed: {e}")
349
+ return None
350
+
351
+ return pat_data
352
+
353
+
354
+ def get_pat_for_authentication() -> SecretStr | None:
355
+ """
356
+ Get a user's Personal Access Token (PAT) for authentication with the DivBase API.
357
+
358
+ Priority order:
359
+ 1. Environment variable
360
+ 2. OS keyring
361
+ 3. file with 0600 permissions fallback
362
+
363
+ Returns the PAT as a SecretStr if found and valid, else None.
364
+ """
365
+ pat = cli_settings.DIVBASE_API_PAT
366
+ if pat is not None:
367
+ return pat
368
+ pat_data = load_stored_user_pat()
369
+
370
+ if not pat_data:
371
+ return None
372
+
373
+ if pat_data.is_pat_expired():
374
+ raise AuthenticationError(PERSONAL_ACCESS_TOKEN_EXPIRED_MESSAGE)
375
+
376
+ return pat_data.pat
377
+
378
+
379
+ @stamina.retry(on=retry_only_on_retryable_divbase_api_errors, attempts=3)
380
+ def make_authenticated_request(
381
+ method: str,
382
+ divbase_base_url: str,
383
+ api_route: str,
384
+ token_path: Path = cli_settings.TOKENS_FALLBACK_PATH,
385
+ **kwargs,
386
+ ) -> httpx.Response:
387
+ """Make an authenticated request to the DivBase server, handles refreshing tokens if needed."""
388
+ headers = kwargs.get("headers", {})
389
+ headers[CLI_VERSION_HEADER_KEY] = cli_version
390
+
391
+ token_data = load_user_tokens(token_path=token_path)
392
+ if not token_data:
393
+ pat = get_pat_for_authentication()
394
+ if not pat:
395
+ raise AuthenticationError(LOGIN_AGAIN_MESSAGE)
396
+ logger.info("Using personal access token in request to DivBase API.")
397
+ headers["Authorization"] = f"Bearer {pat.get_secret_value()}"
398
+ else:
399
+ if token_data.is_access_token_expired():
400
+ if token_data.is_refresh_token_expired():
401
+ # Prevents user getting warning about being already logged in when they try to log in again
402
+ config = load_user_config()
403
+ config.set_login_status(url=None, email=None)
404
+ _delete_stored_jwts(token_path)
405
+ raise AuthenticationError(LOGIN_AGAIN_MESSAGE)
406
+ else:
407
+ token_data = _refresh_access_token(token_data=token_data, divbase_base_url=divbase_base_url)
408
+ headers["Authorization"] = f"Bearer {token_data.access_token.get_secret_value()}"
409
+
410
+ kwargs["headers"] = headers
411
+ url = f"{divbase_base_url}/{api_route.lstrip('/')}"
412
+
413
+ try:
414
+ response = httpx.request(method=method, url=url, **kwargs)
415
+ except httpx.HTTPError as e:
416
+ raise DivBaseAPIConnectionError() from e
417
+
418
+ try:
419
+ response.raise_for_status()
420
+ except httpx.HTTPStatusError:
421
+ _handle_divbase_api_error(response=response, http_method=method, url=url)
422
+
423
+ return response
424
+
425
+
426
+ @stamina.retry(on=retry_only_on_retryable_divbase_api_errors, attempts=3)
427
+ def make_unauthenticated_request(
428
+ method: str,
429
+ divbase_base_url: str,
430
+ api_route: str,
431
+ **kwargs,
432
+ ) -> httpx.Response:
433
+ """
434
+ Make an unauthenticated request to the DivBase server.
435
+ Used for those few endpoints that require no authentication, even if the user is logged in.
436
+ E.g. the announcements endpoint.
437
+ """
438
+ url = f"{divbase_base_url}/{api_route.lstrip('/')}"
439
+
440
+ headers = kwargs.get("headers", {})
441
+ headers[CLI_VERSION_HEADER_KEY] = cli_version
442
+ kwargs["headers"] = headers
443
+
444
+ try:
445
+ response = httpx.request(method=method, url=url, **kwargs)
446
+ except httpx.HTTPError as e:
447
+ raise DivBaseAPIConnectionError() from e
448
+
449
+ try:
450
+ response.raise_for_status()
451
+ except httpx.HTTPStatusError:
452
+ _handle_divbase_api_error(response=response, http_method=method, url=url)
453
+
454
+ return response
455
+
456
+
457
+ def _refresh_access_token(token_data: TokenData, divbase_base_url: str) -> TokenData:
458
+ """
459
+ Use the refresh token to get a new access token and update the token file.
460
+
461
+ Returns the new TokenData object which can be used immediately in a new request.
462
+ NOTE: We do not need retry logic inside this function as the calling function has it.
463
+ """
464
+ refresh_url = f"{divbase_base_url}/v1/auth/refresh"
465
+ try:
466
+ response = httpx.post(
467
+ url=refresh_url,
468
+ json={"refresh_token": token_data.refresh_token.get_secret_value()},
469
+ headers={CLI_VERSION_HEADER_KEY: cli_version},
470
+ )
471
+ except httpx.HTTPError as e:
472
+ raise DivBaseAPIConnectionError() from e
473
+
474
+ try:
475
+ response.raise_for_status()
476
+ except httpx.HTTPStatusError:
477
+ # Possible if e.g. token revoked on server side.
478
+ if response.status_code == 401:
479
+ # Clear logged in status in user config as tokens no longer valid.
480
+ # Prevents user getting warning about being already logged in when they try to log in again.
481
+ config = load_user_config()
482
+ config.set_login_status(url=None, email=None)
483
+ _delete_stored_jwts(token_path=cli_settings.TOKENS_FALLBACK_PATH)
484
+ raise AuthenticationError(LOGIN_AGAIN_MESSAGE) from None
485
+
486
+ _handle_divbase_api_error(response=response, http_method="POST", url=refresh_url)
487
+
488
+ data = response.json()
489
+
490
+ new_token_data = TokenData(
491
+ access_token=SecretStr(data["access_token"]),
492
+ refresh_token=token_data.refresh_token, # (refresh_token is still a SecretStr)
493
+ access_token_expires_at=data["expires_at"],
494
+ refresh_token_expires_at=token_data.refresh_token_expires_at,
495
+ )
496
+ new_token_data.dump_tokens()
497
+ return new_token_data
498
+
499
+
500
+ def _dump_to_keyring_or_file(data: dict[Any, Any], keyring_user_name: str, fallback_file_path: Path) -> None:
501
+ """
502
+ Helper fn to dump a dict to user's OS keyring.
503
+
504
+ If dump fails, will fallback to a local file and set permissions to 0600 (user read/write only).
505
+ Used to store both JWTs and PATs.
506
+ """
507
+ try:
508
+ keyring.set_password(
509
+ service_name=cli_settings.KEYRING_SERVICE,
510
+ username=keyring_user_name,
511
+ password=json.dumps(data),
512
+ )
513
+ fallback_file_path.unlink(missing_ok=True)
514
+ logger.debug(f"Data stored in user device keyring under username: {keyring_user_name}")
515
+ return
516
+ except KeyringError as e:
517
+ logger.debug(f"Keyring storage failed with error: {e}\n falling back to file storage.")
518
+
519
+ fallback_file_path.parent.mkdir(parents=True, exist_ok=True)
520
+ # Create file with 0600 permissions (user read/write only).
521
+ # Windows doesn't support 0600 permissions, but Windows can use keyring, so should never reach this fallback.
522
+ # Even if a Windows OS can't use keyring the fallback will still work, the 0600 mode will just be ignored.
523
+ fd = os.open(path=fallback_file_path, flags=os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=0o600)
524
+ with os.fdopen(fd, "w") as file:
525
+ yaml.safe_dump(data, file, sort_keys=False)
@@ -0,0 +1,177 @@
1
+ """
2
+ Handles the user's configuration file for the divbase-cli package.
3
+ The user configuration is stored in a local file.
4
+
5
+ The path to the config file is determined by `cli_settings.CONFIG_PATH` and
6
+ is stored in a platform-specific user configuration directory (for example,
7
+ under the user application data directory on Linux, macOS, or Windows).
8
+ """
9
+
10
+ import logging
11
+ import warnings
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ import yaml
16
+
17
+ from divbase_cli.cli_config import cli_settings
18
+ from divbase_cli.cli_exceptions import ProjectNotInConfigError
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @dataclass
24
+ class ProjectConfig:
25
+ """Config of a single project."""
26
+
27
+ name: str
28
+ divbase_url: str
29
+
30
+
31
+ @dataclass
32
+ class UserConfig:
33
+ """Overall user configuration"""
34
+
35
+ config_path: Path
36
+ logged_in_url: str | None = None # URL of the divbase server the user is currently logged in to, if any.
37
+ logged_in_email: str | None = None # Email the user is currently logged in with, if any.
38
+ projects: list[ProjectConfig] = field(default_factory=list)
39
+ default_project: str | None = None
40
+ # default_download_dir is a string (rather than Path) for easier loading/saving.
41
+ default_download_dir: str | None = None
42
+
43
+ @property
44
+ def all_project_names(self) -> list[str]:
45
+ """List of all project names in the user's config"""
46
+ return [project.name for project in self.projects]
47
+
48
+ def dump_config(self) -> None:
49
+ """
50
+ Dump the user configuration to the specified output path
51
+ Don't include the config_path in the dumped file.
52
+ """
53
+ config_dict = {
54
+ "logged_in_url": self.logged_in_url,
55
+ "logged_in_email": self.logged_in_email,
56
+ "projects": [project.__dict__ for project in self.projects],
57
+ "default_project": self.default_project,
58
+ "default_download_dir": self.default_download_dir,
59
+ }
60
+
61
+ with open(self.config_path, "w") as file:
62
+ yaml.safe_dump(config_dict, file, sort_keys=False)
63
+
64
+ def add_project(self, name: str, divbase_url: str, is_default: bool) -> ProjectConfig:
65
+ """
66
+ Add a new project to the user configuration file.
67
+ If the configuration file does not exist, it will be created.
68
+ """
69
+ new_project = ProjectConfig(name=name, divbase_url=divbase_url)
70
+
71
+ if new_project.name in self.all_project_names:
72
+ warnings.warn(
73
+ f"""The project: '{new_project.name}' already existed in your configuration file. It will be replaced with your new params""",
74
+ stacklevel=2,
75
+ )
76
+
77
+ self.projects = [project for project in self.projects if project.name != new_project.name]
78
+
79
+ self.projects.append(new_project)
80
+
81
+ if is_default:
82
+ self.default_project = new_project.name
83
+
84
+ self.dump_config()
85
+ return new_project
86
+
87
+ def set_default_project(self, name: str) -> str:
88
+ """
89
+ Set the default project in the user configuration file.
90
+ """
91
+ if name not in self.all_project_names:
92
+ raise ValueError(
93
+ f"The project name specified: '{name}', was not found in your config file, please add it first."
94
+ )
95
+ self.default_project = name
96
+ self.dump_config()
97
+ return self.default_project
98
+
99
+ def remove_project(self, name: str) -> str | None:
100
+ """
101
+ Remove a project from the user configuration file.
102
+ Returns the project name if it was removed successfully, otherwise None.
103
+ """
104
+ if name not in self.all_project_names:
105
+ return
106
+
107
+ self.projects = [project for project in self.projects if project.name != name]
108
+
109
+ if self.default_project == name:
110
+ self.default_project = None
111
+
112
+ self.dump_config()
113
+
114
+ return name
115
+
116
+ def set_default_download_dir(self, download_dir: str) -> str:
117
+ """
118
+ Set the default download directory in the user configuration file.
119
+ """
120
+ self.default_download_dir = download_dir
121
+ self.dump_config()
122
+ return self.default_download_dir
123
+
124
+ def project_info(self, name: str) -> ProjectConfig:
125
+ """
126
+ Get the project configuration given the project name.
127
+ """
128
+ for project in self.projects:
129
+ if project.name == name:
130
+ return project
131
+ raise ProjectNotInConfigError(project_name=name)
132
+
133
+ def set_login_status(self, url: str | None, email: str | None) -> None:
134
+ """
135
+ Used during login/logout to track state (Dumps config after updating)
136
+ Sets the following fields:
137
+ 1. URL of the DivBase server the user is currently logged in to.
138
+ 2. Email of the user currently logged in.
139
+ """
140
+ self.logged_in_url = url
141
+ self.logged_in_email = email
142
+ self.dump_config()
143
+
144
+
145
+ def load_user_config() -> UserConfig:
146
+ """Helper function to load the user config file"""
147
+ try:
148
+ with open(cli_settings.CONFIG_PATH, "r") as file:
149
+ config_contents = yaml.safe_load(file)
150
+ except FileNotFoundError:
151
+ logger.debug(f"No existing config file found at {cli_settings.CONFIG_PATH}, creating a new one.")
152
+ create_user_config(config_path=cli_settings.CONFIG_PATH)
153
+ with open(cli_settings.CONFIG_PATH, "r") as file:
154
+ config_contents = yaml.safe_load(file)
155
+
156
+ projects = [ProjectConfig(**project) for project in config_contents.get("projects", [])]
157
+
158
+ return UserConfig(
159
+ config_path=cli_settings.CONFIG_PATH,
160
+ logged_in_url=config_contents.get("logged_in_url"),
161
+ logged_in_email=config_contents.get("logged_in_email"),
162
+ projects=projects,
163
+ default_project=config_contents.get("default_project"),
164
+ default_download_dir=config_contents.get("default_download_dir"),
165
+ )
166
+
167
+
168
+ def create_user_config(config_path: Path) -> None:
169
+ """Create a user configuration file at the specified path."""
170
+ if config_path.exists():
171
+ raise FileExistsError(
172
+ f"Config file already exists at {config_path}. Stopping to avoid overwriting existing config."
173
+ )
174
+ config_path.parent.mkdir(parents=True, exist_ok=True)
175
+
176
+ user_config = UserConfig(config_path=config_path, projects=[])
177
+ user_config.dump_config()