feat: Implement authentication for API tokens

This commit is contained in:
Faruk AYDIN
2025-04-16 11:09:39 +02:00
parent 2c1888e1b3
commit 883736636b
2 changed files with 48 additions and 1 deletions

View File

@@ -1,5 +1,6 @@
import User from '../models/user.js';
import AccessToken from '../models/access-token.js';
import ApiToken from '../models/api-token.ee.js';
export const isAuthenticated = async (req) => {
const token = req.headers['authorization'];
@@ -46,3 +47,29 @@ export const authenticateUser = async (request, response, next) => {
return response.status(401).end();
}
};
export const isApiTokenAuthenticated = async (request) => {
const token = request.headers['x-api-token'];
if (token == null) return false;
try {
const apiToken = await ApiToken.query().findOne({
token,
});
if (apiToken == null) return false;
return true;
} catch (error) {
return false;
}
};
export const authenticateApiToken = async (request, response, next) => {
if (await isApiTokenAuthenticated(request)) {
next();
} else {
return response.status(401).end();
}
};

View File

@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import { isAuthenticated } from './authentication.js';
import { isAuthenticated, isApiTokenAuthenticated } from './authentication.js';
import { createUser } from '../../test/factories/user.js';
import { createApiToken } from '../../test/factories/api-token.js';
import createAuthTokenByUserId from '../helpers/create-auth-token-by-user-id.js';
describe('isAuthenticated', () => {
@@ -31,3 +32,22 @@ describe('isAuthenticated', () => {
expect(await isAuthenticated(req)).toBe(false);
});
});
describe('isApiTokenAuthenticated', () => {
it('should return false if no token is provided', async () => {
const req = { headers: {} };
expect(await isApiTokenAuthenticated(req)).toBe(false);
});
it('should return false if token is invalid', async () => {
const req = { headers: { 'x-api-token': 'invalidToken' } };
expect(await isApiTokenAuthenticated(req)).toBe(false);
});
it('should return true if token is valid', async () => {
const apiToken = await createApiToken();
const req = { headers: { 'x-api-token': apiToken.token } };
expect(await isApiTokenAuthenticated(req)).toBe(true);
});
});