Skip to content

Commit

Permalink
fix(LoginEvent): prevent duplicate entries (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanaturner authored Oct 10, 2024
1 parent afaecab commit b8277cb
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion server/controllers/LoginEventController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { LoginEvent } from '../models';
export class LoginEventController {
public async log(user_id: string, timestamp?: Date) {
const finalTimestamp = timestamp ?? new Date();
await LoginEvent.create({ timestamp: finalTimestamp, user_id });
await LoginEvent.create({ timestamp: finalTimestamp, user_id }, { ignoreDuplicates: true });
}
}
5 changes: 5 additions & 0 deletions server/models/LoginEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import {
import { User } from './User';

@Table({
indexes: [{
fields: ['user_id', 'timestamp'],
name: 'login_events_user_id_timestamp_unique',
unique: true,
}],
timestamps: true,
tableName: 'login_events',
})
Expand Down
49 changes: 49 additions & 0 deletions server/tests/loginevents.unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { after, afterEach, describe } from 'mocha';
import { expect } from 'chai';
import { LoginEvent } from '../models';
import { LoginEventController } from '@server/controllers/LoginEventController';
import { server } from '@server/index';
import { User } from '@server/models';
import { v4 as uuidv4 } from 'uuid';

describe('LoginEventController', () => {
const controller = new LoginEventController();
let user1: User;

before(async () => {
user1 = await User.create({
uuid: uuidv4(),
email: '[email protected]',
});
});
after(async () => {
await User.destroy({ where: {} });
if (server?.listening) {
server.close();
}
});
afterEach(async () => {
await LoginEvent.destroy({ where: {} });
});

describe('log', () => {
it('should log event', async () => {
await controller.log(user1.uuid);
const foundLog = await LoginEvent.findOne({ where: { user_id: user1.uuid } });
expect(foundLog).to.not.be.null;
});
it('should log event with timestamp specified', async () => {
await controller.log(user1.uuid, new Date(1000));
const foundLog = await LoginEvent.findOne({ where: { user_id: user1.uuid } });
expect(foundLog).to.not.be.null;
expect(foundLog?.get('timestamp')?.getTime()).to.deep.equal(1000);
});
it('should not error on duplicate entry', async () => {
const timestamp = new Date();
await controller.log(user1.uuid, timestamp);
await controller.log(user1.uuid, timestamp);
const foundLogs = await LoginEvent.findAll({ where: { user_id: user1.uuid } });
expect(foundLogs?.length).to.deep.equal(1);
});
});
});

0 comments on commit b8277cb

Please sign in to comment.