diff --git a/backend/cron_state.db-shm b/backend/cron_state.db-shm index 5a5aeb2..38199aa 100644 Binary files a/backend/cron_state.db-shm and b/backend/cron_state.db-shm differ diff --git a/backend/cron_state.db-wal b/backend/cron_state.db-wal index 50bd478..873ecdd 100644 Binary files a/backend/cron_state.db-wal and b/backend/cron_state.db-wal differ diff --git a/backend/src/backend/internal/authentication.py b/backend/src/backend/internal/authentication.py index 3546dad..3a1be41 100644 --- a/backend/src/backend/internal/authentication.py +++ b/backend/src/backend/internal/authentication.py @@ -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: diff --git a/backend/src/backend/internal/rss_reader.py b/backend/src/backend/internal/rss_reader.py index c7e00d8..ffeb291 100644 --- a/backend/src/backend/internal/rss_reader.py +++ b/backend/src/backend/internal/rss_reader.py @@ -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"]) diff --git a/backend/src/backend/main.py b/backend/src/backend/main.py index 897b03a..409f598 100644 --- a/backend/src/backend/main.py +++ b/backend/src/backend/main.py @@ -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() diff --git a/backend/src/backend/routers/users.py b/backend/src/backend/routers/users.py index 9297636..dc29ba0 100644 --- a/backend/src/backend/routers/users.py +++ b/backend/src/backend/routers/users.py @@ -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() diff --git a/blog/astro.config.mjs b/blog/astro.config.mjs index 45e7b64..8f5f8dc 100644 --- a/blog/astro.config.mjs +++ b/blog/astro.config.mjs @@ -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()] }); diff --git a/blog/package-lock.json b/blog/package-lock.json index c2a6537..324cd67 100644 --- a/blog/package-lock.json +++ b/blog/package-lock.json @@ -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": { diff --git a/blog/package.json b/blog/package.json index 89acd3c..26a5d70 100644 --- a/blog/package.json +++ b/blog/package.json @@ -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" } } diff --git a/blog/src/islands/DeleteUser.tsx b/blog/src/islands/DeleteUser.tsx new file mode 100644 index 0000000..1402740 --- /dev/null +++ b/blog/src/islands/DeleteUser.tsx @@ -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) => { + 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 ( +
+

Delete user

+ + {error &&

{error}

} +
+ ); +} diff --git a/blog/src/islands/LoginForm.tsx b/blog/src/islands/LoginForm.tsx new file mode 100644 index 0000000..3083cfd --- /dev/null +++ b/blog/src/islands/LoginForm.tsx @@ -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) => { + 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 ( +
+

Login

+
+ setUserCode(e.currentTarget.value)} + placeholder="Enter your code" + required + /> + + {error &&

{error}

} +
+
+ ); +} diff --git a/blog/src/islands/RegisterForm.tsx b/blog/src/islands/RegisterForm.tsx new file mode 100644 index 0000000..044b7f9 --- /dev/null +++ b/blog/src/islands/RegisterForm.tsx @@ -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({ 'email': '', 'name': '', 'subscription': true }); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + + const handleRegistration = async (e: JSX.TargetedEvent) => { + e.preventDefault(); + setLoading(true); + setError(''); + + try { + await api.register(user); + } catch (err) { + setError(err instanceof Error ? err.message : 'Registrierung fehlgeschlagen'); + } finally { + setLoading(false); + } + }; + + return ( +
+

Registrieren

+
+ setUser({ ...user, email: e.currentTarget.value })} + placeholder="Email" + required + /> + setUser({ ...user, name: e.currentTarget.value })} + placeholder="Name" + required + /> + setUser({ ...user, subscription: e.currentTarget.checked })} + /> + + {error &&

{error}

} +
+
+ ); +} diff --git a/blog/src/islands/ToggleSubscription.tsx b/blog/src/islands/ToggleSubscription.tsx new file mode 100644 index 0000000..3d0b184 --- /dev/null +++ b/blog/src/islands/ToggleSubscription.tsx @@ -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(false); + const [error, setError] = useState(''); + + useEffect(() => { + const fetchUser = async () => { + const user = await api.getUserInfo(); + setSubscription(user.subscription); + }; + fetchUser(); + }, []); + + const handleSubscription = async (e: JSX.TargetedEvent) => { + e.preventDefault(); + setError(''); + + try { + console.log(subscription) + api.toggleSubscription(subscription) + } catch (err) { + setError(err instanceof Error ? err.message : 'Registrierung fehlgeschlagen'); + } + }; + + return ( +
+

Toggle Newsletter Subscription

+
+ { setSubscription(e.currentTarget.checked) }} + /> + + {error &&

{error}

} +
+
+ ); +} diff --git a/blog/src/lib/api.ts b/blog/src/lib/api.ts new file mode 100644 index 0000000..ac63195 --- /dev/null +++ b/blog/src/lib/api.ts @@ -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( + endpoint: string, + options: RequestInit = {} + ): Promise { + 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 { + return this.fetchAPI(`/users/me`); + } + + async register(user: User): Promise { + return this.fetchAPI(`/users`, { + method: 'POST', + body: JSON.stringify(user) + }) + } + + async login(userCode: string): Promise { + 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 { + 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 { + return await this.fetchAPI('/users/me', { + method: "DELETE" + }) + } + + async approveNewsletter(secret: string): Promise { + 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(); diff --git a/blog/src/pages/admin/newsletter/[secret].astro b/blog/src/pages/admin/newsletter/[secret].astro new file mode 100644 index 0000000..62f3047 --- /dev/null +++ b/blog/src/pages/admin/newsletter/[secret].astro @@ -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 } + })); +} + +--- + +

{product.name}

diff --git a/blog/src/pages/index.astro b/blog/src/pages/index.astro index b2bed7a..a9d417b 100644 --- a/blog/src/pages/index.astro +++ b/blog/src/pages/index.astro @@ -12,7 +12,7 @@ const allPostsSorted = (await getCollection('posts')).sort( const [mostRecentPost, ...sortedPosts] = allPostsSorted; --- -
+
diff --git a/blog/src/pages/nutzer-verwaltung.astro b/blog/src/pages/nutzer-verwaltung.astro new file mode 100644 index 0000000..c9aa5de --- /dev/null +++ b/blog/src/pages/nutzer-verwaltung.astro @@ -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"; + + +--- + +
+ + + + +
\ No newline at end of file