feat: Implement token generation logic on api tokens

This commit is contained in:
Faruk AYDIN
2025-04-08 11:22:07 +02:00
parent add8a44f40
commit 59510dcb0a
5 changed files with 42 additions and 18 deletions

View File

@@ -12,9 +12,6 @@ exports[`ApiToken model > jsonSchema should have correct validations 1`] = `
"type": "string",
},
},
"required": [
"token",
],
"type": "object",
}
`;

View File

@@ -1,17 +1,25 @@
import Base from './base.js';
import crypto from 'crypto';
class ApiToken extends Base {
static tableName = 'api_tokens';
static jsonSchema = {
type: 'object',
required: ['token'],
properties: {
id: { type: 'string', format: 'uuid' },
token: { type: 'string', minLength: 32 },
},
};
async assignToken() {
this.token = crypto.randomBytes(48).toString('hex');
}
async $beforeInsert(queryContext) {
await super.$beforeInsert(queryContext);
await this.assignToken();
}
}
export default ApiToken;

View File

@@ -0,0 +1,31 @@
import { describe, it, expect, vi } from 'vitest';
import ApiToken from './api-token.ee.js';
describe('ApiToken model', () => {
it('tableName should return correct name', () => {
expect(ApiToken.tableName).toBe('api_tokens');
});
it('jsonSchema should have correct validations', () => {
expect(ApiToken.jsonSchema).toMatchSnapshot();
});
describe('assignToken', () => {
it('should assign a new token', async () => {
const apiToken = new ApiToken();
await apiToken.assignToken();
expect(apiToken.token).toBeDefined();
});
});
describe('beforeInsert', () => {
it('should call assignToken method', async () => {
const apiToken = new ApiToken();
const assignTokenSpy = vi.spyOn(apiToken, 'assignToken');
await apiToken.$beforeInsert();
expect(assignTokenSpy).toHaveBeenCalled();
});
});
});

View File

@@ -1,12 +0,0 @@
import { describe, it, expect } from 'vitest';
import ApiToken from './api-token.js';
describe('ApiToken model', () => {
it('tableName should return correct name', () => {
expect(ApiToken.tableName).toBe('api_tokens');
});
it('jsonSchema should have correct validations', () => {
expect(ApiToken.jsonSchema).toMatchSnapshot();
});
});

View File

@@ -1,5 +1,5 @@
import crypto from 'crypto';
import ApiToken from '../../src/models/api-token.js';
import ApiToken from '../../src/models/api-token.ee.js';
export const createApiToken = async (params = {}) => {
params.token = params.token || crypto.randomBytes(48).toString('hex');