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
+4 -25
View File
@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession, encryptSession } from '@/lib/auth/crypto';
import { encryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE, SESSION_COOKIE_MAX_AGE } from '@/lib/auth/session-cookie';
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
const COOKIE_OPTIONS = {
httpOnly: true,
@@ -12,28 +13,6 @@ const COOKIE_OPTIONS = {
maxAge: SESSION_COOKIE_MAX_AGE,
};
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string; username: string; hasSessionCookie: boolean } | null> {
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) {
const cookieStore = await cookies();
const hasSessionCookie = !!cookieStore.get(SESSION_COOKIE)?.value;
return { serverUrl, authHeader, username, hasSessionCookie };
}
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, hasSessionCookie: true };
}
/**
* POST /api/account/stalwart/password
* Change user password via Stalwart PATCH /api/principal/{name}
@@ -42,7 +21,7 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
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 });
}
@@ -69,7 +48,7 @@ export async function POST(request: NextRequest) {
}
// Change password via Stalwart principal API
const response = await fetch(`${creds.serverUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
const response = await fetch(`${creds.apiUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
method: 'PATCH',
headers: {
'Authorization': creds.authHeader,