Files
Webklar-Kundenbereich/server/services/appwriteClient.js
2026-05-23 00:36:45 +02:00

117 lines
3.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { config } from '../config.js'
import { deleteUserSession, getUserById } from './appwriteAdmin.js'
const DEBUG_LOG = (location, message, data, hypothesisId) => {
// #region agent log
fetch('http://127.0.0.1:7281/ingest/30e8e71c-b377-4e72-84f9-593826c6d234', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Debug-Session-Id': '80bbfc' },
body: JSON.stringify({
sessionId: '80bbfc',
location,
message,
data,
hypothesisId,
timestamp: Date.now(),
}),
}).catch(() => {})
// #endregion
}
function appwriteHeaders() {
return {
'Content-Type': 'application/json',
'X-Appwrite-Project': config.appwrite.projectId,
}
}
async function appwriteFetch(path, { method = 'GET', body } = {}) {
const url = `${config.appwrite.endpoint}${path}`
const response = await fetch(url, {
method,
headers: appwriteHeaders(),
body: body ? JSON.stringify(body) : undefined,
})
let data = null
const text = await response.text()
if (text) {
try {
data = JSON.parse(text)
} catch {
data = { message: text }
}
}
if (!response.ok) {
const error = new Error(data?.message || `Appwrite ${response.status}`)
error.status = response.status === 401 ? 401 : response.status >= 500 ? 500 : 401
error.code = data?.code
error.type = data?.type
throw error
}
return data
}
/**
* Appwrite Auth per native fetch (Node 26 + node-appwrite-Agent ist inkompatibel).
* session.secret fehlt serverseitig oft userId aus Session + Users-API.
*/
export async function loginWithAppwrite(email, password) {
let session
try {
session = await appwriteFetch('/account/sessions/email', {
method: 'POST',
body: { email, password },
})
DEBUG_LOG('appwriteClient.js:session', 'createEmailPasswordSession ok', {
hasUserId: Boolean(session?.userId),
sessionId: session?.$id || null,
}, 'H6')
} catch (err) {
DEBUG_LOG('appwriteClient.js:session', 'createEmailPasswordSession fail', {
message: err?.message?.slice(0, 120),
code: err?.code,
}, 'H1')
const error = new Error(err.message || 'Anmeldung fehlgeschlagen')
error.status = err.status || 401
throw error
}
if (!session?.userId) {
const error = new Error('Appwrite-Session ohne userId.')
error.status = 500
throw error
}
let user
try {
user = await getUserById(session.userId)
DEBUG_LOG('appwriteClient.js:getUser', 'users.get ok', { userId: user?.$id || null }, 'H6')
} catch (err) {
DEBUG_LOG('appwriteClient.js:getUser', 'users.get fail', {
message: err?.message?.slice(0, 120),
code: err?.code,
}, 'H7')
if (err?.message?.includes('not authorized')) {
const error = new Error(
'Server-API-Key: Scope users.read erforderlich (Appwrite Console).'
)
error.status = 500
throw error
}
user = { $id: session.userId, email, name: '' }
}
if (session.$id) {
try {
await deleteUserSession(session.userId, session.$id)
} catch {
// Portal nutzt eigene Cookie-Session
}
}
return user
}