feat: refactor authentication handling to use centralized Stalwart credentials management

This commit is contained in:
Linus Rath
2026-03-14 15:55:59 +01:00
parent 6fc27804d6
commit 85b5b3c4f1
7 changed files with 94 additions and 136 deletions
+5 -33
View File
@@ -1,34 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
/**
* Extract the user's JMAP server URL and auth header from the session cookie
* or from the Authorization header passed by the client.
*/
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string; username: string } | null> {
// Try Authorization header first (for bearer/basic auth forwarding)
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
const username = request.headers.get('X-JMAP-Username');
if (authHeader && serverUrl && username) {
return { serverUrl, authHeader, username };
}
// Fall back to session cookie
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return { serverUrl: credentials.serverUrl, authHeader: basic, username: credentials.username };
}
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
/**
* GET /api/account/stalwart/auth
@@ -36,12 +8,12 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
export async function GET(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const response = await fetch(`${creds.serverUrl}/api/account/auth`, {
const response = await fetch(`${creds.apiUrl}/api/account/auth`, {
method: 'GET',
headers: { 'Authorization': creds.authHeader },
});
@@ -69,14 +41,14 @@ export async function GET(request: NextRequest) {
*/
export async function POST(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json();
const response = await fetch(`${creds.serverUrl}/api/account/auth`, {
const response = await fetch(`${creds.apiUrl}/api/account/auth`, {
method: 'POST',
headers: {
'Authorization': creds.authHeader,