Merge remote-tracking branch 'origin/dev' into publications-and-topics
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-07-07 01:08:55 +02:00
42 changed files with 3590 additions and 816 deletions
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
"news_id": entry["news_id"],
"relevant": int(entry["relevant"]),
"authors": entry["authors"],
"keywords": entry.get("keywords", []),
}
response_data = _send_es_request("POST", endpoint, payload=document_body)
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
return created_id
def update_entry(index: str, document_id: str, partial_doc: dict):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
def get_entry(index: str, document_id: str) -> dict:
encoded_document_id = quote(document_id, safe="")
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
"query": {"match_all": {}}
}
return _send_es_request("POST", endpoint, payload=payload)
def remove_field_all(index: str, field: str):
endpoint = f"{INSE_URL}/{index}/_update_by_query"
payload = {
"query": {"exists": {"field": field}},
"script": {
"source": f"ctx._source.remove('{field}')",
"lang": "painless",
},
}
return _send_es_request("POST", endpoint, payload=payload)
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
SYSTEM_PROMPT_KEYWORDS = ("""
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
_client = OpenAI(
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
return data.get("person", [])
except json.JSONDecodeError:
return []
def extract_keywords(text: str) -> list[str]:
result = call(SYSTEM_PROMPT_KEYWORDS, text)
if result is None:
return []
try:
import json
data = json.loads(result)
return data.get("keywords", [])
except json.JSONDecodeError:
return []
+81 -2
View File
@@ -16,10 +16,12 @@ def sync_single_news(news_id, max_retries=3):
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
is_news_relevant = llm_client.is_news_relevant(news_text)
authors = llm_client.extract_names(news_text)
keywords = llm_client.extract_keywords(news_text)
new_entry = {
"news_id": news_id,
"relevant": is_news_relevant,
"authors": authors,
"keywords": keywords,
}
es_client.add_entry("aktuell_postproc", new_entry)
return True
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
print(f"Error: {news_id} - {error}")
return False
def update_keywords_single(postproc_entry, max_retries=3):
doc_id = postproc_entry["_id"]
news_id = postproc_entry["_source"]["news_id"]
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
keywords = llm_client.extract_keywords(news_text)
es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords})
return True
except Exception as error:
attempt += 1
print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
if attempt < max_retries:
time.sleep(1)
else:
print(f"Error: {news_id} - {error}")
return False
def main():
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
@@ -47,6 +68,18 @@ def main():
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
)
parser.add_argument(
"--update-keywords",
action="store_true",
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
)
parser.add_argument(
"--reset-keywords",
action="store_true",
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
)
parser.add_argument(
"--stats",
action="store_true",
@@ -60,11 +93,22 @@ def main():
help="Number of threads for --sync-delta (Default: 4).",
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
)
args = parser.parse_args()
if args.delete_all:
es_client.delete_all_entries("aktuell_postproc")
if args.reset_keywords:
result = es_client.remove_field_all("aktuell_postproc", "keywords")
print(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
if args.sync_delta:
start_time = time.time()
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
@@ -96,23 +140,58 @@ def main():
end_time = time.time()
print(f"Sync DONE: {succeeded} entries synced.")
print(f"Time taken: {end_time - start_time} seconds.")
if args.update_keywords:
start_time = time.time()
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"])
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
print(f"Number of entries without keywords: {len(pending)}")
if args.limit is not None:
pending = pending[:args.limit]
total = len(pending)
print(f"Processing {total} entries.")
processed = 0
succeeded = 0
progress_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = [executor.submit(update_keywords_single, entry) for entry in pending]
for future in as_completed(futures):
was_successful = future.result()
with progress_lock:
processed += 1
if was_successful:
succeeded += 1
print(f"Update keywords: {processed} / {total}")
end_time = time.time()
print(f"Update keywords DONE: {succeeded} entries updated.")
print(f"Time taken: {end_time - start_time} seconds.")
if args.stats:
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors"])
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
total_entries = len(postproc_entries)
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
irrelevant_count = total_entries - relevant_count
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
news_without_extracted_names = total_entries - news_with_extracted_names
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
news_without_keywords = total_entries - news_with_keywords
print(f"Total entries in 'aktuell_postproc': {total_entries}")
print(f"Relevant entries: {relevant_count}")
print(f"Irrelevant entries: {irrelevant_count}")
print(f"Entries with extracted names: {news_with_extracted_names}")
print(f"Entries without extracted names: {news_without_extracted_names}")
print(f"Entries with keywords: {news_with_keywords}")
print(f"Entries without keywords: {news_without_keywords}")
if __name__ == "__main__":
main()
File diff suppressed because one or more lines are too long
+26 -1
View File
@@ -4,6 +4,7 @@ from enum import StrEnum
from typing import List
from pydantic import BaseModel
from sqlalchemy import UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
@@ -20,6 +21,11 @@ class TokenType(StrEnum):
ACCESS_TOKEN = "ACCESS_TOKEN"
class SecretPurpose(StrEnum):
LOGIN_OTK = "LOGIN_OTK"
PASSWORD_RESET = "PASSWORD_RESET"
class Durable(SQLModel):
deleted: bool = Field(
default=False,
@@ -106,6 +112,9 @@ class Account(Durable, table=True):
class Secret(SQLModel, table=True):
__table_args__ = (
UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
)
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
@@ -113,10 +122,16 @@ class Secret(SQLModel, table=True):
)
account_id: uuid.UUID = Field(
foreign_key="account.id",
unique=True, # Ensure that each account can have only one associated secret
index=True,
nullable=False,
description="The unique identifier of the account associated with this secret.",
)
purpose: SecretPurpose = Field(
default=SecretPurpose.LOGIN_OTK,
index=True,
nullable=False,
description="The purpose of the secret, such as login OTK or password reset.",
)
secret_value: str = Field(
index=False,
nullable=False,
@@ -127,6 +142,16 @@ class Secret(SQLModel, table=True):
nullable=False,
description="The timestamp indicating when the secret will expire.",
)
request_count: int = Field(
default=0,
nullable=False,
description="The number of password reset requests in the current rate-limit window.",
)
request_window_started_at: datetime | None = Field(
default=None,
index=True,
description="The start timestamp of the current password reset request window.",
)
class BaseTokenData(BaseModel):
+40
View File
@@ -46,6 +46,46 @@ async def request_otk(
return auth_service.request_otk(session=session, email=email, password=password)
@router.post(
"/request-password-reset",
summary="Request Password Reset",
description="Request a one-time password reset link for the given email address.",
operation_id="requestPasswordReset",
responses={
status.HTTP_200_OK: {"description": "Password reset requested successfully."}
},
)
async def request_password_reset(
session: SessionDep,
email: Annotated[str, Body(embed=True, description="User's email address")],
):
return auth_service.request_password_reset(session=session, email=email)
@router.post(
"/reset-password",
summary="Reset Password",
description="Reset the user's password using a one-time password reset token.",
operation_id="resetPassword",
responses={status.HTTP_200_OK: {"description": "Password reset successfully."}},
)
async def reset_password(
session: SessionDep,
reset_token: Annotated[
str, Body(description="Password reset token from the reset link")
],
new_password: Annotated[
str,
Body(description="New password", min_length=8, example="NewPassword123"),
],
):
return auth_service.reset_password(
session=session,
reset_token=reset_token,
new_password=new_password,
)
@router.post(
"/login",
summary="Login with One-Time Key",
+245 -4
View File
@@ -11,6 +11,9 @@ from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from fastapi import Cookie, Depends, HTTPException, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlmodel import Session, func, select
from inse.auth.email_service import send_email
from inse.auth.model import (
AccessResponse,
AccessToken,
@@ -22,19 +25,21 @@ from inse.auth.model import (
OtkResponse,
RefreshTokenMetadata,
Secret,
SecretPurpose,
TokenType,
UserRole,
)
from inse.config import get_settings
from inse.database import get_session
from sqlmodel import Session, select, func
from inse.auth.email_service import send_email
ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
PASSWORD_RESET_EXPIRATION_MINUTES = 5 # 5 minutes
PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES = 5 # 5 minutes
PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
REAL_ACCOUNT_ID_KEY = "real_account_id"
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
@@ -160,7 +165,32 @@ def _verify_password(password: str, password_hash: str) -> bool:
return False
def request_otk(session: Session, email: str, password: str) -> OtkResponse:
def _hash_reset_token(reset_token: str) -> str:
"""Hashes a high-entropy password reset token for storage.
Args:
reset_token (str): The raw reset token sent to the user.
Returns:
str: SHA-256 hash of the reset token.
"""
return hashlib.sha256(reset_token.encode("utf-8")).hexdigest()
def _build_password_reset_link(reset_token: str) -> str:
"""Builds the password reset link that will be sent to the user.
Args:
reset_token (str): The raw reset token to include in the link.
Returns:
str: The full password reset link.
"""
separator = "&" if "?" in settings.password_reset_url else "?"
return f"{settings.password_reset_url}{separator}token={reset_token}"
def request_otk(session: Session, email: str, password: str):
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
Args:
@@ -211,7 +241,12 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
otk_code = f"{secrets.randbelow(1_000_000):06d}"
print(otk_code)
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
secret = session.exec(
select(Secret).where(
Secret.account_id == account.id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
)
).first()
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=OTK_EXPIRATION_MINUTES
@@ -220,6 +255,7 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
if secret is None:
secret = Secret(
account_id=account.id,
purpose=SecretPurpose.LOGIN_OTK,
secret_value=otk_code,
expires_at=expires_at,
)
@@ -251,6 +287,210 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
return OtkResponse(status="success", account_id=account.id)
def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
"""Requests a one-time password reset link for the given email address.
For security reasons, this function always returns a successful response and
does not reveal whether the email address belongs to an active account.
"""
email = email.lower().strip()
now = datetime.datetime.now(datetime.timezone.utc)
account = session.exec(
select(Account).where(
Account.email == email,
Account.deleted == False, # noqa: E712
)
).first()
if account is None or account.deleted or account.id is None:
logger.info("Password reset requested for unknown email %s", email)
return {
"status": "ok",
"reset_link_created": False,
"rate_limited": False,
}
secret = session.exec(
select(Secret).where(
Secret.account_id == account.id,
Secret.purpose == SecretPurpose.PASSWORD_RESET,
)
).first()
if secret is not None:
if secret.request_window_started_at is not None:
window_started_at = secret.request_window_started_at
if getattr(window_started_at, "tzinfo", None) is None:
window_started_at = window_started_at.replace(
tzinfo=datetime.timezone.utc
)
window_ends_at = window_started_at + datetime.timedelta(
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
)
if window_ends_at > now:
if secret.request_count >= PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW:
retry_after_seconds = max(
0,
int((window_ends_at - now).total_seconds()),
)
logger.info(
"Password reset request rate-limited for account %s.",
account.id,
)
return {
"status": "ok",
"reset_link_created": False,
"rate_limited": True,
"retry_after_seconds": retry_after_seconds,
}
else:
secret.request_count = 0
secret.request_window_started_at = now
else:
secret.request_count = 0
secret.request_window_started_at = now
reset_token = secrets.token_urlsafe(32)
reset_token_hash = _hash_reset_token(reset_token)
expires_at = now + datetime.timedelta(minutes=PASSWORD_RESET_EXPIRATION_MINUTES)
if secret is None:
secret = Secret(
account_id=account.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=reset_token_hash,
expires_at=expires_at,
request_count=1,
request_window_started_at=now,
)
session.add(secret)
else:
secret.secret_value = reset_token_hash
secret.expires_at = expires_at
secret.request_count += 1
if secret.request_window_started_at is None:
secret.request_window_started_at = now
session.commit()
reset_link = _build_password_reset_link(reset_token)
if settings.send_password_reset_email:
try:
send_email(
recipient=account.email,
subject="Reset your SmartGUIDE password",
body=(
"Use the following link to reset your SmartGUIDE password:\n"
f"{reset_link}\n\n"
f"This link expires in {PASSWORD_RESET_EXPIRATION_MINUTES} minutes."
),
smtp_server=settings.smtp_server,
smtp_port=settings.smtp_port,
sender=settings.smtp_sender,
username=settings.smtp_username,
password=settings.smtp_password,
use_tls=settings.smtp_use_tls,
)
logger.info("Sent password reset email for account %s", account.id)
except Exception:
if settings.environment == "dev":
logger.exception(
"Failed to send password reset email for account %s. "
"Falling back to console reset link.",
account.id,
)
logger.info(
"Password reset link for account %s: %s",
account.id,
reset_link,
)
else:
raise
elif settings.environment == "dev":
logger.info("Password reset link for account %s: %s", account.id, reset_link)
else:
logger.info("Password reset token generated for account %s", account.id)
return {
"status": "ok",
"reset_link_created": True,
"rate_limited": False,
}
def reset_password(
session: Session,
reset_token: str,
new_password: str,
) -> Dict[str, str]:
"""Resets an account password using a one-time password reset token.
Args:
session (Session): The database session used to query the account and secret.
reset_token (str): The raw reset token from the password reset link.
new_password (str): The new password to store for the account.
Raises:
HTTPException: If the reset token is invalid or expired.
Returns:
Dict[str, str]: A status response.
"""
now = datetime.datetime.now(datetime.timezone.utc)
reset_token_hash = _hash_reset_token(reset_token.strip())
secret = session.exec(
select(Secret).where(
Secret.purpose == SecretPurpose.PASSWORD_RESET,
Secret.secret_value == reset_token_hash,
)
).first()
if secret is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired password reset token",
)
secret_expires = secret.expires_at
if getattr(secret_expires, "tzinfo", None) is None:
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
if secret_expires <= now:
session.delete(secret)
session.commit()
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired password reset token",
)
account = session.get(Account, secret.account_id)
if account is None or account.deleted or account.id is None:
session.delete(secret)
session.commit()
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired password reset token",
)
account.password_hash = _hash_password(new_password)
account.epoch += 1
session.add(account)
session.delete(secret)
session.commit()
return {"status": "ok"}
def login(
session: Session, response: Response, account_id: uuid.UUID, email_code: str
) -> LoginResponse:
@@ -274,6 +514,7 @@ def login(
secret = session.exec(
select(Secret).where(
Secret.account_id == account_id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
Secret.secret_value == email_code,
# Validating the code and ensuring it matches the account ID
)
+204 -6
View File
@@ -14,6 +14,7 @@ from inse.auth.model import (
Account,
Organization,
Secret,
SecretPurpose,
AccessToken,
IdTokenMetadata,
AccessTokenMetadata,
@@ -98,7 +99,10 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
assert resp.account_id == acc.id
secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
)
).first()
assert secret is not None
@@ -281,7 +285,12 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
assert acc.id is not None
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
secret = Secret(
account_id=acc.id,
purpose=SecretPurpose.LOGIN_OTK,
secret_value="000000",
expires_at=expired_at,
)
in_memory_session.add(secret)
in_memory_session.commit()
@@ -426,14 +435,20 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
auth_service.request_otk(in_memory_session, email, password)
secret1 = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
)
).first()
assert secret1 is not None
first_value = secret1.secret_value
auth_service.request_otk(in_memory_session, email, password)
secret2 = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
)
).first()
assert secret2 is not None
@@ -460,13 +475,19 @@ def test_otk_deleted_after_login(in_memory_session, settings_backup):
auth_service.request_otk(in_memory_session, email, password)
secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
)
).first()
assert secret is not None
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
post = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.LOGIN_OTK,
)
).first()
assert post is None
@@ -551,3 +572,180 @@ def test_get_account_epoch_not_found(in_memory_session):
random_id = uuid.uuid4()
with pytest.raises(Exception):
auth_service._get_account_epoch(in_memory_session, random_id)
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
email = "reset@example.com"
password = "oldpw123"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
result = auth_service.request_password_reset(in_memory_session, email)
assert result["status"] == "ok"
secret = in_memory_session.exec(
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.PASSWORD_RESET,
)
).first()
assert secret is not None
assert secret.secret_value is not None
assert secret.secret_value != ""
assert secret.secret_value != password
def test_request_password_reset_unknown_email_is_safe(
in_memory_session, settings_backup, monkeypatch
):
sent_emails = []
def fake_send_email(**kwargs):
sent_emails.append(kwargs)
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
config_module.settings.send_password_reset_email = True
result = auth_service.request_password_reset(
in_memory_session, "missing@example.com"
)
assert result["status"] == "ok"
assert sent_emails == []
def test_request_password_reset_sends_email(
in_memory_session, settings_backup, monkeypatch
):
email = "mail-reset@example.com"
password = "oldpw123"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
sent_emails = []
def fake_send_email(**kwargs):
sent_emails.append(kwargs)
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
config_module.settings.send_password_reset_email = True
config_module.settings.password_reset_url = "http://localhost/reset-password"
result = auth_service.request_password_reset(in_memory_session, email)
assert result["status"] == "ok"
assert len(sent_emails) == 1
assert sent_emails[0]["recipient"] == email
assert "token=" in sent_emails[0]["body"]
def test_reset_password_changes_password_and_increments_epoch(in_memory_session):
email = "do-reset@example.com"
password = "oldpw123"
new_password = "NewPassword123"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
reset_token = "valid-reset-token"
secret = Secret(
account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token),
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
)
in_memory_session.add(secret)
in_memory_session.commit()
old_epoch = acc.epoch
result = auth_service.reset_password(
in_memory_session,
reset_token=reset_token,
new_password=new_password,
)
assert result["status"] == "ok"
in_memory_session.refresh(acc)
assert auth_service._verify_password(new_password, acc.password_hash)
assert acc.epoch == old_epoch + 1
deleted_secret = in_memory_session.exec(
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.PASSWORD_RESET,
)
).first()
assert deleted_secret is None
def test_reset_password_rejects_reused_token(in_memory_session):
email = "reuse-reset@example.com"
password = "oldpw123"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
reset_token = "single-use-token"
secret = Secret(
account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token),
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
)
in_memory_session.add(secret)
in_memory_session.commit()
auth_service.reset_password(
in_memory_session,
reset_token=reset_token,
new_password="NewPassword123",
)
with pytest.raises(HTTPException):
auth_service.reset_password(
in_memory_session,
reset_token=reset_token,
new_password="AnotherPassword123",
)
def test_reset_password_rejects_invalid_token(in_memory_session):
with pytest.raises(HTTPException):
auth_service.reset_password(
in_memory_session,
reset_token="invalid-token",
new_password="NewPassword123",
)
def test_reset_password_rejects_expired_token(in_memory_session):
email = "expired-reset@example.com"
password = "oldpw123"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
reset_token = "expired-token"
secret = Secret(
account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token),
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
)
in_memory_session.add(secret)
in_memory_session.commit()
with pytest.raises(HTTPException):
auth_service.reset_password(
in_memory_session,
reset_token=reset_token,
new_password="NewPassword123",
)
deleted_secret = in_memory_session.exec(
select(Secret).where(
Secret.account_id == acc.id,
Secret.purpose == SecretPurpose.PASSWORD_RESET,
)
).first()
assert deleted_secret is None
+2
View File
@@ -70,6 +70,8 @@ class Settings(BaseSettings):
skip_otk_validation: bool = True
# SMTP / email config
send_otk_email: bool = False
send_password_reset_email: bool = True
password_reset_url: str = "http://localhost:4200/inse-webapp/reset-password"
smtp_server: str = "localhost"
smtp_port: int = 25
smtp_sender: str = "no-reply@smartguide.local"
+2
View File
@@ -36,6 +36,8 @@ class ESIndex(StrEnum):
OPENALEX_PUBLICATIONS = "openalex-publications"
OPENALEX_COUNTRIES = "openalex-countries"
OPENALEX_CONTINENTS = "openalex-continents"
OPENALEX_TOPICS = "openalex-topics"
OPENALEX_TOPIC_VECTORS = "topicvectors"
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
Binary file not shown.
+48 -19
View File
@@ -12,7 +12,8 @@ from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
from ..topics.logic import vector_search_topics
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
logger = logging.getLogger(__name__)
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
TOPIC_QUERY_CONTENT_CHARS = 300
TOPIC_NUM_CANDIDATES = 100
TOPIC_SIMILARITY = 0.5
TOPIC_MATCHES_PER_KEYWORD = 1
KEYWORD_LIMIT = 6
KEYWORD_CONTENT_CHARS = 4000
KEYWORD_SYSTEM_PROMPT = """\
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
"""
RELATED_BLOCK_SIZE = 5
@@ -247,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
source = response.get("_source", {})
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
keywords = await _get_article_keywords(
news_id,
postproc_id,
@@ -255,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
source.get("maintitle"),
source.get("full_content"),
)
topics = await _match_topics_for_keywords(keywords)
return NewsArticleDetail(
id=response.get("_id"),
@@ -265,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
full_content=source.get("full_content"),
relevant=relevant,
authors=await _build_mentioned_persons(authors),
topics=topics,
keywords=keywords,
topics=topics,
)
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
query = " ".join(
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
).strip()
if not query:
return []
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
return [topic["display_name"] for topic in topics if topic.get("display_name")]
async def _get_article_keywords(
news_id: str,
postproc_id: str | None,
@@ -315,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
try:
parsed = json.loads(raw)
candidates = parsed if isinstance(parsed, list) else []
if isinstance(parsed, list):
candidates = parsed
elif isinstance(parsed, dict):
candidates = parsed.get("keywords", [])
else:
candidates = []
except (json.JSONDecodeError, TypeError):
candidates = re.split(r"[,\n]", raw)
@@ -350,6 +350,35 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list)
logger.exception(f"Failed to cache keywords for {news_id}.")
async def _match_topics_for_keywords(keywords: list) -> list:
matched = []
seen_ids = set()
for keyword in keywords:
try:
response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD)
except Exception:
logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.")
continue
for topic in response.results or []:
if not topic.id or topic.id in seen_ids:
continue
seen_ids.add(topic.id)
matched.append(
MatchedTopic(
id=topic.id,
display_name=topic.display_name,
subfield_name=topic.subfield.display_name if topic.subfield else None,
field_name=topic.var_field.display_name if topic.var_field else None,
domain_name=topic.domain.display_name if topic.domain else None,
source_keyword=keyword,
)
)
return matched
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
try:
from ..util import get_model
+10 -1
View File
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
person_id: Optional[str] = None
class MatchedTopic(BaseModel):
id: Optional[str] = None
display_name: Optional[str] = None
subfield_name: Optional[str] = None
field_name: Optional[str] = None
domain_name: Optional[str] = None
source_keyword: Optional[str] = None
class NewsArticleDetail(NewsArticle):
full_content: Optional[str] = None
relevant: Optional[bool] = None
authors: List[MentionedPerson] = []
topics: List[str] = []
keywords: List[str] = []
topics: List[MatchedTopic] = []
class NewsPage(BaseModel):
+116 -26
View File
@@ -4,13 +4,12 @@
Business logic for OpenAlex topics.
"""
import asyncio
import logging
from copy import deepcopy
from typing import Any
import httpx
import asyncio
from pydantic import ValidationError
from inse.exceptions import (
UpstreamAPIException,
BadRequestException,
@@ -23,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import (
AutocompleteResponseResultsInner,
)
from inse.models.openalex.topics_list_response import TopicsListResponse
from inse.model import ESCluster
from .search_client import OpenAlexTopicsClient
from inse.model import ESCluster, ESIndex
from .search_client import TopicsSearchClient
logger = logging.getLogger(__name__)
@@ -40,15 +39,15 @@ async def list_topics(
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
client: OpenAlexTopicsClient | None = None,
client: TopicsSearchClient | None = None,
) -> TopicsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise BadRequestException("sample cannot be combined with sort or page.")
openalex_client = client or OpenAlexTopicsClient()
topics_client = client or TopicsSearchClient()
try:
data = await openalex_client.list_topics(
data = await topics_client.list_topics(
search=search,
filter=filter,
sort=sort,
@@ -59,25 +58,24 @@ async def list_topics(
sample=sample,
select=select,
)
except httpx.HTTPStatusError as exc:
status_code = exc.response.status_code
detail = "OpenAlex topics request failed."
try:
error_body = exc.response.json()
detail = error_body.get("message") or error_body.get("error") or detail
except ValueError:
if exc.response.text:
detail = exc.response.text
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex topics request failed.")
except ValueError as exc:
raise BadRequestException(str(exc)) from exc
except ElasticsearchException as exc:
logger.exception("OpenAlex topics Elasticsearch request failed.")
raise UpstreamAPIException(
message="OpenAlex topics request failed.",
message="OpenAlex topics Elasticsearch request failed.",
status_code=502,
) from exc
try:
normalized_data = _normalize_topics_response(data)
openalex_style_data = _elasticsearch_to_topics_response(
data,
per_page=per_page,
page=page,
cursor=cursor,
group_by=group_by,
)
normalized_data = _normalize_topics_response(openalex_style_data)
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("OpenAlex topics response could not be parsed.")
@@ -94,7 +92,7 @@ async def autocomplete_topics(
field_id: str | None = None,
subfield_id: str | None = None,
limit: int = 10,
client: OpenAlexTopicsClient | None = None,
client: TopicsSearchClient | None = None,
) -> AutocompleteResponse:
filters = []
if domain_id:
@@ -153,6 +151,99 @@ async def autocomplete_topics(
)
def _elasticsearch_to_topics_response(
data: dict[str, Any],
*,
per_page: int,
page: int | None,
cursor: str | None,
group_by: str | None,
) -> dict[str, Any]:
"""
Converts an Elasticsearch search response into the OpenAlex-style topics
response expected by TopicsListResponse.
Elasticsearch response shape:
{
"took": 12,
"hits": {
"total": {"value": 123},
"hits": [
{"_source": {...}, "sort": [...]}
]
},
"aggregations": {...}
}
OpenAlex-style response shape:
{
"meta": {...},
"results": [...],
"group_by": [...]
}
"""
hits_root = data.get("hits") or {}
raw_hits = hits_root.get("hits") or []
total = hits_root.get("total")
if isinstance(total, dict):
count = total.get("value")
else:
count = total
results: list[dict[str, Any]] = []
for hit in raw_hits:
if not isinstance(hit, dict):
continue
source = hit.get("_source")
if isinstance(source, dict):
results.append(source)
groups = _extract_group_by_results(data) if group_by else []
meta = {
"count": count,
"db_response_time_ms": data.get("took"),
"page": page if cursor is None else None,
"per_page": per_page,
"groups_count": len(groups) if group_by else None,
"next_cursor": (data.get("meta") or {}).get("next_cursor"),
"cost_usd": None,
}
return {
"meta": meta,
"results": results,
"group_by": groups,
}
def _extract_group_by_results(data: dict[str, Any]) -> list[dict[str, Any]]:
aggregations = data.get("aggregations") or {}
group_by_agg = aggregations.get("group_by") or {}
buckets = group_by_agg.get("buckets") or []
groups: list[dict[str, Any]] = []
for bucket in buckets:
if not isinstance(bucket, dict):
continue
key = bucket.get("key")
groups.append(
{
"key": key,
"key_display_name": bucket.get("key_as_string") or key,
"count": bucket.get("doc_count"),
}
)
return groups
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
normalized = deepcopy(data)
@@ -264,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None:
return f"{text}T00:00:00Z"
return text
# Configuration for vector search similarity thresholds and boosts
SIMILARITY_THRESHOLD = (
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
@@ -388,7 +478,7 @@ async def vector_search_topics(
try:
raw_results = await elasticsearch.search(
index="topicvectors", body=body, cluster=ESCluster.NES
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
)
except Exception as exc:
logger.exception("Elasticsearch vector search failed with unexpected error.")
@@ -458,7 +548,7 @@ async def vector_search_topics_batch(
)
tasks.append(
elasticsearch.search(
index="topicvectors", body=body, cluster=ESCluster.NES
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
)
)
+306 -56
View File
@@ -1,33 +1,200 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for OpenAlex topics.
Elasticsearch search client for OpenAlex topics.
"""
from __future__ import annotations
import base64
import json
from typing import Any
import httpx
from inse.model import ESCluster, ESIndex
from .. import config
from inse.integrations.elasticsearch import search as elasticsearch_search
class OpenAlexTopicsClient:
class TopicsSearchClient:
"""
Search client for OpenAlex topics backed by Elasticsearch.
This replaces the old OpenAlex HTTP API client and uses the internal
Elasticsearch wrapper instead.
"""
DEFAULT_SEARCH_FIELDS = [
"display_name^5",
"description^3",
"keywords",
"domain.display_name^2",
"field.display_name^2",
"subfield.display_name^2",
]
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
*,
index: ESIndex | str | None = None,
cluster: ESCluster = ESCluster.NES,
):
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
self.timeout = (
timeout
if timeout is not None
else config.settings.openalex_api_timeout_seconds
)
self.transport = transport
self.index = index or self._default_index()
self.cluster = cluster
def list_topics_params(
@staticmethod
def _default_index() -> str:
"""
Resolve the OpenAlex topics index name.
Prefer a configured value if present, otherwise fall back to a sensible
default string index name.
"""
return (
ESIndex.OPENALEX_TOPICS.value
)
@staticmethod
def _split_csv(value: str | None) -> list[str]:
if not value:
return []
return [part.strip() for part in value.split(",") if part.strip()]
@staticmethod
def _encode_cursor(sort_values: list[Any]) -> str:
raw = json.dumps(sort_values).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
@staticmethod
def _decode_cursor(cursor: str | None) -> list[Any] | None:
if not cursor or cursor == "*":
return None
padding = "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(cursor + padding)
return json.loads(raw.decode("utf-8"))
@staticmethod
def _parse_select(select: str | None) -> list[str] | None:
fields = TopicsSearchClient._split_csv(select)
return fields or None
@staticmethod
def _parse_sort(sort: str | None) -> list[dict[str, Any]] | None:
"""
Parses OpenAlex-style sort syntax into Elasticsearch sort syntax.
Examples:
"works_count:desc"
"cited_by_count:desc,display_name:asc"
"-works_count"
"""
parts = TopicsSearchClient._split_csv(sort)
if not parts:
return None
parsed: list[dict[str, Any]] = []
for part in parts:
direction = "asc"
field = part
if part.startswith("-"):
direction = "desc"
field = part[1:]
elif ":" in part:
field, direction = part.split(":", 1)
field = field.strip()
direction = direction.strip().lower()
if direction not in {"asc", "desc"}:
direction = "asc"
if field in {"score", "_score", "relevance_score"}:
parsed.append({"_score": {"order": direction}})
else:
parsed.append({field: {"order": direction, "missing": "_last"}})
return parsed
@staticmethod
def _parse_filter_clause(expression: str) -> tuple[dict[str, Any] | None, bool]:
"""
Parses a single simple OpenAlex-style filter expression.
Supported examples:
"works_count:>100"
"works_count:>=100"
"display_name:Physics"
"ids.openalex:T123"
"field.id:F1|F2"
"is_active:true"
"is_active:!true"
Returns:
tuple[clause, is_negative]
"""
if ":" not in expression:
return None, False
field, value = expression.split(":", 1)
field = field.strip()
value = value.strip()
if not field or not value:
return None, False
is_negative = False
if value.startswith("!"):
is_negative = True
value = value[1:].strip()
range_ops = {
">=": "gte",
"<=": "lte",
">": "gt",
"<": "lt",
}
for prefix, op in range_ops.items():
if value.startswith(prefix):
range_value = value[len(prefix):].strip()
return {"range": {field: {op: range_value}}}, is_negative
if "|" in value:
values = [v.strip() for v in value.split("|") if v.strip()]
return {"terms": {field: values}}, is_negative
lowered = value.lower()
if lowered == "true":
typed_value: Any = True
elif lowered == "false":
typed_value = False
else:
typed_value = value
return {"term": {field: typed_value}}, is_negative
@classmethod
def _parse_filters(
cls,
filter: str | None,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
filter_clauses: list[dict[str, Any]] = []
must_not_clauses: list[dict[str, Any]] = []
for expression in cls._split_csv(filter):
clause, is_negative = cls._parse_filter_clause(expression)
if clause is None:
continue
if is_negative:
must_not_clauses.append(clause)
else:
filter_clauses.append(clause)
return filter_clauses, must_not_clauses
def build_search_body(
self,
*,
search: str | None = None,
@@ -40,28 +207,118 @@ class OpenAlexTopicsClient:
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
params: dict[str, Any] = {"per_page": per_page}
"""
Build the Elasticsearch search body from the previous OpenAlex-style API
parameters.
"""
filter_clauses, must_not_clauses = self._parse_filters(filter)
must_clauses: list[dict[str, Any]] = []
if search:
params["search"] = search
if filter:
params["filter"] = filter
if sort:
params["sort"] = sort
if group_by:
params["group_by"] = group_by
if cursor:
params["cursor"] = cursor
elif page is not None:
params["page"] = page
if sample is not None:
params["sample"] = sample
if select:
params["select"] = select
if self.api_key:
params["api_key"] = self.api_key
must_clauses.append(
{
"multi_match": {
"query": search,
"fields": self.DEFAULT_SEARCH_FIELDS,
"type": "best_fields",
"operator": "and",
}
}
)
return params
if must_clauses or filter_clauses or must_not_clauses:
query: dict[str, Any] = {
"bool": {
"must": must_clauses or [{"match_all": {}}],
"filter": filter_clauses,
"must_not": must_not_clauses,
}
}
else:
query = {"match_all": {}}
if sample is not None:
query = {
"function_score": {
"query": query,
"random_score": {},
}
}
size = sample if sample is not None else per_page
body: dict[str, Any] = {
"query": query,
"size": size,
"track_total_hits": True,
}
source = self._parse_select(select)
if source is not None:
body["_source"] = source
sort_clause = self._parse_sort(sort)
if sort_clause is not None:
body["sort"] = sort_clause
search_after = self._decode_cursor(cursor)
if search_after is not None:
body["search_after"] = search_after
elif cursor is None and page is not None:
body["from"] = max(page - 1, 0) * per_page
if group_by:
body["size"] = 0
body["aggs"] = {
"group_by": {
"terms": {
"field": group_by,
"size": per_page,
}
}
}
return body
async def search_topics(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
body = self.build_search_body(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
result = await elasticsearch_search(
index=self.index,
body=body,
cluster=self.cluster,
)
hits = result.get("hits", {}).get("hits", [])
if hits:
last_sort = hits[-1].get("sort")
if last_sort is not None:
result.setdefault("meta", {})["next_cursor"] = self._encode_cursor(last_sort)
return result
async def list_topics(
self,
@@ -76,24 +333,17 @@ class OpenAlexTopicsClient:
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.get(
"/topics",
params=self.list_topics_params(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
),
)
response.raise_for_status()
return response.json()
"""
Backwards-compatible alias for the old OpenAlex client method name.
"""
return await self.search_topics(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
+146 -106
View File
@@ -1,9 +1,7 @@
import httpx
import pytest
from inse.exceptions import BadRequestException
from inse.exceptions import BadRequestException
from inse.topics import logic
from inse.topics.search_client import OpenAlexTopicsClient
@pytest.fixture
@@ -11,108 +9,144 @@ def anyio_backend():
return "asyncio"
class FakeTopicsSearchClient:
def __init__(self, response: dict):
self.response = response
self.calls: list[dict] = []
async def list_topics(self, **kwargs):
self.calls.append(kwargs)
return self.response
@pytest.mark.anyio
async def test_list_topics_maps_openalex_response_to_model():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
async def test_list_topics_maps_elasticsearch_response_to_model():
client = FakeTopicsSearchClient(
{
"took": 12,
"hits": {
"total": {"value": 1, "relation": "eq"},
"hits": [
{
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"description": "Methods that learn from data.",
"keywords": ["machine learning", "classification"],
"subfield": {
"id": "https://openalex.org/subfields/1702",
"display_name": "Artificial Intelligence",
"_id": "https://openalex.org/T12419",
"_source": {
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"description": "Methods that learn from data.",
"keywords": ["machine learning", "classification"],
"subfield": {
"id": "https://openalex.org/subfields/1702",
"display_name": "Artificial Intelligence",
},
"field": {
"id": "https://openalex.org/fields/17",
"display_name": "Computer Science",
},
"domain": {
"id": "https://openalex.org/domains/4",
"display_name": "Physical Sciences",
},
"works_count": 123,
"cited_by_count": 456,
"ids": {
"openalex": "https://openalex.org/T12419",
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
},
"works_api_url": (
"https://api.openalex.org/works?"
"filter=topics.id:T12419"
),
"created_date": "2023-12-25",
"updated_date": "2023-11-07T05:31:56Z",
},
"field": {
"id": "https://openalex.org/fields/17",
"display_name": "Computer Science",
},
"domain": {
"id": "https://openalex.org/domains/4",
"display_name": "Physical Sciences",
},
"works_count": 123,
"cited_by_count": 456,
"ids": {
"openalex": "https://openalex.org/T12419",
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
},
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
"created_date": "2023-12-25",
"updated_date": "2023-11-07T05:31:56Z",
}
],
"group_by": [
{
"key": "https://openalex.org/domains/4",
"key_display_name": "Physical Sciences",
"count": 1,
}
],
},
)
client = OpenAlexTopicsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
"aggregations": {
"group_by": {
"buckets": [
{
"key": "https://openalex.org/domains/4",
"key_as_string": "Physical Sciences",
"doc_count": 1,
}
]
}
},
}
)
result = await logic.list_topics(search="machine learning", client=client)
result = await logic.list_topics(
search="machine learning",
group_by="domain.id",
client=client,
)
assert client.calls[0]["search"] == "machine learning"
assert client.calls[0]["group_by"] == "domain.id"
assert result.meta.count == 1
assert result.meta.db_response_time_ms == 12
topic = result.results[0]
assert topic.display_name == "Machine learning"
assert topic.var_field.display_name == "Computer Science"
assert topic.subfield.display_name == "Artificial Intelligence"
assert topic.domain.display_name == "Physical Sciences"
assert topic.ids.openalex == "https://openalex.org/T12419"
assert result.group_by[0].key == "https://openalex.org/domains/4"
assert result.group_by[0].key_display_name == "Physical Sciences"
assert result.group_by[0].count == 1
@pytest.mark.anyio
async def test_list_topics_rejects_sample_with_sort():
with pytest.raises(BadRequestException) as exc_info:
with pytest.raises(BadRequestException):
await logic.list_topics(sample=10, sort="works_count:desc")
@pytest.mark.anyio
async def test_list_topics_accepts_practical_openalex_type_variants():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": "1", "page": "1", "per_page": "25"},
"results": [
client = FakeTopicsSearchClient(
{
"took": "10",
"hits": {
"total": {"value": "1", "relation": "eq"},
"hits": [
{
"id": 123,
"display_name": 456,
"description": True,
"keywords": ["topic", 123],
"subfield": {"id": 1, "display_name": 2},
"field": {"id": 3, "display_name": 4},
"domain": {"id": 5, "display_name": 6},
"works_count": "12.0",
"cited_by_count": False,
"ids": {"openalex": 123, "wikipedia": 456},
"created_date": "2023-12-25T10:11:12Z",
"updated_date": "2023-12-25",
"_id": "123",
"_source": {
"id": 123,
"display_name": 456,
"description": True,
"keywords": ["topic", 123],
"subfield": {"id": 1, "display_name": 2},
"field": {"id": 3, "display_name": 4},
"domain": {"id": 5, "display_name": 6},
"works_count": "12.0",
"cited_by_count": False,
"ids": {"openalex": 123, "wikipedia": 456},
"created_date": "2023-12-25T10:11:12Z",
"updated_date": "2023-12-25",
},
}
],
"group_by": [{"key": True, "count": "1"}],
},
)
client = OpenAlexTopicsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
"aggregations": {
"group_by": {
"buckets": [
{
"key": True,
"doc_count": "1",
}
]
}
},
}
)
result = await logic.list_topics(client=client)
result = await logic.list_topics(group_by="domain.id", client=client)
topic = result.results[0]
assert topic.id == "123"
@@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants():
@pytest.mark.anyio
async def test_autocomplete_topics_returns_frontend_options():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["search"] == "machine learning"
assert request.url.params["filter"] == (
"domain.id:https://openalex.org/domains/4,"
"field.id:https://openalex.org/fields/17,"
"subfield.id:https://openalex.org/subfields/1702"
)
assert request.url.params["sort"] == "works_count:desc"
assert request.url.params["per_page"] == "5"
assert request.url.params["select"] == (
"id,display_name,description,keywords,subfield,field,domain,"
"works_count,cited_by_count,ids"
)
return httpx.Response(
200,
json={
"meta": {"count": 1, "db_response_time_ms": 12},
"results": [
client = FakeTopicsSearchClient(
{
"took": 12,
"hits": {
"total": {"value": 1, "relation": "eq"},
"hits": [
{
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"description": "Methods that learn from data.",
"field": {"display_name": "Computer Science"},
"subfield": {"display_name": "Artificial Intelligence"},
"domain": {"display_name": "Physical Sciences"},
"works_count": 123,
"cited_by_count": 456,
"ids": {"openalex": "https://openalex.org/T12419"},
"_id": "https://openalex.org/T12419",
"_source": {
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"description": "Methods that learn from data.",
"field": {"display_name": "Computer Science"},
"subfield": {
"display_name": "Artificial Intelligence",
},
"domain": {"display_name": "Physical Sciences"},
"works_count": 123,
"cited_by_count": 456,
"ids": {
"openalex": "https://openalex.org/T12419",
},
},
}
],
},
)
client = OpenAlexTopicsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
}
)
result = await logic.autocomplete_topics(
@@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options():
client=client,
)
assert client.calls[0]["search"] == "machine learning"
assert client.calls[0]["filter"] == (
"domain.id:https://openalex.org/domains/4,"
"field.id:https://openalex.org/fields/17,"
"subfield.id:https://openalex.org/subfields/1702"
)
assert client.calls[0]["sort"] == "works_count:desc"
assert client.calls[0]["per_page"] == 5
assert client.calls[0]["page"] == 1
assert client.calls[0]["select"] == (
"id,display_name,description,keywords,subfield,field,domain,"
"works_count,cited_by_count,ids"
)
assert result.meta.count == 1
assert result.meta.db_response_time_ms == 12
assert len(result.results) == 1
option = result.results[0]
assert option.id == "https://openalex.org/T12419"
assert option.display_name == "Machine learning"
@@ -190,4 +230,4 @@ async def test_autocomplete_topics_returns_frontend_options():
assert option.works_count == 123
assert option.cited_by_count == 456
assert option.entity_type == "topic"
assert option.external_id == "https://openalex.org/T12419"
assert option.external_id == "https://openalex.org/T12419"
@@ -1,7 +1,7 @@
import httpx
import pytest
from inse.topics.search_client import OpenAlexTopicsClient
from inse.model import ESCluster, ESIndex
from inse.topics.search_client import TopicsSearchClient
@pytest.fixture
@@ -9,10 +9,10 @@ def anyio_backend():
return "asyncio"
def test_list_topics_params_include_openalex_query_parameters():
client = OpenAlexTopicsClient(api_key="test-key")
def test_build_search_body_includes_openalex_query_parameters():
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
params = client.list_topics_params(
body = client.build_search_body(
search="machine learning",
filter="domain.id:4,works_count:>1000",
sort="works_count:desc",
@@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters():
select="id,display_name",
)
assert params == {
"search": "machine learning",
"filter": "domain.id:4,works_count:>1000",
"sort": "works_count:desc",
"group_by": "domain.id",
"per_page": 10,
"page": 2,
"select": "id,display_name",
"api_key": "test-key",
assert body["query"] == {
"bool": {
"must": [
{
"multi_match": {
"query": "machine learning",
"fields": client.DEFAULT_SEARCH_FIELDS,
"type": "best_fields",
"operator": "and",
}
}
],
"filter": [
{"term": {"domain.id": "4"}},
{"range": {"works_count": {"gt": "1000"}}},
],
"must_not": [],
}
}
assert body["_source"] == ["id", "display_name"]
assert body["sort"] == [
{"works_count": {"order": "desc", "missing": "_last"}}
]
# group_by queries use aggregations and no regular hits
assert body["size"] == 0
assert body["from"] == 10
assert body["track_total_hits"] is True
assert body["aggs"] == {
"group_by": {
"terms": {
"field": "domain.id",
"size": 10,
}
}
}
def test_list_topics_params_prefers_cursor_over_page():
client = OpenAlexTopicsClient(api_key="test-key")
def test_build_search_body_prefers_cursor_over_page():
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
params = client.list_topics_params(cursor="*", page=3)
cursor = client._encode_cursor(["Machine learning", "https://openalex.org/T12419"])
assert params["cursor"] == "*"
assert "page" not in params
body = client.build_search_body(
cursor=cursor,
page=3,
per_page=25,
)
assert body["search_after"] == [
"Machine learning",
"https://openalex.org/T12419",
]
assert "from" not in body
def test_build_search_body_with_plain_cursor_star_does_not_use_page_offset():
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
body = client.build_search_body(
cursor="*",
page=3,
per_page=25,
)
assert "search_after" not in body
assert "from" not in body
@pytest.mark.anyio
async def test_list_topics_calls_openalex_topics_endpoint():
def handler(request: httpx.Request) -> httpx.Response:
assert request.method == "GET"
assert request.url.path == "/topics"
assert request.url.params["search"] == "machine learning"
assert request.url.params["api_key"] == "test-key"
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch):
captured = {}
async def fake_elasticsearch_search(*, index, body, cluster):
captured["index"] = index
captured["body"] = body
captured["cluster"] = cluster
return {
"took": 3,
"hits": {
"total": {"value": 1, "relation": "eq"},
"hits": [
{
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"_id": "https://openalex.org/T12419",
"_source": {
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
},
"sort": [1000, "https://openalex.org/T12419"],
}
],
},
)
}
client = OpenAlexTopicsClient(
base_url="https://api.openalex.org",
api_key="test-key",
transport=httpx.MockTransport(handler),
monkeypatch.setattr(
"inse.topics.search_client.elasticsearch_search",
fake_elasticsearch_search,
)
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
result = await client.list_topics(search="machine learning")
assert result["meta"]["count"] == 1
assert result["results"][0]["display_name"] == "Machine learning"
assert captured["index"] == ESIndex.OPENALEX_TOPICS
assert captured["cluster"] == ESCluster.NES
assert captured["body"]["query"]["bool"]["must"] == [
{
"multi_match": {
"query": "machine learning",
"fields": client.DEFAULT_SEARCH_FIELDS,
"type": "best_fields",
"operator": "and",
}
}
]
assert captured["body"]["size"] == 25
assert captured["body"]["from"] == 0
assert captured["body"]["track_total_hits"] is True
assert result["hits"]["total"]["value"] == 1
assert result["hits"]["hits"][0]["_source"]["display_name"] == "Machine learning"
assert result["meta"]["next_cursor"] is not None
@@ -48,6 +48,8 @@ model/bodyChangePassword.ts
model/bodyGetAccessToken.ts
model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyRequestPasswordReset.ts
model/bodyResetPassword.ts
model/bundProject.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
+227
View File
@@ -39,6 +39,10 @@ import { BodyLogin } from '../model/bodyLogin';
// @ts-ignore
import { BodyRequestOtk } from '../model/bodyRequestOtk';
// @ts-ignore
import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset';
// @ts-ignore
import { BodyResetPassword } from '../model/bodyResetPassword';
// @ts-ignore
import { CreateAccountRequest } from '../model/createAccountRequest';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -1436,6 +1440,229 @@ export class AuthService extends BaseService {
);
}
/**
* Request Password Reset
* Request a one-time password reset link for the given email address.
* @endpoint post /api/auth/v2/request-password-reset
* @param bodyRequestPasswordReset
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public requestPasswordReset(
bodyRequestPasswordReset: BodyRequestPasswordReset,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any>;
public requestPasswordReset(
bodyRequestPasswordReset: BodyRequestPasswordReset,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<any>>;
public requestPasswordReset(
bodyRequestPasswordReset: BodyRequestPasswordReset,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<any>>;
public requestPasswordReset(
bodyRequestPasswordReset: BodyRequestPasswordReset,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
bodyRequestPasswordReset === null ||
bodyRequestPasswordReset === undefined
) {
throw new Error(
'Required parameter bodyRequestPasswordReset was null or undefined when calling requestPasswordReset.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/auth/v2/request-password-reset`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`, {
context: localVarHttpContext,
body: bodyRequestPasswordReset,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
});
}
/**
* Reset Password
* Reset the user's password using a one-time password reset token.
* @endpoint post /api/auth/v2/reset-password
* @param bodyResetPassword
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public resetPassword(
bodyResetPassword: BodyResetPassword,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any>;
public resetPassword(
bodyResetPassword: BodyResetPassword,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<any>>;
public resetPassword(
bodyResetPassword: BodyResetPassword,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<any>>;
public resetPassword(
bodyResetPassword: BodyResetPassword,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (bodyResetPassword === null || bodyResetPassword === undefined) {
throw new Error(
'Required parameter bodyResetPassword was null or undefined when calling resetPassword.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/auth/v2/reset-password`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`, {
context: localVarHttpContext,
body: bodyResetPassword,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
});
}
/**
* Update Account
* @endpoint put /api/accounts/{account_id}
@@ -0,0 +1,16 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface BodyRequestPasswordReset {
/**
* User's email address
*/
email: string;
}
@@ -0,0 +1,20 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface BodyResetPassword {
/**
* Password reset token from the reset link
*/
reset_token: string;
/**
* New password
*/
new_password: string;
}
+2
View File
@@ -23,6 +23,8 @@ export * from './bodyChangePassword';
export * from './bodyGetAccessToken';
export * from './bodyLogin';
export * from './bodyRequestOtk';
export * from './bodyRequestPasswordReset';
export * from './bodyResetPassword';
export * from './bundProject';
export * from './bundProjectDetails';
export * from './bundProjectPage';
+45 -3
View File
@@ -1,10 +1,12 @@
import { Routes } from '@angular/router';
import { userGuard } from './shared/guards/user.guard';
import { superAdminGuard } from './shared/guards/super-admin.guard';
import { guestOnlyGuard } from './shared/guards/guest-only.guard';
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
import { personListResolver } from './resolvers/person-list.resolver';
import { personBioResolver } from './resolvers/person-bio.resolver';
import { personResolver } from './resolvers/person.resolver';
import { personNewsResolver } from './resolvers/person-news.resolver';
import { institutionResolver } from './resolvers/institution.resolver';
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
@@ -37,10 +39,19 @@ export const routes: Routes = [
),
},
{
path: 'register',
path: 'forgot-password',
canActivate: [guestOnlyGuard],
loadComponent: () =>
import('./modules/app-register/app-register.component').then(
(mod) => mod.AppRegisterComponent,
import('./modules/forgot-password/forgot-password.component').then(
(mod) => mod.ForgotPasswordComponent,
),
},
{
path: 'reset-password',
canActivate: [guestOnlyGuard],
loadComponent: () =>
import('./modules/reset-password/reset-password.component').then(
(mod) => mod.ResetPasswordComponent,
),
},
{
@@ -270,6 +281,23 @@ export const routes: Routes = [
(mod) => mod.PersonFundingComponent,
),
},
{
path: 'news',
loadComponent: () =>
import('./modules/person-news/person-news.component').then(
(mod) => mod.PersonNewsComponent,
),
resolve: {
newsPage: personNewsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'pageSize', 'sortOrder', 'query'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'patents',
loadComponent: () =>
@@ -383,6 +411,20 @@ export const routes: Routes = [
(mod) => mod.PatentsComponent,
),
},
{
path: 'news',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
},
{
path: 'news/:id',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/news-detail/news-detail.component').then(
(mod) => mod.NewsDetailComponent,
),
},
{
path: 'error',
loadComponent: () =>
@@ -82,8 +82,10 @@
</button>
<div class="form-actions">
<a routerLink="/login">Passwort vergessen?</a>
<a routerLink="/register">Konto erstellen</a>
<span></span>
<a class="auth-link" routerLink="/forgot-password"
>Passwort vergessen?</a
>
</div>
</form>
} @else {
@@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input';
import { CredentialService } from '../../shared/services/credential.service';
import { MatIconModule } from '@angular/material/icon';
import { CommonModule } from '@angular/common';
import { Subscription } from 'rxjs';
import { finalize, Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
@@ -103,35 +103,39 @@ export class AppLoginComponent implements OnDestroy {
const email = this.credentialsForm.controls.email.value ?? '';
const password = this.credentialsForm.controls.password.value ?? '';
this.credentialService.requestOtk(email, password).subscribe({
next: (otkResponse) => {
const accountId = otkResponse.account_id;
this.accountId = accountId;
this.currentStep = 'otk';
this.otkForm.reset();
this.startCountdown();
this.snackBar.open(
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
'OK',
{
duration: 4000,
},
);
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
},
);
},
complete: () => {
this.isSubmitting = false;
this.credentialsForm.enable();
},
});
this.credentialService
.requestOtk(email, password)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.credentialsForm.enable();
}),
)
.subscribe({
next: (otkResponse) => {
const accountId = otkResponse.account_id;
this.accountId = accountId;
this.currentStep = 'otk';
this.otkForm.reset();
this.startCountdown();
this.snackBar.open(
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
'OK',
{
duration: 4000,
},
);
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
},
);
},
});
}
resendCode() {
@@ -169,30 +173,34 @@ export class AppLoginComponent implements OnDestroy {
const code = this.otkForm.controls.code.value ?? '';
this.credentialService.loginWithOtk(this.accountId, code).subscribe({
next: () => {
this.credentialService.reauthenticateViaIdToken().subscribe({
next: () => {
this.checkEnter();
this.stopCountdown();
this.router.navigate(['/dashboard']);
},
});
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
},
);
},
complete: () => {
this.isSubmitting = false;
this.otkForm.enable();
},
});
this.credentialService
.loginWithOtk(this.accountId, code)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.otkForm.enable();
}),
)
.subscribe({
next: () => {
this.credentialService.reauthenticateViaIdToken().subscribe({
next: () => {
this.checkEnter();
this.stopCountdown();
this.router.navigate(['/dashboard']);
},
});
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
},
);
},
});
}
editCredentials() {
@@ -1,100 +0,0 @@
<div class="container">
<form class="form" [formGroup]="registerForm">
<h3>Konto erstellen</h3>
<p class="field">Bitte gib Deine Daten ein, um Dich zu registrieren.</p>
<mat-form-field class="field">
<mat-label>Benutzername</mat-label>
<input matInput formControlName="username" />
@if (registerForm.controls['username'].hasError('required')) {
<mat-error>Fehler: <b>Benutzername</b> erforderlich.</mat-error>
} @else if (registerForm.controls['username'].hasError('minlength')) {
<mat-error>Fehler: <b>Benutzername</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>E-Mail</mat-label>
<input matInput type="email" formControlName="email" />
@if (registerForm.controls['email'].hasError('required')) {
<mat-error>Fehler: <b>E-Mail</b> erforderlich.</mat-error>
} @else if (registerForm.controls['email'].hasError('email')) {
<mat-error>Fehler: Ungültige <b>E-Mail</b> Adresse.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>Passwort</mat-label>
<input
matInput
[type]="showPassword ? 'text' : 'password'"
formControlName="password" />
@if (showPassword) {
<mat-icon matSuffix (click)="showPassword = false">visibility</mat-icon>
} @else {
<mat-icon matSuffix (click)="showPassword = true"
>visibility_off</mat-icon
>
}
@if (registerForm.controls['password'].hasError('required')) {
<mat-error>Fehler: <b>Passwort</b> erforderlich.</mat-error>
} @else if (registerForm.controls['password'].hasError('minlength')) {
<mat-error>Fehler: <b>Passwort</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>Institution</mat-label>
<mat-icon matPrefix>apartment</mat-icon>
<input
type="text"
matInput
formControlName="institution"
[matAutocomplete]="auto"
placeholder="Institution suchen..." />
@if (registerForm.controls['institution'].hasError('required')) {
<mat-error>Fehler: <b>Institution</b> erforderlich.</mat-error>
}
<mat-autocomplete
#auto="matAutocomplete"
(optionSelected)="onInstitutionSelected($event)">
@for (institution of institutionOptions(); track institution.id) {
<mat-option
[value]="institution.display_name"
style="font-size: 16px">
<div>
<span>{{ institution.display_name }}</span>
</div>
@if (institution.hint) {
<small>{{ institution.hint }}</small>
}
</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<div class="field checkbox-container">
<mat-checkbox formControlName="superadmin"
>Superadmin Rechte</mat-checkbox
>
</div>
<button
mat-raised-button
class="button"
(click)="submit()"
[disabled]="!registerForm.valid || credentialService.isValidating()">
Registrieren
</button>
<div class="field" style="text-align: center; margin-top: -10px">
<button mat-button type="button" routerLink="/login">
Bereits ein Konto? <b>Anmelden</b>
</button>
</div>
</form>
<p class="progress">
<!-- Statusanzeige analog zum Login-Formular -->
</p>
</div>
@@ -1,56 +0,0 @@
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: linear-gradient(160deg, #f4f6fb, #e8ecf7);
}
.form {
display: flex;
flex-direction: column;
align-items: center;
background: #fff;
border: none;
border-radius: 12px;
box-shadow:
0 2px 12px #1a3a6e1a,
0 1px 4px #0000000f;
gap: 20px;
padding: 36px 32px 28px;
h3 {
margin: 0 0 4px;
font-weight: 600;
color: #1a3a6e;
}
}
.button {
min-height: 48px;
min-width: 140px;
border-radius: 8px;
font-weight: 500;
letter-spacing: 0.02em;
}
.field {
width: 400px;
}
.checkbox-container {
display: flex;
align-items: center;
justify-content: flex-start;
}
.progress {
padding-top: 5px;
width: 300px;
height: 2em;
text-align: center;
font-size: small;
color: #585f71;
}
@@ -1,168 +0,0 @@
import {
Component,
inject,
OnDestroy,
signal,
DestroyRef,
effect,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, RouterLink } from '@angular/router';
import {
FormBuilder,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { CredentialService } from '../../shared/services/credential.service';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import {
Subscription,
map,
switchMap,
debounceTime,
distinctUntilChanged,
catchError,
of,
} from 'rxjs';
import {
MatAutocompleteModule,
MatAutocompleteSelectedEvent,
} from '@angular/material/autocomplete';
import { InstitutionsService } from '../../api';
@Component({
selector: 'app-register',
standalone: true,
imports: [
CommonModule,
ReactiveFormsModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatCheckboxModule,
RouterLink,
MatSnackBarModule,
MatAutocompleteModule,
],
templateUrl: './app-register.component.html',
styleUrl: './app-register.component.scss',
})
export class AppRegisterComponent implements OnDestroy {
private readonly fb = inject(FormBuilder);
protected readonly credentialService = inject(CredentialService);
private readonly router = inject(Router);
private readonly snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
private subscription?: Subscription;
private institutionsService = inject(InstitutionsService);
registerForm: FormGroup = this.fb.group({
username: ['', [Validators.required, Validators.minLength(4)]],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
institution: ['', [Validators.required]],
superadmin: [false],
});
readonly institutionOptions = signal<any[]>([]);
showPassword = false;
constructor() {
effect(() => {
if (this.credentialService.isValidating()) {
this.registerForm.disable();
} else {
this.registerForm.enable();
this.checkEnter();
}
});
this.setupInstitutionAutocomplete();
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
checkEnter(): void {
if (this.credentialService.isAuthenticated()) {
this.router.navigate(['/dashboard']);
}
}
submit() {
if (this.registerForm.valid) {
this.credentialService.isValidating.set(true);
this.registerForm.disable();
this.subscription = this.credentialService
.registerAccount(this.registerForm.value)
.subscribe({
next: () => {
this.credentialService.isValidating.set(false);
this.snackBar.open(
'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.',
'OK',
{ duration: 5000 },
);
this.router.navigate(['/login']);
},
error: (err) => {
this.credentialService.isValidating.set(false);
this.registerForm.enable();
const message =
err.error?.message ||
'Fehler bei der Registrierung. Bitte versuche es später erneut.';
this.snackBar.open(message, 'Schließen', {
panelClass: ['error-snackbar'],
duration: 5000,
});
},
});
}
}
private setupInstitutionAutocomplete(): void {
this.registerForm.controls['institution'].valueChanges
.pipe(
debounceTime(250),
map((value) => (typeof value === 'string' ? value.trim() : '')),
distinctUntilChanged(),
switchMap((query) => {
if (query.length < 2) {
this.institutionOptions.set([]);
return of([]);
}
return this.searchInstitutions(query).pipe(
catchError((ev) => {
console.log(ev);
return of([]);
}),
);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((options) => {
this.institutionOptions.set(options);
});
}
private searchInstitutions(query: string) {
return this.institutionsService
.autocompleteInstitutions(query, undefined, undefined, 10)
.pipe(map((response) => response.results ?? []));
}
onInstitutionSelected(event: MatAutocompleteSelectedEvent): void {
const val = event.option.value;
this.registerForm.controls['institution'].setValue(val, {
emitEvent: false,
});
this.institutionOptions.set([]);
}
}
@@ -0,0 +1,105 @@
<section class="login-page">
<div class="login-panel">
<div class="brand-block">
<span class="eyebrow">SmartGuide Account Portal</span>
<h1>Passwort vergessen</h1>
<p>
Gib Deine E-Mail-Adresse ein. Wenn ein Konto existiert, senden wir Dir
einen Link zum Zurücksetzen des Passworts.
</p>
</div>
@if (emailSent()) {
<div class="login-form">
<div class="code-intro">
<mat-icon>
{{ rateLimited() ? 'hourglass_empty' : 'mark_email_unread' }}
</mat-icon>
<div>
@if (rateLimited()) {
<strong>Zu viele Anfragen</strong>
<span>
Es wurden bereits mehrere Links angefordert. Bitte prüfe Dein
Postfach oder versuche es in {{ retryAfterText() }} erneut.
</span>
} @else {
<strong>E-Mail wurde versendet</strong>
<span>
Falls ein Konto mit dieser E-Mail-Adresse existiert, wurde ein
Link zum Zurücksetzen des Passworts versendet. Bitte prüfe Dein
Postfach.
</span>
}
</div>
</div>
@if (errorMessage()) {
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<div>
<strong>Fehler</strong>
<span>{{ errorMessage() }}</span>
</div>
</div>
}
<div class="form-actions">
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
<a
class="auth-link"
href="#"
(click)="$event.preventDefault(); requestPasswordResetAgain()">
E-Mail nicht bekommen?
</a>
</div>
</div>
} @else {
<form
class="login-form"
[formGroup]="form"
(ngSubmit)="requestPasswordReset()">
<mat-form-field class="field" appearance="outline">
<mat-label>E-Mail-Adresse</mat-label>
<input
matInput
type="email"
autocomplete="email"
formControlName="email" />
@if (form.controls.email.hasError('required')) {
<mat-error>E-Mail-Adresse ist erforderlich.</mat-error>
} @else if (form.controls.email.hasError('email')) {
<mat-error>Bitte gib eine gültige E-Mail-Adresse ein.</mat-error>
}
</mat-form-field>
@if (errorMessage()) {
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<div>
<strong>Fehler</strong>
<span>{{ errorMessage() }}</span>
</div>
</div>
}
<button
mat-flat-button
color="primary"
class="submit-button"
type="submit"
[disabled]="form.invalid || isSubmitting()">
@if (isSubmitting()) {
Link wird gesendet...
} @else {
Link zum Zurücksetzen senden
}
</button>
<div class="form-actions">
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
</div>
</form>
}
</div>
</section>
@@ -0,0 +1,137 @@
import { Component, inject, signal } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { RouterLink } from '@angular/router';
import { finalize } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { CredentialService } from '../../shared/services/credential.service';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
@Component({
selector: 'app-forgot-password',
imports: [
ReactiveFormsModule,
RouterLink,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatSnackBarModule,
],
templateUrl: './forgot-password.component.html',
styleUrl: '../app-login/app-login.component.scss',
standalone: true,
})
export class ForgotPasswordComponent {
private readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar);
form = new FormGroup({
email: new FormControl<string>('', [Validators.required, Validators.email]),
});
readonly isSubmitting = signal(false);
readonly emailSent = signal(false);
readonly rateLimited = signal(false);
readonly retryAfterSeconds = signal<number | undefined>(undefined);
readonly requestedEmail = signal('');
readonly errorMessage = signal<string | undefined>(undefined);
requestPasswordReset(): void {
if (this.form.invalid || this.isSubmitting()) {
this.form.markAllAsTouched();
return;
}
const email = this.form.controls.email.value ?? '';
this.sendPasswordResetRequest(email);
}
requestPasswordResetAgain(): void {
const email = this.requestedEmail();
if (!email || this.isSubmitting()) {
return;
}
this.sendPasswordResetRequest(email);
}
retryAfterText(): string {
const seconds = this.retryAfterSeconds();
if (!seconds) {
return 'einigen Minuten';
}
const minutes = Math.max(1, Math.ceil(seconds / 60));
return `${minutes} ${minutes === 1 ? 'Minute' : 'Minuten'}`;
}
private sendPasswordResetRequest(email: string): void {
const wasAlreadySent = this.emailSent();
this.isSubmitting.set(true);
this.errorMessage.set(undefined);
if (!wasAlreadySent) {
this.form.disable();
}
this.credentialService
.requestPasswordReset(email)
.pipe(
finalize(() => {
this.isSubmitting.set(false);
}),
)
.subscribe({
next: (response) => {
this.requestedEmail.set(email);
this.emailSent.set(true);
this.rateLimited.set(response.rate_limited);
this.retryAfterSeconds.set(response.retry_after_seconds);
if (response.rate_limited) {
this.snackBar.open(
`Es wurden bereits mehrere Links angefordert. Bitte versuche es in ${this.retryAfterText()} erneut.`,
'OK',
{ duration: 7000 },
);
return;
}
if (wasAlreadySent) {
this.snackBar.open(
'Wir haben Dir einen neuen Link zum Zurücksetzen des Passworts gesendet.',
'OK',
{ duration: 5000 },
);
}
},
error: () => {
this.errorMessage.set(
'Der Link zum Zurücksetzen des Passworts konnte nicht angefordert werden. Bitte versuche es später erneut.',
);
if (!wasAlreadySent) {
this.form.enable();
}
this.snackBar.open(
'Die Anfrage konnte nicht gesendet werden. Bitte versuche es später erneut.',
'OK',
{ duration: 7000 },
);
},
});
}
}
@@ -83,7 +83,8 @@
mat-stroked-button
color="primary"
(click)="deselectAll()"
[disabled]="isExtracting()">
[disabled]="isExtracting()"
matTooltip="Alle extrahierten Keywords abwählen">
<mat-icon>select_all</mat-icon>
<span>Alle abwählen</span>
</button>
@@ -344,14 +345,16 @@
<mat-expansion-panel-header>
<mat-panel-title>Quellentext: {{ sourceUrl() }}</mat-panel-title>
</mat-expansion-panel-header>
<div class="source-text">{{ sourceContent() }}</div>
<div
class="source-text"
[innerHTML]="highlightedSourceContent()"></div>
</mat-expansion-panel>
}
</mat-card-content>
@if (isExtracting() && !keywordsExist()) {
<app-loading
text="{{ statusMessage() }}"
icon="group"
icon="manage_search"
[size]="200"
[diameter]="200" />
}
@@ -50,6 +50,10 @@ $touch-target: 44px;
::ng-deep app-topic-legend .topic-legend {
width: 100%;
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
border-bottom: none;
border-radius: 4px;
margin: 0;
}
}
@@ -66,7 +70,8 @@ $touch-target: 44px;
.toolbar-wrapper {
display: grid;
grid-template-columns: 3fr 1.3fr;
border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
border-bottom: none;
}
.toolbar-controls--placeholder {
@@ -188,14 +193,13 @@ mat-button-toggle-group {
}
.keyword-card {
background-color: var(--sg-background);
padding: 0.5rem;
padding: 0 !important;
background: var(--sg-background-muted, #f4f5f7);
.mat-card-header {
padding: 0 0 0.5rem 0;
}
.mat-card-content {
.mat-mdc-card-content {
padding: 0;
}
}
@@ -209,12 +213,12 @@ mat-button-toggle-group {
}
.table-head {
border-top: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
padding-top: 0.5rem;
display: grid;
grid-template-columns: repeat(3, 1fr) 1.3fr;
column-gap: 1rem;
border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
padding-bottom: 0.5rem;
background: var(--sg-background-muted, #f4f5f7);
}
@@ -235,12 +239,13 @@ mat-button-toggle-group {
}
.table-body {
min-height: 200px;
display: grid;
grid-template-columns: repeat(3, 1fr) 1.3fr;
column-gap: 1rem;
row-gap: 0.4rem;
align-items: start;
border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
//border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
}
.table-col {
@@ -249,7 +254,7 @@ mat-button-toggle-group {
min-width: 0;
padding: 0.5rem;
height: 100%;
border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
&:last-child {
border-right: none;
@@ -266,7 +271,7 @@ mat-button-toggle-group {
}
.thick-border {
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)) !important;
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08)) !important;
}
@container keyword-tool (max-width: #{$tablet}) {
@@ -504,7 +509,7 @@ mat-button-toggle-group {
margin: 0.75rem 0;
background: var(--sg-background-muted, #f5f5f5);
border-radius: 4px;
border-left: 4px solid var(--sg-primary, #1976d2);
//border-left: 4px solid var(--sg-primary, #1976d2);
.mat-expansion-panel-header {
padding: 0.5rem 0.75rem;
@@ -554,7 +559,6 @@ mat-button-toggle-group {
PROGRESS BAR
============================================================ */
.progress-container {
min-height: 300px;
margin-top: 0.5rem;
position: relative;
padding: 1rem;
@@ -45,6 +45,7 @@ import {
} from '../../resolvers/utils/topic-legend';
import { MatTooltipModule } from '@angular/material/tooltip';
import { A11yModule } from '@angular/cdk/a11y';
import { DomSanitizer } from '@angular/platform-browser';
type InputMode = 'url' | 'text';
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
type KeywordView = 'llm' | 'topic';
@@ -77,6 +78,7 @@ type KeywordView = 'llm' | 'topic';
})
export class KeywordsSearchComponent {
private readonly formBuilder = inject(FormBuilder);
private readonly sanitizer = inject(DomSanitizer);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
@@ -128,6 +130,55 @@ export class KeywordsSearchComponent {
readonly sourceContent = signal<string>('');
readonly sourceUrl = signal<string | null>(null);
readonly highlightedSourceContent = computed(() => {
const content = this.sourceContent();
if (!content) return '';
const selectedKeywords = this.selectedKeywords();
if (selectedKeywords.length === 0) return content;
let highlightedContent = content;
// replace the keyword with highlighted spans
for (const keyword of selectedKeywords) {
const normalizedKeyword = this.normalizeKeyword(keyword);
// Find the first keyword entry that matches this normalized keyword
const entry = this.allKeywordEntries().find(
(e) =>
this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword,
);
if (entry) {
const topic = this.getTopic(entry);
if (topic) {
const color = this.getTopicColor(topic);
// Escape HTML special characters in the keyword before using it in HTML
const escapedKeyword = keyword
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
// Create the replacement span HTML
const replacement = `<span style="background-color: color-mix(in srgb, ${color} 27%, #ffffff); 100%); font-weight: bold;" title="Keyword: ${keyword}">${escapedKeyword}</span>`;
const escapedRegexKeyword = keyword.replace(
/[.*+?^${}()|[\]\\]/g,
'\\$&',
);
const regex = new RegExp(escapedRegexKeyword, 'g');
highlightedContent = highlightedContent.replace(regex, replacement);
}
}
}
console.log(
'Highlighted content:',
this.sanitizer.bypassSecurityTrustHtml(highlightedContent),
);
return this.sanitizer.bypassSecurityTrustHtml(highlightedContent);
});
private isRestoringState = false;
// Set right before we call router.navigate() ourselves (from
@@ -54,7 +54,10 @@
<div class="article-body">
@if (article.full_content) {
<p class="content">{{ article.full_content }}</p>
<p
#articleBody
class="content"
[innerHTML]="highlightedContent"></p>
} @else {
<p class="placeholder">Kein Inhalt verfügbar.</p>
}
@@ -76,55 +79,168 @@
<aside class="sidebar">
<div class="sidebar-card">
<h3>
<mat-icon>group</mat-icon>
Erwähnte Personen
</h3>
<div class="person-list">
@if (article.authors && article.authors.length) {
@for (person of article.authors; track person.name) {
@if (person.is_ude && person.person_id) {
<a
class="person-item is-link"
[routerLink]="['/person', person.person_id, 'overview']">
<div class="avatar">{{ person.name.charAt(0) }}</div>
<span class="person-name">{{ person.name }}</span>
<span class="ude-badge">UDE</span>
</a>
} @else {
<article class="person-item is-muted">
<div class="avatar">{{ person.name.charAt(0) }}</div>
<span class="person-name">{{ person.name }}</span>
</article>
}
<div class="accordion-panel">
<button
type="button"
class="accordion-header"
(click)="openPanel = openPanel === 'persons' ? null : 'persons'"
[attr.aria-expanded]="openPanel === 'persons'">
<mat-icon>group</mat-icon>
<span class="accordion-title">Erwähnte Personen</span>
<mat-icon
class="info-icon"
matTooltip="Personen, die im Text erwähnt wurden. Klicke auf eine der UDE angehörige Person, um zu ihrem Profil zu gelangen."
matTooltipPosition="above"
(click)="$event.stopPropagation()"
>info_outline</mat-icon
>
@if (article.authors?.length) {
<span class="count-badge">{{ article.authors!.length }}</span>
}
} @else {
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
<mat-icon
class="chevron"
[class.rotated]="openPanel !== 'persons'"
>expand_more</mat-icon
>
</button>
@if (openPanel === 'persons') {
<div class="accordion-body">
@if (article.authors && article.authors.length) {
<div class="person-list">
@for (person of pagedPersons; track person.name) {
@if (person.is_ude && person.person_id) {
<a
class="person-item is-link"
[routerLink]="[
'/person',
person.person_id,
'overview',
]">
<div class="avatar">
{{ personInitials(person.name) }}
</div>
<span class="person-name">{{ person.name }}</span>
<span class="ude-badge">UDE</span>
</a>
} @else {
<div class="person-item is-muted">
<div class="avatar">
{{ personInitials(person.name) }}
</div>
<span class="person-name">{{ person.name }}</span>
</div>
}
}
</div>
@if (personsPageCount > 1) {
<div class="persons-pagination">
<button
type="button"
class="page-btn"
[disabled]="personsPage === 0"
(click)="personsPage = personsPage - 1">
<mat-icon>chevron_left</mat-icon>
</button>
<span class="page-indicator"
>{{ personsPage + 1 }} / {{ personsPageCount }}</span
>
<button
type="button"
class="page-btn"
[disabled]="personsPage === personsPageCount - 1"
(click)="personsPage = personsPage + 1">
<mat-icon>chevron_right</mat-icon>
</button>
</div>
}
} @else {
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
}
</div>
}
</div>
</div>
<div class="sidebar-card">
<h3>
<mat-icon>label</mat-icon>
Schlüsselwörter
</h3>
<div class="chip-list">
@if (article.keywords && article.keywords.length) {
@for (
keyword of article.keywords;
track keyword;
let i = $index
) {
<span
class="topic-chip"
(click)="onKeywordClick(keyword)"
[ngClass]="chipColor(i)"
>{{ keyword }}</span
>
<div class="accordion-panel">
<button
type="button"
class="accordion-header"
(click)="openPanel = openPanel === 'topics' ? null : 'topics'"
[attr.aria-expanded]="openPanel === 'topics'">
<mat-icon>label</mat-icon>
<span class="accordion-title">Themen & Schlüsselwörter</span>
<mat-icon
class="info-icon"
matTooltip="Themen, die mit den extrahierten Schlüsselwörtern des Artikels assoziiert werden. Klicke auf ein Schlüsselwort, um zum hervorgehobenen Begriff im Text zu springen."
matTooltipPosition="above"
(click)="$event.stopPropagation()"
>info_outline</mat-icon
>
@if (article.topics?.length) {
<span class="count-badge">{{ article.topics!.length }}</span>
}
} @else {
<p class="placeholder">Keine Schlüsselwörter gefunden.</p>
<mat-icon class="chevron" [class.rotated]="openPanel !== 'topics'"
>expand_more</mat-icon
>
</button>
@if (openPanel === 'topics') {
<div class="accordion-body">
@if (article.topics && article.topics.length) {
<div class="topics-accordion">
@for (
topic of article.topics;
track topic.id ?? topic.display_name
) {
<div
class="topic-item"
[style.--t]="getTopicColor(topic)">
<button
type="button"
class="topic-item-header"
[class.is-expanded]="expandedTopicId === topic.id"
(click)="toggleTopic(topic.id)">
<span class="topic-item-name">{{
topic.display_name
}}</span>
<mat-icon>{{
expandedTopicId === topic.id
? 'expand_less'
: 'expand_more'
}}</mat-icon>
</button>
@if (expandedTopicId === topic.id) {
<div class="topic-item-body">
@if (topic.source_keyword) {
<p class="kw-suggestion-label">
Vorgeschlagen durch das Schlüsselwort im Text:
</p>
<button
type="button"
class="kw-pill"
(click)="scrollToKeyword(topic.source_keyword)">
»{{ topic.source_keyword }}«
</button>
<p class="kw-hint">
Im Artikel hervorgehoben · klicken zum Suche zu
öffnen
</p>
} @else {
<p class="placeholder">
Kein Schlüsselwort verknüpft.
</p>
}
</div>
}
</div>
}
</div>
} @else {
<p class="placeholder">
Keine Themen oder Schlüsselwörter gefunden.
</p>
}
</div>
}
</div>
</div>
@@ -54,7 +54,7 @@
.detail-layout {
display: grid;
grid-template-columns: 1fr 280px;
grid-template-columns: 1fr 288px;
gap: 40px;
align-items: start;
}
@@ -137,60 +137,121 @@ main {
margin: 0;
color: var(--sg-text-muted);
font-style: italic;
font-size: 13px;
}
.article-actions {
margin-top: 32px;
}
// ── Sidebar ──────────────────────────────────────────────────────────────────
.sidebar {
display: flex;
flex-direction: column;
gap: 16px;
position: sticky;
top: 24px;
max-height: calc(100vh - 48px);
overflow-y: auto;
}
.sidebar-card {
padding: 20px;
border: 1px solid #d7e4ff;
border-radius: 16px;
background: #ffffff;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
overflow: hidden;
}
h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 14px;
font-size: 14px;
font-weight: 600;
color: var(--sg-text);
// ── Accordion ────────────────────────────────────────────────────────────────
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
color: var(--sg-text-muted);
}
.accordion-panel {
display: block;
}
.accordion-header {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 16px 20px;
background: none;
border: none;
cursor: pointer;
text-align: left;
font-size: 14px;
font-weight: 600;
color: var(--sg-text);
transition: background 0.12s;
&:hover {
background: #f6f9ff;
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
color: var(--sg-text-muted);
flex-shrink: 0;
}
}
.accordion-title {
flex: 1;
}
.count-badge {
padding: 2px 7px;
border-radius: 999px;
background: #e8effe;
color: #3b5bd6;
font-size: 11px;
font-weight: 700;
}
.info-icon {
flex-shrink: 0;
font-size: 16px;
width: 16px;
height: 16px;
color: var(--sg-text-muted);
opacity: 0.7;
cursor: default;
&:hover {
opacity: 1;
}
}
.chevron {
transition: transform 0.2s ease;
color: var(--sg-text-muted) !important;
&.rotated {
transform: rotate(-90deg);
}
}
.accordion-body {
padding: 0 20px 16px;
}
// ── Persons ───────────────────────────────────────────────────────────────────
.person-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 375px;
overflow-y: auto;
padding-right: 4px;
gap: 6px;
}
.person-item {
display: grid;
grid-template-columns: 38px minmax(0, 1fr) auto;
gap: 11px;
grid-template-columns: 36px minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
padding: 12px;
padding: 10px 12px;
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-muted);
}
@@ -232,32 +293,200 @@ main {
.avatar {
display: grid;
place-items: center;
width: 38px;
height: 38px;
width: 36px;
height: 36px;
border-radius: 50%;
background: #e5ecfb;
color: var(--sg-text);
font-size: 15px;
font-size: 13px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
flex-shrink: 0;
}
.person-name {
color: var(--sg-text);
font-size: 13px;
font-weight: 700;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
// ── Persons pagination ────────────────────────────────────────────────────────
.persons-pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
margin-top: 8px;
}
.page-btn {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border: 1px solid #d7e4ff;
border-radius: 8px;
background: none;
cursor: pointer;
color: var(--sg-text-muted);
transition: background 0.12s;
&:hover:not(:disabled) {
background: #f0f6ff;
color: var(--sg-text);
}
&:disabled {
opacity: 0.35;
cursor: default;
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
.page-indicator {
font-size: 12px;
color: var(--sg-text-muted);
min-width: 36px;
text-align: center;
}
// ── Topic accordion items ─────────────────────────────────────────────────────
.topics-accordion {
display: flex;
flex-direction: column;
gap: 8px;
}
.topic-item {
border-radius: 12px;
overflow: hidden;
border: 1.5px solid color-mix(in srgb, var(--t) 38%, #ffffff);
}
.topic-item-header {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 11px 14px;
background: color-mix(in srgb, var(--t) 13%, #ffffff);
color: color-mix(in srgb, var(--t) 90%, #0f172a);
border: none;
cursor: pointer;
text-align: left;
font-size: 13px;
font-weight: 600;
line-height: 1.35;
transition: background 0.15s;
&:hover {
background: color-mix(in srgb, var(--t) 22%, #ffffff);
}
&.is-expanded {
background: var(--t);
color: #ffffff;
mat-icon {
color: rgba(255, 255, 255, 0.85);
}
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
flex-shrink: 0;
color: color-mix(in srgb, var(--t) 70%, #0f172a);
}
}
.topic-item-name {
flex: 1;
}
.topic-item-body {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
padding: 14px 14px 14px;
background: #ffffff;
}
.kw-suggestion-label {
margin: 0;
font-size: 12px;
color: var(--sg-text-muted);
}
.kw-pill {
display: inline-flex;
align-items: center;
justify-content: center;
width: 100%;
padding: 6px 14px;
border-radius: 999px;
border: 1.5px solid color-mix(in srgb, var(--t) 50%, #ffffff);
background: color-mix(in srgb, var(--t) 10%, #ffffff);
color: color-mix(in srgb, var(--t) 90%, #0f172a);
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: background 0.12s;
&:hover {
background: color-mix(in srgb, var(--t) 22%, #ffffff);
}
}
.kw-hint {
margin: 0;
font-size: 11px;
color: var(--sg-text-muted);
}
// ── Topics & Keywords ─────────────────────────────────────────────────────────
.chip-group {
display: flex;
flex-direction: column;
gap: 8px;
& + .chip-group {
margin-top: 14px;
}
}
.chip-group-label {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--sg-text-muted);
}
.chip-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
gap: 6px;
}
.topic-chip {
display: inline-flex;
align-items: center;
padding: 6px 12px;
padding: 5px 11px;
border: 1px solid var(--topic-border);
border-radius: 8px;
background: var(--topic-bg);
@@ -267,6 +496,22 @@ main {
line-height: 1.25;
}
.kw-chip {
cursor: pointer;
transition:
box-shadow 0.12s,
background 0.12s;
&:hover {
box-shadow: 0 0 0 2px var(--topic-border);
}
&.is-active {
box-shadow: 0 0 0 2px var(--topic-color);
font-weight: 600;
}
}
.purple {
--topic-border: #d8cafe;
--topic-bg: #f6f0ff;
@@ -296,3 +541,39 @@ main {
--topic-bg: #fff1f5;
--topic-color: #d12f61;
}
// ── Keyword highlights in article text ───────────────────────────────────────
@keyframes kw-flash {
0% {
background: color-mix(in srgb, var(--t) 45%, #ffffff);
}
40% {
background: color-mix(in srgb, var(--t) 45%, #ffffff);
}
100% {
background: transparent;
}
}
:host ::ng-deep .kw-mark {
background: transparent;
color: var(--t);
text-decoration: underline;
text-decoration-color: var(--t);
text-decoration-style: solid;
text-decoration-thickness: 2px;
text-underline-offset: 2px;
font-weight: inherit;
border-radius: 2px;
padding: 0 1px;
transition: background 0.15s;
&:hover {
background: color-mix(in srgb, var(--t) 15%, #ffffff);
}
&.kw-flash {
animation: kw-flash 2.4s ease-out forwards;
}
}
@@ -1,13 +1,23 @@
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { Location, NgClass } from '@angular/common';
import {
Component,
DestroyRef,
ElementRef,
OnInit,
ViewChild,
inject,
} from '@angular/core';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { WorksService } from '../../api';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
interface MentionedPerson {
name: string;
@@ -15,6 +25,15 @@ interface MentionedPerson {
person_id?: string | null;
}
interface MatchedTopic {
id?: string | null;
display_name?: string | null;
subfield_name?: string | null;
field_name?: string | null;
domain_name?: string | null;
source_keyword?: string | null;
}
interface NewsArticleDetail {
id: string;
date?: string | null;
@@ -25,6 +44,7 @@ interface NewsArticleDetail {
relevant?: boolean;
authors?: MentionedPerson[];
keywords?: string[];
topics?: MatchedTopic[];
}
@Component({
@@ -33,28 +53,83 @@ interface NewsArticleDetail {
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
MatTooltipModule,
RouterLink,
NgClass,
],
templateUrl: './news-detail.component.html',
styleUrl: './news-detail.component.scss',
})
export class NewsDetailComponent implements OnInit {
@ViewChild('articleBody') articleBodyRef?: ElementRef<HTMLElement>;
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly httpClient = inject(HttpClient);
private readonly worksService = inject(WorksService);
private readonly location = inject(Location);
private readonly router = inject(Router);
private readonly sanitizer = inject(DomSanitizer);
article: NewsArticleDetail | null = null;
highlightedContent: SafeHtml = this.sanitizer.bypassSecurityTrustHtml('');
loading = false;
notFound = false;
private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink'];
openPanel: 'persons' | 'topics' | null = 'persons';
expandedTopicId: string | null = null;
chipColor(index: number): string {
return this.chipColors[index % this.chipColors.length];
personsPage = 0;
readonly personsPageSize = 5;
get pagedPersons(): MentionedPerson[] {
const authors = this.article?.authors ?? [];
return authors.slice(
this.personsPage * this.personsPageSize,
(this.personsPage + 1) * this.personsPageSize,
);
}
get personsPageCount(): number {
return Math.ceil(
(this.article?.authors?.length ?? 0) / this.personsPageSize,
);
}
getTopicColor(topic: MatchedTopic): string {
return topicHierarchyColor({
id: topic.id,
name: topic.display_name,
field_name: topic.field_name,
domain_name: topic.domain_name,
});
}
personInitials(name: string): string {
const parts = name.trim().split(/\s+/);
if (parts.length === 1) return parts[0].charAt(0).toUpperCase();
return (
parts[0].charAt(0) + parts[parts.length - 1].charAt(0)
).toUpperCase();
}
toggleTopic(id: string | null | undefined): void {
this.expandedTopicId = this.expandedTopicId === id ? null : (id ?? null);
}
scrollToKeyword(keyword: string): void {
const body = this.articleBodyRef?.nativeElement;
if (!body) return;
body
.querySelectorAll<HTMLElement>('.kw-flash')
.forEach((el) => el.classList.remove('kw-flash'));
const marks = body.querySelectorAll<HTMLElement>('[data-kw]');
for (const mark of Array.from(marks)) {
if (mark.dataset['kw']?.toLowerCase() === keyword.toLowerCase()) {
mark.scrollIntoView({ behavior: 'smooth', block: 'center' });
mark.classList.add('kw-flash');
setTimeout(() => mark.classList.remove('kw-flash'), 2400);
break;
}
}
}
ngOnInit(): void {
@@ -71,11 +146,7 @@ export class NewsDetailComponent implements OnInit {
navigateBack(): void {
this.location.back();
}
onKeywordClick(keyword: string): void {
this.router.navigate(['/keywords'], {
queryParams: { selected: keyword, manual: keyword },
});
}
formatDate(dateStr?: string | null): string {
if (!dateStr) return '-';
const date = new Date(dateStr);
@@ -97,6 +168,9 @@ export class NewsDetailComponent implements OnInit {
.subscribe({
next: (article) => {
this.article = article;
this.highlightedContent = this.buildHighlightedContent(article);
this.expandedTopicId = null;
this.personsPage = 0;
this.loading = false;
},
error: () => {
@@ -105,4 +179,63 @@ export class NewsDetailComponent implements OnInit {
},
});
}
private buildHighlightedContent(article: NewsArticleDetail): SafeHtml {
const text = article.full_content;
if (!text) return this.sanitizer.bypassSecurityTrustHtml('');
const keywords = article.keywords ?? [];
const keywordColorMap = new Map<string, string>();
for (const topic of article.topics ?? []) {
if (topic.source_keyword) {
keywordColorMap.set(
topic.source_keyword.toLowerCase(),
this.getTopicColor(topic),
);
}
}
const orphanColors = [
'#7255d9',
'#0b63ce',
'#24834f',
'#c67500',
'#d12f61',
];
let orphanIdx = 0;
let html = this.escapeHtml(text);
if (keywords.length) {
[...keywords]
.sort((a, b) => b.length - a.length)
.forEach((kw) => {
let color = keywordColorMap.get(kw.toLowerCase());
if (!color) {
color = orphanColors[orphanIdx % orphanColors.length];
orphanIdx++;
}
const kwHtml = this.escapeHtml(kw);
const re = new RegExp(
`(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`,
'gi',
);
html = html.replace(
re,
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
);
});
}
return this.sanitizer.bypassSecurityTrustHtml(html);
}
private escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
private escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
}
@@ -0,0 +1,164 @@
<section class="login-page">
<div class="login-panel">
<div class="brand-block">
<span class="eyebrow">SmartGuide Account Portal</span>
<h1>Passwort zurücksetzen</h1>
<p>Gib ein neues Passwort für Dein Konto ein.</p>
</div>
@if (passwordChanged()) {
<div class="login-form">
<div class="code-intro">
<mat-icon>check_circle</mat-icon>
<div>
<strong>Passwort geändert</strong>
<span>
Dein Passwort wurde erfolgreich geändert. Bitte melde Dich mit dem
neuen Passwort an.
</span>
</div>
</div>
<button
mat-flat-button
color="primary"
class="submit-button"
type="button"
routerLink="/login">
Zurück zum Login
</button>
</div>
} @else if (!hasToken()) {
<div class="login-form">
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<div>
<strong>Ungültiger Link</strong>
<span>
Der Link zum Zurücksetzen des Passworts ist ungültig oder
unvollständig.
</span>
</div>
</div>
<
<div class="form-actions">
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
<a class="auth-link" routerLink="/forgot-password"
>Neuen Link anfordern</a
>
</div>
</div>
} @else if (linkInvalid()) {
<div class="login-form">
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<div>
<strong>Link nicht mehr gültig</strong>
<span>
Der Link zum Zurücksetzen des Passworts ist abgelaufen oder wurde
bereits verwendet.
</span>
</div>
</div>
<div class="form-actions">
<a class="auth-link" routerLink="/forgot-password"
>Neuen Link anfordern</a
>
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
</div>
</div>
} @else {
<form class="login-form" [formGroup]="form" (ngSubmit)="resetPassword()">
<mat-form-field class="field" appearance="outline">
<mat-label>Neues Passwort</mat-label>
<input
matInput
[type]="showPasswords() ? 'text' : 'password'"
autocomplete="new-password"
formControlName="newPassword" />
<button
mat-icon-button
matSuffix
type="button"
[attr.aria-label]="
showPasswords() ? 'Passwort verbergen' : 'Passwort anzeigen'
"
(click)="showPasswords.set(!showPasswords())">
<mat-icon>
{{ showPasswords() ? 'visibility' : 'visibility_off' }}
</mat-icon>
</button>
@if (form.controls.newPassword.hasError('required')) {
<mat-error>Neues Passwort ist erforderlich.</mat-error>
} @else if (form.controls.newPassword.hasError('minlength')) {
<mat-error>Passwort muss mindestens 8 Zeichen haben.</mat-error>
} @else if (form.controls.newPassword.hasError('maxlength')) {
<mat-error>Passwort darf maximal 64 Zeichen haben.</mat-error>
}
</mat-form-field>
<mat-form-field class="field" appearance="outline">
<mat-label>Neues Passwort wiederholen</mat-label>
<input
matInput
[type]="showPasswords() ? 'text' : 'password'"
autocomplete="new-password"
formControlName="confirmPassword" />
<button
mat-icon-button
matSuffix
type="button"
[attr.aria-label]="
showPasswords() ? 'Passwort verbergen' : 'Passwort anzeigen'
"
(click)="showPasswords.set(!showPasswords())">
<mat-icon>
{{ showPasswords() ? 'visibility' : 'visibility_off' }}
</mat-icon>
</button>
@if (form.controls.confirmPassword.hasError('required')) {
<mat-error>Bitte wiederhole das neue Passwort.</mat-error>
} @else if (
form.controls.confirmPassword.hasError('passwordsMismatch')
) {
<mat-error>Die Passwörter stimmen nicht überein.</mat-error>
}
</mat-form-field>
@if (errorMessage()) {
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<div>
<strong>Fehler</strong>
<span>{{ errorMessage() }}</span>
</div>
</div>
}
<button
mat-flat-button
color="primary"
class="submit-button"
type="submit"
[disabled]="form.invalid || isSubmitting()">
@if (isSubmitting()) {
Passwort wird geändert...
} @else {
Passwort ändern
}
</button>
<div class="form-actions form-actions-single">
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
</div>
</form>
}
</div>
</section>
@@ -0,0 +1,155 @@
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
AbstractControl,
FormControl,
FormGroup,
ReactiveFormsModule,
ValidationErrors,
Validators,
} from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { finalize } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { CredentialService } from '../../shared/services/credential.service';
@Component({
selector: 'app-reset-password',
standalone: true,
imports: [
ReactiveFormsModule,
RouterLink,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatSnackBarModule,
],
templateUrl: './reset-password.component.html',
styleUrl: '../app-login/app-login.component.scss',
})
export class ResetPasswordComponent {
private readonly destroyRef = inject(DestroyRef);
private readonly snackBar = inject(MatSnackBar);
private readonly resetToken = signal<string | undefined>(undefined);
readonly isSubmitting = signal(false);
readonly passwordChanged = signal(false);
readonly showPasswords = signal(false);
readonly linkInvalid = signal(false);
readonly errorMessage = signal<string | undefined>(undefined);
readonly form = new FormGroup({
newPassword: new FormControl<string>('', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(64),
]),
confirmPassword: new FormControl<string>('', [Validators.required]),
});
constructor(
private readonly credentialService: CredentialService,
route: ActivatedRoute,
) {
const token = route.snapshot.queryParamMap.get('token') ?? undefined;
this.resetToken.set(token);
this.form.controls.confirmPassword.addValidators(
this.passwordsMatchValidator.bind(this),
);
this.form.controls.newPassword.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.form.controls.confirmPassword.updateValueAndValidity();
});
}
hasToken(): boolean {
return !!this.resetToken();
}
resetPassword(): void {
if (!this.hasToken()) {
this.linkInvalid.set(true);
this.errorMessage.set(
'Der Link zum Zurücksetzen des Passworts ist ungültig oder unvollständig.',
);
return;
}
if (this.form.invalid || this.isSubmitting()) {
this.form.markAllAsTouched();
return;
}
const resetToken = this.resetToken();
const newPassword = this.form.controls.newPassword.value ?? '';
if (!resetToken) {
this.linkInvalid.set(true);
return;
}
this.isSubmitting.set(true);
this.errorMessage.set(undefined);
this.form.disable();
this.credentialService
.resetPassword(resetToken, newPassword)
.pipe(
finalize(() => {
this.isSubmitting.set(false);
}),
)
.subscribe({
next: () => {
this.passwordChanged.set(true);
},
error: (error: HttpErrorResponse) => {
console.error('Password reset failed', error);
if (
error.status === 400 ||
error.status === 401 ||
error.status === 403 ||
error.status === 404
) {
this.linkInvalid.set(true);
this.snackBar.open(
'Der Link zum Zurücksetzen des Passworts ist abgelaufen oder wurde bereits verwendet.',
'OK',
{ duration: 7000 },
);
return;
}
this.errorMessage.set(
'Das Passwort konnte nicht geändert werden. Bitte versuche es später erneut.',
);
this.form.enable();
},
});
}
private passwordsMatchValidator(
control: AbstractControl,
): ValidationErrors | null {
const newPassword = this.form.controls.newPassword.value;
const confirmPassword = control.value;
if (!newPassword || !confirmPassword) {
return null;
}
return newPassword === confirmPassword ? null : { passwordsMismatch: true };
}
}
@@ -0,0 +1,14 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { CredentialService } from '../services/credential.service';
export const guestOnlyGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
if (credentialService.isAuthenticated()) {
return router.createUrlTree(['/dashboard']);
}
return true;
};
@@ -49,6 +49,17 @@ export interface StoredAuthState {
accessToken: AccessToken | null;
}
export interface PasswordResetRequestResponse {
status: string;
reset_link_created: boolean;
rate_limited: boolean;
retry_after_seconds?: number;
}
export interface ResetPasswordResponse {
status: string;
}
const EXPIRY_SKEW_MS = 10 * 1000; // 10 seconds
@Injectable({
@@ -201,6 +212,34 @@ export class CredentialService {
);
}
public requestPasswordReset(
email: string,
): Observable<PasswordResetRequestResponse> {
return this.authService.requestPasswordReset(
{
email: email.trim().toLowerCase(),
},
undefined,
undefined,
{ context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
) as Observable<PasswordResetRequestResponse>;
}
public resetPassword(
resetToken: string,
newPassword: string,
): Observable<ResetPasswordResponse> {
return this.authService.resetPassword(
{
reset_token: resetToken,
new_password: newPassword,
},
undefined,
undefined,
{ context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
) as Observable<ResetPasswordResponse>;
}
public loginWithOtk(
accountId: string,
emailCode: string,
@@ -368,8 +407,4 @@ export class CredentialService {
await this.router.navigate(['/login'], { replaceUrl: true });
}
}
public registerAccount(_data: unknown): Observable<never> {
return throwError(() => new Error('Registration is temporarily disabled.'));
}
}
@@ -45,9 +45,19 @@
}
@for (topic of topics(); track topic) {
<mat-option [value]="topic.display_name">{{
topic.display_name
}}</mat-option>
<mat-option [value]="topic.display_name">
<div class="topic-option">
<div class="topic-main">
{{ topic.display_name }}
</div>
<div class="topic-path">
{{ topic.domain?.display_name }} >
{{ topic.field?.display_name }} >
{{ topic.subfield?.display_name }}
</div>
</div></mat-option
>
}
@if (
@@ -13,3 +13,21 @@ mat-form-field {
.topic-field {
width: 100%;
}
.topic-option {
display: flex;
flex-direction: column;
line-height: 1.2;
}
.topic-main {
font-size: 14px;
font-weight: 500;
}
.topic-path {
font-size: 11px;
color: rgba(0, 0, 0, 0.6);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}