Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Journaliser le changement d'adresse email (PIX-14360) #10137

Merged
merged 3 commits into from
Sep 24, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { auditLoggerRepository } from '../../../../lib/infrastructure/repositories/audit-logger-repository.js';
import { JobController } from '../../../shared/application/jobs/job-controller.js';
import { EventLoggingJob } from '../../domain/models/jobs/EventLoggingJob.js';

export class EventLoggingJobController extends JobController {
constructor() {
super(EventLoggingJob.name);
}

async handle({ data: jobData, dependencies = { auditLoggerRepository } }) {
const { client, action, role, userId, targetUserId, data, occurredAt } = jobData;

bpetetot marked this conversation as resolved.
Show resolved Hide resolved
return dependencies.auditLoggerRepository.logEvent({
client,
action,
role,
userId: userId.toString(),
targetUserId: targetUserId.toString(),
data,
occurredAt,
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Joi from 'joi';

import { EntityValidationError } from '../../../../shared/domain/errors.js';

const CLIENTS = ['PIX_ADMIN', 'PIX_APP'];
const ACTIONS = ['ANONYMIZATION', 'ANONYMIZATION_GAR', 'EMAIL_CHANGED'];
const ROLES = ['SUPER_ADMIN', 'SUPPORT', 'USER'];

const EventLogSchema = Joi.object({
client: Joi.string()
.valid(...CLIENTS)
.required(),
action: Joi.string()
.valid(...ACTIONS)
.required(),
role: Joi.string()
.valid(...ROLES)
.required(),
userId: Joi.number().required(),
targetUserId: Joi.number().required(),
data: Joi.object().optional(),
occurredAt: Joi.date().optional(),
});

export class EventLoggingJob {
constructor({ client, action, role, userId, targetUserId, data, occurredAt }) {
this.client = client;
this.action = action;
this.role = role;
this.userId = userId;
this.targetUserId = targetUserId;
this.data = data;
this.occurredAt = occurredAt || new Date();

this.#validate();
}

#validate() {
const { error } = EventLogSchema.validate(this, { abortEarly: false });
if (error) throw EntityValidationError.fromJoiErrors(error.details);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { importNamedExportsFromDirectory } from '../../../shared/infrastructure/
import { accountRecoveryDemandRepository } from '../../infrastructure/repositories/account-recovery-demand.repository.js';
import * as authenticationMethodRepository from '../../infrastructure/repositories/authentication-method.repository.js';
import { emailValidationDemandRepository } from '../../infrastructure/repositories/email-validation-demand.repository.js';
import { eventLoggingJobRepository } from '../../infrastructure/repositories/jobs/event-logging-job.repository.js';
import { garAnonymizedBatchEventsLoggingJobRepository } from '../../infrastructure/repositories/jobs/gar-anonymized-batch-events-logging-job-repository.js';
import { oidcProviderRepository } from '../../infrastructure/repositories/oidc-provider-repository.js';
import { refreshTokenRepository } from '../../infrastructure/repositories/refresh-token.repository.js';
Expand All @@ -45,8 +46,9 @@ const repositories = {
authenticationMethodRepository,
campaignParticipationRepository,
campaignRepository,
emailValidationDemandRepository,
campaignToJoinRepository: campaignRepositories.campaignToJoinRepository,
emailValidationDemandRepository,
eventLoggingJobRepository,
oidcProviderRepository,
organizationLearnerRepository,
refreshTokenRepository,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@ import {
InvalidVerificationCodeError,
UserNotAuthorizedToUpdateEmailError,
} from '../../../shared/domain/errors.js';
import { EventLoggingJob } from '../models/jobs/EventLoggingJob.js';

const updateUserEmailWithValidation = async function ({ code, userId, userEmailRepository, userRepository }) {
const updateUserEmailWithValidation = async function ({
code,
userId,
userEmailRepository,
userRepository,
eventLoggingJobRepository,
}) {
const user = await userRepository.get(userId);
if (!user.email) {
throw new UserNotAuthorizedToUpdateEmailError();
Expand All @@ -29,6 +36,18 @@ const updateUserEmailWithValidation = async function ({ code, userId, userEmailR
},
});

// Currently only used in Pix App, which is why app name is hard-coded for the audit log.
await eventLoggingJobRepository.performAsync(
new EventLoggingJob({
client: 'PIX_APP',
bpetetot marked this conversation as resolved.
Show resolved Hide resolved
action: 'EMAIL_CHANGED',
role: 'USER',
userId: user.id,
targetUserId: user.id,
data: { oldEmail: user.email, newEmail: emailModificationDemand.newEmail },
}),
);

return { email: emailModificationDemand.newEmail };
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { JobRepository, JobRetry } from '../../../../shared/infrastructure/repositories/jobs/job-repository.js';
import { EventLoggingJob } from '../../../domain/models/jobs/EventLoggingJob.js';

class EventLoggingJobRepository extends JobRepository {
bpetetot marked this conversation as resolved.
Show resolved Hide resolved
constructor() {
super({
name: EventLoggingJob.name,
retry: JobRetry.STANDARD_RETRY,
});
}
}

export const eventLoggingJobRepository = new EventLoggingJobRepository();
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ export class JobRepository {

/**
* @param {Object} config
* @param {valueOf<JobPriority>} config.priority
* @param {valueOf<JobRetry>} config.retry
* @param {valueOf<JobExpireIn>} config.expireIn
* @param {string} config.name Job name
* @param {valueOf<JobPriority>} config.priority Job prority
* @param {valueOf<JobRetry>} config.retry Job retry strategy
* @param {valueOf<JobExpireIn>} config.expireIn Job retention duration
*/
constructor(config) {
this.name = config.name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { expect } from 'chai';

import { EventLoggingJob } from '../../../../../src/identity-access-management/domain/models/jobs/EventLoggingJob.js';
import { usecases } from '../../../../../src/identity-access-management/domain/usecases/index.js';
import { userEmailRepository } from '../../../../../src/identity-access-management/infrastructure/repositories/user-email.repository.js';
import {
AlreadyRegisteredEmailError,
EmailModificationDemandNotFoundOrExpiredError,
InvalidVerificationCodeError,
UserNotAuthorizedToUpdateEmailError,
} from '../../../../../src/shared/domain/errors.js';
import { temporaryStorage } from '../../../../../src/shared/infrastructure/temporary-storage/index.js';
import { catchErr, databaseBuilder, knex, sinon } from '../../../../test-helper.js';

const verifyEmailTemporaryStorage = temporaryStorage.withPrefix('verify-email:');

describe('Integration | Identity Access Management | Domain | UseCase | updateUserEmailWithValidation', function () {
let clock;
const now = new Date('2024-12-25');

beforeEach(function () {
verifyEmailTemporaryStorage.flushAll();
clock = sinon.useFakeTimers({ now, toFake: ['Date'] });
});

afterEach(async function () {
clock.restore();
});

it('updates the user email checking the verification code', async function () {
// given
const code = 123;
const newEmail = '[email protected]';
const user = databaseBuilder.factory.buildUser({ email: '[email protected]' });
await databaseBuilder.commit();
await userEmailRepository.saveEmailModificationDemand({ userId: user.id, code, newEmail });

// when
const result = await usecases.updateUserEmailWithValidation({ userId: user.id, code, newEmail });

// then
expect(result.email).to.equal(newEmail);

const updatedUser = await knex('users').where({ id: user.id }).first();
expect(updatedUser.email).to.equal(newEmail);
expect(updatedUser.emailConfirmedAt).to.not.be.null;

await expect(EventLoggingJob.name).to.have.been.performed.withJobPayload({
client: 'PIX_APP',
action: 'EMAIL_CHANGED',
role: 'USER',
userId: user.id,
targetUserId: user.id,
data: { oldEmail: '[email protected]', newEmail: '[email protected]' },
occurredAt: '2024-12-25T00:00:00.000Z',
});
});

context('when the verification code is invalid', function () {
it('throws an error', async function () {
// given
const code = 123;
const invalidCode = 456;
const newEmail = '[email protected]';
const user = databaseBuilder.factory.buildUser({ email: '[email protected]' });
await databaseBuilder.commit();
await userEmailRepository.saveEmailModificationDemand({ userId: user.id, code, newEmail });

// when
const error = await catchErr(usecases.updateUserEmailWithValidation)({
userId: user.id,
code: invalidCode,
newEmail,
});

// then
expect(error).to.be.instanceOf(InvalidVerificationCodeError);
});
});

context('when the email modification demand is not found or expired', function () {
it('throws an error', async function () {
// given
const code = 123;
const newEmail = '[email protected]';
const user = databaseBuilder.factory.buildUser({ email: '[email protected]' });
await databaseBuilder.commit();

// when
const error = await catchErr(usecases.updateUserEmailWithValidation)({
userId: user.id,
code,
newEmail,
});

// then
expect(error).to.be.instanceOf(EmailModificationDemandNotFoundOrExpiredError);
});
});

context('when the user has no email', function () {
it('throws an error', async function () {
// given
const code = 123;
const newEmail = '[email protected]';
const user = databaseBuilder.factory.buildUser({ email: null });
await databaseBuilder.commit();
await userEmailRepository.saveEmailModificationDemand({ userId: user.id, code, newEmail });

// when
const error = await catchErr(usecases.updateUserEmailWithValidation)({
userId: user.id,
code,
newEmail,
});

// then
expect(error).to.be.instanceOf(UserNotAuthorizedToUpdateEmailError);
});
});

context('when the new email is already registered for an other user', function () {
it('throws an error', async function () {
// given
const code = 123;
const alreadyExistEmail = '[email protected]';
const user = databaseBuilder.factory.buildUser({ email: '[email protected]' });
databaseBuilder.factory.buildUser({ email: alreadyExistEmail });
await databaseBuilder.commit();
await userEmailRepository.saveEmailModificationDemand({ userId: user.id, code, newEmail: alreadyExistEmail });

// when
const error = await catchErr(usecases.updateUserEmailWithValidation)({
userId: user.id,
code,
newEmail: alreadyExistEmail,
});

// then
expect(error).to.be.instanceOf(AlreadyRegisteredEmailError);
});
});
});
bpetetot marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { EventLoggingJobController } from '../../../../../src/identity-access-management/application/jobs/event-logging.job-controller.js';
import { EventLoggingJob } from '../../../../../src/identity-access-management/domain/models/jobs/EventLoggingJob.js';
import { expect, sinon } from '../../../../test-helper.js';

describe('Unit | Identity Access Management | Application | Jobs | EventLoggingJobController', function () {
it('sets up the job controller configuration', async function () {
const jobController = new EventLoggingJobController();
expect(jobController.jobName).to.equal(EventLoggingJob.name);
});

it('logs the event', async function () {
// given
const auditLoggerRepository = { logEvent: sinon.stub() };
const options = { dependencies: { auditLoggerRepository } };
const data = {
client: 'PIX_APP',
action: 'EMAIL_CHANGED',
role: 'USER',
userId: 123,
targetUserId: 456,
EmmanuelleBonnemay marked this conversation as resolved.
Show resolved Hide resolved
data: { foo: 'bar' },
occurredAt: new Date(),
};

// when
const jobController = new EventLoggingJobController();
await jobController.handle({ data, ...options });

// then
expect(auditLoggerRepository.logEvent).to.have.been.calledWith({
client: data.client,
action: data.action,
role: data.role,
userId: data.userId.toString(),
targetUserId: data.targetUserId.toString(),
data: data.data,
occurredAt: data.occurredAt,
});
});
});
Loading
Loading