add authentication for kontor-scripts
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
"""
|
||||
Setup database connections
|
||||
"""
|
||||
from logging import Logger
|
||||
import sqlite3
|
||||
from typing import Any, Dict
|
||||
import psycopg2
|
||||
import logging.config
|
||||
from platformdirs import PlatformDirs
|
||||
from pathlib import Path
|
||||
import requests
|
||||
import yaml
|
||||
|
||||
|
||||
@@ -54,3 +57,37 @@ def get_logger(level, config: str):
|
||||
logger.setLevel(logging.INFO)
|
||||
return logger
|
||||
|
||||
def get_api_config(log: Logger, config: str) -> Dict[str, Any]:
|
||||
api_data: Dict[str, Any] = {}
|
||||
token: str | None = None
|
||||
host: str | None = None
|
||||
port: int = 0
|
||||
dirs = PlatformDirs(config)
|
||||
api_config = Path(dirs.user_config_dir, 'api.yaml')
|
||||
with open(api_config, 'rt') as f:
|
||||
api_data = yaml.safe_load(f.read())
|
||||
if not api_data:
|
||||
log.fatal("API configuration is missing")
|
||||
return api_data
|
||||
host = api_data["host"]
|
||||
port = api_data["login_port"]
|
||||
if not token:
|
||||
log.info("Call login first")
|
||||
login_url = f"http://{host}:{port}/login"
|
||||
login_data = {}
|
||||
login_data['user'] = api_data["user"]
|
||||
login_data['pass'] = api_data["pass"]
|
||||
response = requests.post(login_url, data=login_data)
|
||||
status = response.status_code
|
||||
log.info(f"Status: {status}")
|
||||
if status != 200:
|
||||
log.fatal("authentication failed")
|
||||
return api_data
|
||||
data = response.json()
|
||||
token = data['token']
|
||||
api_data['token'] = token
|
||||
with open(api_config, 'w') as f:
|
||||
yaml.dump(api_data, f)
|
||||
else:
|
||||
token = api_data['token']
|
||||
return api_data
|
||||
|
||||
Reference in New Issue
Block a user