aktueller Stand API integration

This commit is contained in:
ebby 2026-09-30 16:29:07 +02:00
parent 89e2b480a2
commit badfcfc43b
17 changed files with 339 additions and 36 deletions

Binary file not shown.

Binary file not shown.

View file

@ -30,8 +30,10 @@ security = HTTPBearer()
def get_token(credentials = Security(security)) -> str:
parts = credentials.credentials.split()
if len(parts) == 2 and parts[0].lower() == "bearer":
if parts[0].lower() == "bearer":
return parts[1]
else:
return parts[0]
raise HTTPException(status_code=403, detail="Invalid authorization format")
def decode_token(token: str)-> str | None:

View file

@ -14,7 +14,7 @@ def check_blog_rss_and_send_admin_mail():
date_string = str(article["published"])
date_object = datetime.strptime(date_string, '%a, %d %b %Y %H:%M:%S %Z')
if date_object > (datetime.now() - timedelta(days=16)):
if date_object > (datetime.now() - timedelta(days=1)):
title = str(article["title"])
description = str(article["summary"])
subtitle = str(article["subtitle"])

View file

@ -11,7 +11,7 @@ from backend.internal.rss_reader import check_blog_rss_and_send_admin_mail
app = FastAPI()
crons = Crons(app)
@crons.cron("0 14 * * *", name="RSS-Check")
@crons.cron("0 13 * * *", name="RSS-Check")
async def check_for_new_article():
check_blog_rss_and_send_admin_mail()

View file

@ -89,12 +89,14 @@ def delete(current_user: User = Depends(get_current_user), session: Session = De
session.commit()
@router.put(path="/me/subscribe", status_code=201)
@router.put(path="/me/subscription", status_code=201)
def change_subscription(
subscription: bool = Form(),
current_user: User = Depends(get_current_user),
session: Session = Depends(get_session)
):
print(subscription)
print(current_user)
current_user.subscription = subscription
session.add(current_user)
session.commit()

View file

@ -1,6 +1,7 @@
// @ts-check
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import preact from '@astrojs/preact';
// https://astro.build/config
export default defineConfig({
@ -9,5 +10,5 @@ export default defineConfig({
build: {
assets: '_assets',
},
integrations: [mdx()]
integrations: [mdx(), preact()]
});

48
blog/package-lock.json generated
View file

@ -8,10 +8,10 @@
"version": "0.0.1",
"dependencies": {
"@astrojs/mdx": "^7.0.8",
"@astrojs/preact": "^6.0.2",
"@astrojs/preact": "^6.0.5",
"@astrojs/rss": "^4.0.19",
"astro": "^7.2.2",
"preact": "^10.29.0"
"preact": "^10.29.8"
},
"engines": {
"node": ">=22.12.0"
@ -206,9 +206,9 @@
}
},
"node_modules/@astrojs/internal-helpers": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.11.0.tgz",
"integrity": "sha512-3rzxJ+xbo0+8YyqOzLziIN32wmsHdCjEVz2sGOpRxJ+Ben/KiLph4ItxBy1abEL+E8fkRzqjg0rfXmaHJGw9JA==",
"license": "MIT",
"dependencies": {
"@types/hast": "^3.0.4",
@ -297,12 +297,12 @@
}
},
"node_modules/@astrojs/preact": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/@astrojs/preact/-/preact-6.0.2.tgz",
"integrity": "sha512-OoV/1KeGpRU8f9a+jBk2q2GK05jqjnRg7H+ZN8i48FBKrLJQj+4nU/Vg+JSsvhZ9PZtku0kS2vyFBJ8SGXoTiQ==",
"version": "6.0.5",
"resolved": "https://registry.npmjs.org/@astrojs/preact/-/preact-6.0.5.tgz",
"integrity": "sha512-ONNVrPUM3PxEGJ0Z1MseRRXn0MCirTxEzH84ZUphD8WoR2WOvgHAf4C/0RVc4dmJigytHG3UFg+hsZd/oFz03w==",
"license": "MIT",
"dependencies": {
"@astrojs/internal-helpers": "0.10.2",
"@astrojs/internal-helpers": "0.11.0",
"@preact/preset-vite": "^2.10.5",
"@preact/signals": "^2.8.2",
"devalue": "^5.8.1",
@ -2637,22 +2637,6 @@
}
}
},
"node_modules/astro/node_modules/@astrojs/internal-helpers": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.11.0.tgz",
"integrity": "sha512-3rzxJ+xbo0+8YyqOzLziIN32wmsHdCjEVz2sGOpRxJ+Ben/KiLph4ItxBy1abEL+E8fkRzqjg0rfXmaHJGw9JA==",
"license": "MIT",
"dependencies": {
"@types/hast": "^3.0.4",
"@types/mdast": "^4.0.4",
"js-yaml": "^4.3.0",
"picomatch": "^4.0.4",
"retext-smartypants": "^6.2.0",
"shiki": "^4.0.2",
"smol-toml": "^1.6.0",
"unified": "^11.0.5"
}
},
"node_modules/astro/node_modules/@astrojs/markdown-satteri": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.4.1.tgz",
@ -5830,13 +5814,21 @@
}
},
"node_modules/preact": {
"version": "10.29.2",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.29.2.tgz",
"integrity": "sha512-7tNmwg/7mzzAoB/8kSg6Hl37JraAZw3Z3A0JSY7VXlZwo82Xn0G7wKbNNs2qoF4ZEEsQGTwDAroNdqKs1ofJxQ==",
"version": "10.29.8",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.29.8.tgz",
"integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
},
"peerDependencies": {
"preact-render-to-string": ">=5"
},
"peerDependenciesMeta": {
"preact-render-to-string": {
"optional": true
}
}
},
"node_modules/preact-render-to-string": {

View file

@ -13,9 +13,9 @@
},
"dependencies": {
"@astrojs/mdx": "^7.0.8",
"@astrojs/preact": "^6.0.2",
"@astrojs/preact": "^6.0.5",
"@astrojs/rss": "^4.0.19",
"astro": "^7.2.2",
"preact": "^10.29.0"
"preact": "^10.29.8"
}
}

View file

@ -0,0 +1,33 @@
import { useState } from 'preact/hooks';
import type { JSX } from 'preact';
import { api, AUTH_TOKEN_KEY } from '../lib/api';
export default function DeleteUser() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleClick = async (e: JSX.TargetedEvent<HTMLButtonElement>) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const jwt = await api.deleteUser()
} catch (err) {
setError(err instanceof Error ? err.message : 'Löschen hat nicht geklappt');
} finally {
setLoading(false);
localStorage.removeItem(AUTH_TOKEN_KEY);
}
};
return (
<div>
<h2>Delete user</h2>
<button onClick={e => handleClick(e)} disabled={loading}>
Löschen
</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
</div>
);
}

View file

@ -0,0 +1,44 @@
import { useState } from 'preact/hooks';
import type { JSX } from 'preact';
import { api, AUTH_TOKEN_KEY } from '../lib/api';
export default function LoginForm() {
const [userCode, setUserCode] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleLogin = async (e: JSX.TargetedEvent<HTMLFormElement>) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const jwt = await api.login(userCode)
localStorage.setItem(AUTH_TOKEN_KEY, jwt)
// window.location.href = '/';
} catch (err) {
setError(err instanceof Error ? err.message : 'Login failed');
} finally {
setLoading(false);
}
};
return (
<div>
<h2>Login</h2>
<form onSubmit={handleLogin}>
<input
type="text"
value={userCode}
onChange={(e) => setUserCode(e.currentTarget.value)}
placeholder="Enter your code"
required
/>
<button type="submit" disabled={loading}>
{loading ? 'Logging in...' : 'Login'}
</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
</form>
</div>
);
}

View file

@ -0,0 +1,55 @@
import { useState } from 'preact/hooks';
import type { JSX } from 'preact';
import { api, type User } from '../lib/api';
import React from 'preact/compat';
export default function RegisterForm() {
const [user, setUser] = React.useState<User>({ 'email': '', 'name': '', 'subscription': true });
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleRegistration = async (e: JSX.TargetedEvent<HTMLFormElement>) => {
e.preventDefault();
setLoading(true);
setError('');
try {
await api.register(user);
} catch (err) {
setError(err instanceof Error ? err.message : 'Registrierung fehlgeschlagen');
} finally {
setLoading(false);
}
};
return (
<div>
<h2>Registrieren</h2>
<form onSubmit={handleRegistration}>
<input
type="email"
value={user.email}
onChange={e => setUser({ ...user, email: e.currentTarget.value })}
placeholder="Email"
required
/>
<input
type="text"
value={user.name}
onChange={e => setUser({ ...user, name: e.currentTarget.value })}
placeholder="Name"
required
/>
<input
type="checkbox"
checked={user.subscription}
onChange={e => setUser({ ...user, subscription: e.currentTarget.checked })}
/>
<button type="submit" disabled={loading}>
{loading ? 'Logging in...' : 'Login'}
</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
</form>
</div>
);
}

View file

@ -0,0 +1,46 @@
import { useEffect, useState } from 'preact/hooks';
import type { JSX } from 'preact';
import { api } from '../lib/api';
import React from 'preact/compat';
export default function ToggleSubscription() {
const [subscription, setSubscription] = React.useState<boolean>(false);
const [error, setError] = useState('');
useEffect(() => {
const fetchUser = async () => {
const user = await api.getUserInfo();
setSubscription(user.subscription);
};
fetchUser();
}, []);
const handleSubscription = async (e: JSX.TargetedEvent<HTMLFormElement>) => {
e.preventDefault();
setError('');
try {
console.log(subscription)
api.toggleSubscription(subscription)
} catch (err) {
setError(err instanceof Error ? err.message : 'Registrierung fehlgeschlagen');
}
};
return (
<div>
<h2>Toggle Newsletter Subscription</h2>
<form onSubmit={handleSubscription}>
<input
type="checkbox"
checked={subscription}
onChange={e => { setSubscription(e.currentTarget.checked) }}
/>
<button type="submit">
Absenden
</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
</form>
</div>
);
}

94
blog/src/lib/api.ts Normal file
View file

@ -0,0 +1,94 @@
export interface User {
email: string;
name: string;
subscription: boolean;
}
const API_BASE = import.meta.env.PUBLIC_API_URL;
export const AUTH_TOKEN_KEY = 'authToken'
class BlauwasserAPI {
private async fetchAPI<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = new URL(endpoint, API_BASE);
const defaultHeaders: HeadersInit = {
'Content-Type': 'application/json',
};
if (typeof window !== 'undefined') {
const jwt = localStorage.getItem(AUTH_TOKEN_KEY);
if (jwt) {
defaultHeaders['Authorization'] = `Bearer ${jwt}`;
}
}
const response = await fetch(url, {
...options,
headers: { ...defaultHeaders, ...options.headers },
});
if (!response.ok) {
throw new Error(`API Error ${response.status}: ${response.statusText}`);
}
return response.json();
}
async getUserInfo(): Promise<User> {
return this.fetchAPI(`/users/me`);
}
async register(user: User): Promise<void> {
return this.fetchAPI(`/users`, {
method: 'POST',
body: JSON.stringify(user)
})
}
async login(userCode: string): Promise<string> {
const formData = new URLSearchParams();
formData.append('user_code', userCode);
return await this.fetchAPI('/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData,
});
}
async toggleSubscription(subscription: boolean): Promise<void> {
const formData = new URLSearchParams();
formData.append('subscription', JSON.stringify(subscription));
return await this.fetchAPI('/users/me/subscription', {
method: 'PUT',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData,
});
}
async deleteUser(): Promise<void> {
return await this.fetchAPI('/users/me', {
method: "DELETE"
})
}
async approveNewsletter(secret: string): Promise<void> {
const formData = new URLSearchParams();
formData.append('secret', JSON.stringify(secret));
return await this.fetchAPI('/newsletter/approve', {
method: 'POST',
body: formData
})
}
}
export const api = new BlauwasserAPI();

View file

@ -0,0 +1,18 @@
---
import { api } from '../../../lib/api';
const { secret } = Astro.props;
export async function getStaticPaths() {
const response = await api.approveNewsletter(secret);
return response.map(product => ({
params: { id: product.id },
props: { product }
}));
}
---
<h1>{product.name}</h1>

View file

@ -12,7 +12,7 @@ const allPostsSorted = (await getCollection('posts')).sort(
const [mostRecentPost, ...sortedPosts] = allPostsSorted;
---
<Main title="Startseite">
<Main>
<PostPreviewLarge
post={mostRecentPost.data}
/>

View file

@ -0,0 +1,16 @@
---
import DeleteUser from "../islands/DeleteUser";
import LoginForm from "../islands/LoginForm";
import RegisterForm from "../islands/RegisterForm";
import ToggleSubscription from "../islands/ToggleSubscription";
import Main from "../layouts/Main.astro";
---
<Main>
<RegisterForm client:only="preact" />
<LoginForm client:only="preact" />
<ToggleSubscription client:only="preact" />
<DeleteUser client:only="preact" />
</Main>