Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions documentation/backend/services/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ Handles authentication and authorization: Multiple auth providers (Plex OAuth, O
- Password hashed with bcrypt (10 rounds) and stored in `authToken` field
- `bcrypt` 6.x: prebuilt native binaries ship in the package (linux x64/arm64, glibc + musl), no install-time download or compile. `$2a$`/`$2b$` hashes made by bcrypt 5 verify unchanged (`tests/services/auth/bcrypt-compat.test.ts`)
- Login: POST `/api/auth/admin/login` with username/password
- Account checks: same as the regular local login (`src/lib/services/auth/local-account-status.ts`). Pending approval: 200 `{success:false, pendingApproval:true}`; rejected: 401 `Account has been rejected`; deleted (`deletedAt` set): 401 `Invalid username or password`. Approved or null `registrationStatus` signs in. Checked after the password, before `lastLoginAt` and tokens
- Identified by: `isSetupAdmin=true` AND `plexId` starts with `local-`

**Password Management:**
Expand Down Expand Up @@ -307,6 +308,7 @@ oidc.admin_claim_value = 'readmeabook-admin'

- **OIDC accounts:** OIDC sign-in is kept to OIDC accounts.
- **Plex profile identity:** profile sign-in takes the profile's identity from Plex and requires a profile from the account's Home list.
- **Admin sign-in account checks:** `/api/auth/admin/login` now applies the same account checks as the regular local sign-in (pending approval, rejected) and also refuses deleted accounts.
- **#297 Hardcoded JWT fallback secrets:** `jwt.ts` fell back to built-in default strings when `JWT_SECRET`/`JWT_REFRESH_SECRET` were unset (installs that bypass the unified entrypoint). Fix: fallbacks removed; secrets derived from `CONFIG_ENCRYPTION_KEY` via HKDF. Affected installs: all sessions + download links invalidated on upgrade (re-login required).
- **#215 Soft-deleted users counted as local users/admins:** `hasLocalUsers`/`hasLocalAdmins` (providers + admin settings) had no `deletedAt: null`, so a deleted local admin kept the login form shown and the Auth tab lockout warnings quiet. Fix: count non-deleted users only. First-user checks unchanged (deleted users still count).

Expand Down
21 changes: 20 additions & 1 deletion src/app/api/auth/admin/login/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import { generateAccessToken, generateRefreshToken } from '@/lib/utils/jwt';
import { getEncryptionService } from '@/lib/services/encryption.service';
import { RMABLogger } from '@/lib/utils/logger';
import { readJsonBody, AUTH_JSON_BODY_LIMIT_BYTES } from '@/lib/utils/request-body';
import {
getRegistrationRefusal,
PENDING_APPROVAL_MESSAGE,
REJECTED_ACCOUNT_ERROR,
} from '@/lib/services/auth/local-account-status';

const logger = RMABLogger.create('API.Auth.AdminLogin');

Expand Down Expand Up @@ -48,7 +53,8 @@ export async function POST(request: NextRequest) {
where: { plexId: `local-${normalizedUsername}` },
});

if (!user) {
// A deleted account answers exactly like an unknown one
if (!user || user.deletedAt) {
return NextResponse.json(
{
error: 'AuthenticationError',
Expand Down Expand Up @@ -86,6 +92,19 @@ export async function POST(request: NextRequest) {
);
}

// Same registration checks as the regular local login, same responses
const refusal = getRegistrationRefusal(user.registrationStatus);
if (refusal === 'pending_approval') {
return NextResponse.json({
success: false,
pendingApproval: true,
message: PENDING_APPROVAL_MESSAGE,
});
}
if (refusal === 'rejected') {
return NextResponse.json({ error: REJECTED_ACCOUNT_ERROR }, { status: 401 });
}

// Update last login time
await prisma.user.update({
where: { id: user.id },
Expand Down
3 changes: 2 additions & 1 deletion src/app/api/auth/local/login/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { LocalAuthProvider } from '@/lib/services/auth/LocalAuthProvider';
import { RMABLogger } from '@/lib/utils/logger';
import { readJsonBody, AUTH_JSON_BODY_LIMIT_BYTES } from '@/lib/utils/request-body';
import { PENDING_APPROVAL_MESSAGE } from '@/lib/services/auth/local-account-status';

const logger = RMABLogger.create('API.Auth.LocalLogin');

Expand Down Expand Up @@ -42,7 +43,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json({
success: false,
pendingApproval: true,
message: 'Account pending admin approval.',
message: PENDING_APPROVAL_MESSAGE,
});
}
logger.error('Login failed', { error: result.error });
Expand Down
10 changes: 6 additions & 4 deletions src/lib/services/auth/LocalAuthProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { getConfigService } from '@/lib/services/config.service';
import { getEncryptionService } from '@/lib/services/encryption.service';
import { prisma } from '@/lib/db';
import { RMABLogger } from '@/lib/utils/logger';
import { getRegistrationRefusal, REJECTED_ACCOUNT_ERROR } from './local-account-status';

const logger = RMABLogger.create('LocalAuth');

Expand Down Expand Up @@ -70,15 +71,16 @@ export class LocalAuthProvider implements IAuthProvider {
}

// Check registration status
if (user.registrationStatus === 'pending_approval') {
const refusal = getRegistrationRefusal(user.registrationStatus);
if (refusal === 'pending_approval') {
return {
success: false,
requiresApproval: true,
};
}

if (user.registrationStatus === 'rejected') {
return { success: false, error: 'Account has been rejected' };
if (refusal === 'rejected') {
return { success: false, error: REJECTED_ACCOUNT_ERROR };
}

// Verify password
Expand Down Expand Up @@ -295,7 +297,7 @@ export class LocalAuthProvider implements IAuthProvider {
return false;
}

if (user.registrationStatus === 'pending_approval' || user.registrationStatus === 'rejected') {
if (getRegistrationRefusal(user.registrationStatus)) {
return false;
}

Expand Down
22 changes: 22 additions & 0 deletions src/lib/services/auth/local-account-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Component: Local Account Sign-in Checks
* Documentation: documentation/backend/services/auth.md
*/

/** Messages both local sign-in routes return for a refused account. */
export const PENDING_APPROVAL_MESSAGE = 'Account pending admin approval.';
export const REJECTED_ACCOUNT_ERROR = 'Account has been rejected';

export type RegistrationRefusal = 'pending_approval' | 'rejected';

/**
* Registration states a local sign-in refuses. Anything else (approved, or null on
* older rows) is allowed to sign in, matching the regular local login.
*/
export function getRegistrationRefusal(
registrationStatus: string | null | undefined
): RegistrationRefusal | null {
if (registrationStatus === 'pending_approval') return 'pending_approval';
if (registrationStatus === 'rejected') return 'rejected';
return null;
}
108 changes: 108 additions & 0 deletions tests/api/auth-admin-login.routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,112 @@ describe('Admin login route', () => {
expect(payload.refreshToken).toBe('refresh-token');
expect(prismaMock.user.update).toHaveBeenCalled();
});

describe('account checks', () => {
const baseUser = {
id: 'user-10',
plexId: 'local-reader',
plexUsername: 'reader',
plexEmail: null,
role: 'user',
avatarUrl: null,
authToken: 'enc-hash',
authProvider: 'local',
isSetupAdmin: false,
registrationStatus: 'approved' as string | null,
deletedAt: null as Date | null,
};

const signIn = async (row: Record<string, unknown>) => {
prismaMock.user.findUnique.mockResolvedValue(row);
prismaMock.user.update.mockResolvedValue({});
encryptionMock.decrypt.mockReturnValue('hash');
bcryptMock.compare.mockResolvedValue(true);
const { POST } = await import('@/app/api/auth/admin/login/route');
const request = makeRequest({ username: 'reader', password: 'pass' }) as unknown as Parameters<typeof POST>[0];
const response = await POST(request);
return { response, payload: await response.json() };
};

const expectNoSession = (payload: Record<string, unknown>) => {
expect(payload.accessToken).toBeUndefined();
expect(payload.refreshToken).toBeUndefined();
expect(tokenMock.generateAccessToken).not.toHaveBeenCalled();
expect(tokenMock.generateRefreshToken).not.toHaveBeenCalled();
expect(prismaMock.user.update).not.toHaveBeenCalled();
};

it('gives an account pending approval the regular pending response and no session', async () => {
const { response, payload } = await signIn({ ...baseUser, registrationStatus: 'pending_approval' });

expect(response.status).toBe(200);
expect(payload).toEqual({
success: false,
pendingApproval: true,
message: 'Account pending admin approval.',
});
expectNoSession(payload);
});

it('refuses a rejected account with the regular rejected response and no session', async () => {
const { response, payload } = await signIn({ ...baseUser, registrationStatus: 'rejected' });

expect(response.status).toBe(401);
expect(payload).toEqual({ error: 'Account has been rejected' });
expectNoSession(payload);
});

it('answers a deleted account exactly like a wrong password and gives no session', async () => {
const { response, payload } = await signIn({ ...baseUser, deletedAt: new Date('2026-01-01T00:00:00Z') });

expect(response.status).toBe(401);
expect(payload).toEqual({
error: 'AuthenticationError',
message: 'Invalid username or password',
});
expectNoSession(payload);
});

it('still signs in the setup admin', async () => {
const { response, payload } = await signIn({
...baseUser,
id: 'setup-admin',
plexId: 'local-admin',
plexUsername: 'admin',
role: 'admin',
authProvider: 'plex',
isSetupAdmin: true,
});

expect(response.status).toBe(200);
expect(payload.success).toBe(true);
expect(payload.accessToken).toBe('access-token');
expect(payload.refreshToken).toBe('refresh-token');
expect(payload.user).toMatchObject({ id: 'setup-admin', role: 'admin' });
expect(prismaMock.user.update).toHaveBeenCalledWith({
where: { id: 'setup-admin' },
data: { lastLoginAt: expect.any(Date) },
});
});

it('still signs in an approved local user', async () => {
const { response, payload } = await signIn({ ...baseUser });

expect(response.status).toBe(200);
expect(payload.success).toBe(true);
expect(payload.accessToken).toBe('access-token');
expect(payload.user).toMatchObject({ id: 'user-10', role: 'user' });
expect(prismaMock.user.update).toHaveBeenCalledTimes(1);
});

it('still signs in an older row with no registration status', async () => {
const { response, payload } = await signIn({ ...baseUser, id: 'legacy-1', registrationStatus: null });

expect(response.status).toBe(200);
expect(payload.success).toBe(true);
expect(payload.accessToken).toBe('access-token');
expect(payload.user).toMatchObject({ id: 'legacy-1' });
expect(prismaMock.user.update).toHaveBeenCalledTimes(1);
});
});
});
Loading