Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2418821691 | ||
|
|
bda7aff447 | ||
|
|
82421c1040 |
@@ -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):
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
Binary file not shown.
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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';
|
||||
@@ -37,10 +38,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,
|
||||
),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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 },
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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.'));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user