Skip to content

Commit

Permalink
gitlab oauth testing in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
nheeb committed Oct 18, 2024
1 parent 8705663 commit 64a5dce
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 11 deletions.
10 changes: 7 additions & 3 deletions src/hermes/commands/deposit/invenio.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from hermes.model.context import CodeMetaContext
from hermes.model.path import ContextPath
from hermes.utils import hermes_user_agent
from hermes.commands.init.connect_with_zenodo import oauth_process
import hermes.commands.init.connect_with_zenodo as connect_zenodo


_log = logging.getLogger("cli.deposit.invenio")
Expand Down Expand Up @@ -268,11 +268,15 @@ def __init__(self, command: HermesDepositCommand, ctx: CodeMetaContext, client=N
# If auth_token is a refresh-token, get the auth-token from that.
if str(auth_token).startswith("REFRESH_TOKEN:"):
_log.debug(f"Getting token from refresh_token {auth_token}")
tokens = oauth_process().get_tokens_from_refresh_token(auth_token.split("REFRESH_TOKEN:")[1])
# TODO How do we know if this targets sandbox or not?
# Now we assume it's sandbox
connect_zenodo.setup(True)
tokens = connect_zenodo.oauth_process() \
.get_tokens_from_refresh_token(auth_token.split("REFRESH_TOKEN:")[1])
_log.debug(f"Tokens: {str(tokens)}")
auth_token = tokens.get("access_token", "")
_log.debug(f"Auth Token: {auth_token}")
# TODO Update the secret (github token is needed)
# TODO Update the secret (github/lab token is needed)
if not auth_token:
raise DepositionUnauthorizedError("No valid auth token given for deposition platform")
self.client = self.invenio_client_class(self.config,
Expand Down
19 changes: 14 additions & 5 deletions src/hermes/commands/init/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys
import requests
import toml
import re
from enum import Enum, auto
from urllib.parse import urlparse
from pathlib import Path
Expand Down Expand Up @@ -130,7 +131,7 @@ class HermesInitCommand(HermesCommand):
def __init__(self, parser: argparse.ArgumentParser):
super().__init__(parser)
self.folder_info: HermesInitFolderInfo = HermesInitFolderInfo()
self.tokens: dict[str: str] = {}
self.tokens: dict = {}
self.setup_method: str = ""
self.deposit_platform: DepositPlatform = DepositPlatform.Empty

Expand Down Expand Up @@ -160,7 +161,7 @@ def __call__(self, args: argparse.Namespace) -> None:

# Choosing setup method
self.setup_method = sc.choose(
f"How do you want to setup {self.deposit_platform.name} and the {self.folder_info.used_git_hoster.name} CI?",
f"How do you want to connect {self.deposit_platform.name} with your {self.folder_info.used_git_hoster.name} CI?",
{"a": "automatically (using OAuth / Device Flow)", "m": "manually (with instructions)"}, default="a"
)

Expand Down Expand Up @@ -303,8 +304,8 @@ def create_ci_template(self):
hermes_ci_template_url = ("https://raw.githubusercontent.com/softwarepub/ci-templates/refs/heads/"
"feature/init-command/gitlab/hermes-ci.yml")
gitlab_ci_path = Path(".gitlab-ci.yml")
Path(".gitlab").mkdir(parents=True, exist_ok=True)
hermes_ci_path = Path(".gitlab") / "hermes-ci.yml"
Path("gitlab").mkdir(parents=True, exist_ok=True)
hermes_ci_path = Path("gitlab") / "hermes-ci.yml"
if gitlab_ci_path.exists():
if string_in_file(gitlab_ci_path, "hermes-ci.yml"):
sc.echo(f"It seems like your {gitlab_ci_path} file is already configured for hermes.")
Expand All @@ -315,13 +316,21 @@ def create_ci_template(self):
download_file_from_url(gitlab_ci_template_url, gitlab_ci_path)
sc.echo(f"{gitlab_ci_path} was created.")
download_file_from_url(hermes_ci_template_url, hermes_ci_path)
# When using gitlab.com we need to use gitlab-org-docker as tag
# TODO make this cleaner
if "gitlab.com" in self.folder_info.git_remote_url:
with open(hermes_ci_path, 'r') as file:
content = file.read()
new_content = re.sub(r'(tags:\n\s+- )docker', r'\1gitlab-org-docker', content)
with open(hermes_ci_path, 'w') as file:
file.write(new_content)
sc.echo(f"{hermes_ci_path} was created.")

def get_zenodo_token(self, sandbox: bool = True):
self.tokens[self.deposit_platform] = ""
if self.setup_method == "a":
connect_zenodo.setup(sandbox)
self.tokens[self.deposit_platform] = connect_zenodo.get_refresh_token()
self.tokens[self.deposit_platform] = "REFRESH_TOKEN:" + connect_zenodo.get_refresh_token()
if self.tokens[self.deposit_platform]:
sc.echo("OAuth at Zenodo was successful.")
sc.echo(self.tokens[self.deposit_platform], debug=True)
Expand Down
2 changes: 1 addition & 1 deletion src/hermes/commands/init/oauth_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def get_tokens_from_device_flow(self) -> dict[str: str]:

# User has to open the url and enter the code
if verification_uri_complete:
sc.echo(f"Open {verification_uri_complete} and confirm the code ({user_code})")
sc.echo(f"Open {verification_uri_complete} and confirm the code.")
else:
sc.echo(f"Open {verification_uri} and enter this code: {user_code}")

Expand Down
4 changes: 2 additions & 2 deletions src/hermes/commands/init/slim_click.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
Slim, self-made version of click so we don't need to use it for simple console questions.
"""

PRINT_DEBUG = True
PRINT_DEBUG = False
"""If this is true, echo() will print texts with debug=True."""


Expand Down Expand Up @@ -63,7 +63,7 @@ def choose(text: str, options: dict[str, str], default: str = "") -> str:
for char, description in options.items():
char = char.lower().strip()
if char == default.lower():
description += " (default)"
description += " [default]"
print(f"[{char}] {description}")
while True:
_answer = input("Your choice: ").lower().strip()
Expand Down

0 comments on commit 64a5dce

Please sign in to comment.