import http from 'http' import { readBodyJson } from '../server'; import { getModels, getTools } from './ollamaCalls'; export const base = 'http://open-webui:8080'; type Me = { id: string; email: string; name: string; role: string; profile_image_url: string; token: string; token_type: string; expires_at: string | null; permissions: { workspace: { models: boolean; knowledge: boolean; prompts: boolean; tools: boolean; }; features: { direct_tool_servers: boolean; web_search: boolean; image_generation: boolean; code_interpreter: boolean; notes: boolean; }; }; }; export default async function loginUser(req: http.IncomingMessage, res: http.ServerResponse) { const { email, password } = await readBodyJson(req); if (!email || !password) { res.writeHead(400).end(JSON.stringify({ error: "email or password not sent" })); return; } // login with username/password const loginRes = await fetch(`${base}/api/v1/auths/signin`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email, password }), }); if (!loginRes.ok) { console.error("error logging in", await loginRes.text()); res.writeHead(401).end(); return } const upstreamCookie = loginRes.headers.get("set-cookie"), user = await loginRes.json(); // forward Set-Cookie to the browser so it stores the cookie const outHeaders: Record = { "content-type": "application/json", }; if (upstreamCookie) { outHeaders["Set-Cookie"] = upstreamCookie; } res.writeHead(200, outHeaders).end(JSON.stringify({ user })); } export async function getUser(req: http.IncomingMessage, res: http.ServerResponse) { if (!req.headers.cookie) { return res.writeHead(401).end("Not logged in"); } const cookies = Object.fromEntries(req.headers.cookie.split(';').map(c => c.split('=').map(o => o.trim()))); if (!('token' in cookies)) { return res.writeHead(401).end("Not logged in"); } const uRes = await fetch(`${base}/api/v1/auths/`, { method: "GET", headers: { "content-type": "application/json", 'Authorization': `Bearer ${cookies['token']}` }, }); if (!uRes.ok) { console.error("Error getting user", await uRes.text()); return res.writeHead(401).end(); } const uObj = await uRes.json(); uObj.models = await getModels(cookies['token']); uObj.tools = await getTools(cookies['token']); res.writeHead(200).end(JSON.stringify(uObj)); }