Skip to content

Commit 87e7ae0

Browse files
committed
fix(auth): update authentication middleware to use async database queries
- Changed `authenticateAdminDashboard` and `authenticateAdminAPI` to async functions for improved database interaction. - Replaced `getDb` with `getRow` for fetching user roles and details. - Updated routes to handle async middleware with `asyncHandler` for better error management. - Enhanced `listClients` to utilize `getAllRows` for fetching client data.
1 parent 3291873 commit 87e7ae0

File tree

6 files changed

+16
-18
lines changed

6 files changed

+16
-18
lines changed

src/auth/adminApi.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import jwt from 'jsonwebtoken';
88
import { isTokenRevoked } from './jwt.js';
9-
import { getDb } from '../db/authDb.js';
9+
import { getRow } from '../db/authDb.js';
1010
import { isAdmin } from './permissions.js';
1111
import { throwUnauthorized, throwForbidden } from '../middleware/responseHelpers.js';
1212
import logger from '../logging/logger.js';
@@ -16,7 +16,7 @@ import logger from '../logging/logger.js';
1616
* Verifies the user has admin role or admin scope.
1717
* Returns 401/403 for API calls, redirects for browser requests.
1818
*/
19-
export const authenticateAdminAPI = (req, res, next) => {
19+
export const authenticateAdminAPI = async (req, res, next) => {
2020
let user = null;
2121

2222
// First try JWT authentication
@@ -36,8 +36,7 @@ export const authenticateAdminAPI = (req, res, next) => {
3636

3737
// Fallback to session authentication
3838
if (!user && req.session && req.session.user) {
39-
const db = getDb();
40-
const dbUser = db.prepare('SELECT id, username, role, scopes FROM users WHERE id = ? AND is_active = TRUE').get(req.session.user.id);
39+
const dbUser = await getRow('SELECT id, username, role, scopes FROM users WHERE id = ? AND is_active = TRUE', [req.session.user.id]);
4140

4241
if (dbUser) {
4342
// Parse scopes

src/auth/adminDashboard.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,22 @@
44
* Requires the user to be logged in via session and have admin role.
55
*/
66

7-
import { getDb } from '../db/authDb.js';
7+
import { getRow } from '../db/authDb.js';
88

99
/**
1010
* Middleware to protect admin dashboard page.
1111
* Checks for session authentication and admin role.
1212
* Redirects to login if not authenticated or not admin.
1313
*/
14-
export const authenticateAdminDashboard = (req, res, next) => {
14+
export const authenticateAdminDashboard = async (req, res, next) => {
1515
// Check if user has a session
1616
if (!req.session || !req.session.user) {
1717
// Redirect to login with return_to parameter
1818
return res.redirect(`/login?return_to=${encodeURIComponent(req.originalUrl)}`);
1919
}
2020

2121
// Get user's role from database
22-
const db = getDb();
23-
const user = db.prepare('SELECT role FROM users WHERE id = ? AND is_active = TRUE').get(req.session.user.id);
22+
const user = await getRow('SELECT role FROM users WHERE id = ? AND is_active = TRUE', [req.session.user.id]);
2423

2524
if (!user || user.role !== 'admin') {
2625
// Non-admin user - redirect to login with error

src/auth/oauth2/client.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import bcrypt from 'bcrypt';
99
import crypto from 'crypto';
10-
import { executeQuery, getRow, pruneExpiredCodes } from '../../db/authDb.js';
10+
import { executeQuery, getRow, getAllRows, pruneExpiredCodes } from '../../db/authDb.js';
1111
import logger from '../../logging/logger.js';
1212
import { AuthenticationError } from '../../errors/index.js';
1313

@@ -163,7 +163,7 @@ export const generateClientSecret = () => {
163163
* Returns safe client information for listing.
164164
*/
165165
export const listClients = async () => {
166-
const clients = await executeQuery(`
166+
const clients = await getAllRows(`
167167
SELECT
168168
client_id,
169169
allowed_scopes,
@@ -173,7 +173,7 @@ export const listClients = async () => {
173173
ORDER BY created_at DESC
174174
`);
175175

176-
return clients.rows || [];
176+
return clients || [];
177177
};
178178

179179
/**

src/routes/admin.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { adminLimiter, standardWriteLimiter, deleteLimiter } from '../middleware
1515
const router = express.Router();
1616

1717
// All admin routes require authentication (JWT or session) and rate limiting
18-
router.use(authenticateAdminAPI);
18+
router.use(asyncHandler(authenticateAdminAPI));
1919
router.use(adminLimiter);
2020

2121
/**
@@ -24,7 +24,7 @@ router.use(adminLimiter);
2424
* List all OAuth clients (without secrets).
2525
*/
2626
router.get('/oauth-clients', asyncHandler(async (req, res) => {
27-
const clients = listClients();
27+
const clients = await listClients();
2828
sendSuccess(res, { clients });
2929
}));
3030

@@ -35,7 +35,7 @@ router.get('/oauth-clients', asyncHandler(async (req, res) => {
3535
*/
3636
router.get('/oauth-clients/:clientId', validateParams(ClientIdParamsSchema), asyncHandler(async (req, res) => {
3737
const { clientId } = req.validatedParams;
38-
const client = getClient(clientId);
38+
const client = await getClient(clientId);
3939

4040
if (!client) {
4141
throwNotFound(`OAuth client '${clientId}' not found`);
@@ -110,7 +110,7 @@ router.put('/oauth-clients/:clientId',
110110
*/
111111
router.delete('/oauth-clients/:clientId', deleteLimiter, validateParams(ClientIdParamsSchema), asyncHandler(async (req, res) => {
112112
const { clientId } = req.validatedParams;
113-
const deleted = deleteClient(clientId);
113+
const deleted = await deleteClient(clientId);
114114

115115
if (!deleted) {
116116
throwNotFound(`OAuth client '${clientId}' not found`);

src/routes/auth.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import jwt from 'jsonwebtoken';
1111
import crypto from 'crypto';
1212
import { authenticateUser } from '../auth/user.js';
1313
import { issueTokens, revokeToken, isTokenRevoked, authenticateJWT } from '../auth/jwt.js';
14-
import { insertToken } from '../db/authDb.js';
14+
import { insertToken, getRow } from '../db/authDb.js';
1515
import { ACCESS_TTL_SECONDS } from '../config/index.js';
1616
import { validateBody } from '../middleware/validation-schemas.js';
1717
import { LoginSchema, LogoutSchema } from '../middleware/validation-schemas.js';
@@ -43,7 +43,6 @@ router.post('/login', loginLimiterWithLogging, validateBody(LoginSchema), async
4343
}
4444

4545
// Get user's current role and scopes from database
46-
const { getRow } = await import('../db/authDb.js');
4746
const user = await getRow('SELECT role, scopes FROM users WHERE id = ?', [decoded.user_id]);
4847
const role = user?.role || decoded.role || 'user';
4948
const scopes = user?.scopes || decoded.scope || 'api';

src/routes/login.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import express from 'express';
88
import rateLimit from 'express-rate-limit';
99
import { authenticateUser } from '../auth/user.js';
1010
import { authenticateAdminDashboard } from '../auth/adminDashboard.js';
11+
import { asyncHandler } from '../middleware/asyncHandler.js';
1112

1213
const router = express.Router();
1314

@@ -21,7 +22,7 @@ router.get('/login', (req, res) => {
2122
res.sendFile('./src/public/static/api-login.html', { root: process.cwd() });
2223
});
2324

24-
router.get('/admin', authenticateAdminDashboard, (req, res) => {
25+
router.get('/admin', asyncHandler(authenticateAdminDashboard), (req, res) => {
2526
res.sendFile('./src/public/static/admin.html', { root: process.cwd() });
2627
});
2728

0 commit comments

Comments
 (0)