Skip to content

Commit

Permalink
fix: Writing auth token file when logging in with token (#268)
Browse files Browse the repository at this point in the history
* fix: Writing auth token file when logging in with token

* Pass in config, guard write in try/except

* Fix changelog
  • Loading branch information
pederhan authored Dec 4, 2024
1 parent cbe83c2 commit 81b9e2e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed

- Ordering of User commands in the help output.
- Auth token file being written when logging in with a token.
- Custom auth token file path not being used when writing auth token file.

## [3.4.0](https://github.com/unioslo/zabbix-cli/releases/tag/3.4.0) - 2024-11-28

Expand Down
21 changes: 17 additions & 4 deletions zabbix_cli/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,10 @@ def login(self) -> ZabbixAPI:
self.config.api.url = self.get_zabbix_url()
client = ZabbixAPI.from_config(self.config)
info = self._do_login(client)
if self.config.app.use_auth_token_file:
write_auth_token_file(self.config.api.username, info.token)
if info.credentials.username and self.config.app.use_auth_token_file:
write_auth_token_file(
info.credentials.username, info.token, self.config.app.auth_token_file
)

if info.credentials.username:
add_user(info.credentials.username)
Expand Down Expand Up @@ -411,6 +413,14 @@ def write_auth_token_file(
username: str, auth_token: str, file: Path = AUTH_TOKEN_FILE
) -> Path:
"""Write a username/auth token pair to the auth token file."""
if not username or not auth_token:
logger.error(
"Cannot write auth token file without both a username (%s) and token (%s).",
username,
auth_token,
)
return file

contents = f"{username}::{auth_token}"
if not file.exists():
try:
Expand All @@ -428,8 +438,11 @@ def write_auth_token_file(
f"Unable to set secure permissions ({SECURE_PERMISSIONS_STR}) on {file} when saving auth token. "
"Change permissions manually or delete the file."
) from e
file.write_text(contents)
logger.info(f"Wrote auth token file {file}")
try:
file.write_text(contents)
logger.info(f"Wrote auth token file {file}")
except OSError as e:
raise AuthTokenFileError(f"Unable to write auth token file {file}: {e}") from e
return file


Expand Down

0 comments on commit 81b9e2e

Please sign in to comment.