1
0
mirror of https://github.com/immich-app/immich.git synced 2024-11-24 08:52:28 +02:00

fix(server, web): Prevent the user from setting a future date of birth (#5803)

* Hide the person age if it is negative

* Add validation to prevent future birth dates

* Add comment

* Add test, Add birth date validation and update birth date modal

* Add birthDate validation in PersonService and SetBirthDateModal

* Running npm run format:fix

* Generating the migration file propoerly, and Make the birthdate form logic simpler

* Make birthDate type only string

* Adding useLocationPin back
This commit is contained in:
Mohamed BOUSSAID 2023-12-19 17:07:38 +01:00 committed by GitHub
parent 95a7bf7fac
commit 234449f3c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 95 additions and 16 deletions

View File

@ -278,13 +278,55 @@ describe(PersonService.name, () => {
thumbnailPath: '/path/to/thumbnail.jpg',
isHidden: false,
});
expect(personMock.getById).toHaveBeenCalledWith('person-1');
expect(personMock.update).toHaveBeenCalledWith({ id: 'person-1', birthDate: new Date('1976-06-30') });
expect(jobMock.queue).not.toHaveBeenCalled();
expect(accessMock.person.checkOwnerAccess).toHaveBeenCalledWith(authStub.admin.user.id, new Set(['person-1']));
});
it('should throw BadRequestException if birthDate is in the future', async () => {
personMock.getById.mockResolvedValue(personStub.noBirthDate);
personMock.update.mockResolvedValue(personStub.withBirthDate);
personMock.getAssets.mockResolvedValue([assetStub.image]);
accessMock.person.checkOwnerAccess.mockResolvedValue(new Set(['person-1']));
const futureDate = new Date();
futureDate.setMinutes(futureDate.getMinutes() + 1); // Set birthDate to one minute in the future
await expect(sut.update(authStub.admin, 'person-1', { birthDate: futureDate })).rejects.toThrow(
new BadRequestException('Date of birth cannot be in the future'),
);
});
it('should not throw an error if birthdate is in the past', async () => {
const pastDate = new Date();
pastDate.setMinutes(pastDate.getMinutes() - 1); // Set birthDate to one minute in the past
personMock.getById.mockResolvedValue(personStub.noBirthDate);
personMock.update.mockResolvedValue({ ...personStub.withBirthDate, birthDate: pastDate });
personMock.getAssets.mockResolvedValue([assetStub.image]);
accessMock.person.checkOwnerAccess.mockResolvedValue(new Set(['person-1']));
const result = await sut.update(authStub.admin, 'person-1', { birthDate: pastDate });
expect(result.birthDate).toEqual(pastDate);
expect(personMock.update).toHaveBeenCalledWith({ id: 'person-1', birthDate: pastDate });
});
it('should not throw an error if birthdate is today', async () => {
const today = new Date(); // Set birthDate to now()
personMock.getById.mockResolvedValue(personStub.noBirthDate);
personMock.update.mockResolvedValue({ ...personStub.withBirthDate, birthDate: today });
personMock.getAssets.mockResolvedValue([assetStub.image]);
accessMock.person.checkOwnerAccess.mockResolvedValue(new Set(['person-1']));
const result = await sut.update(authStub.admin, 'person-1', { birthDate: today });
expect(result.birthDate).toEqual(today);
expect(personMock.update).toHaveBeenCalledWith({ id: 'person-1', birthDate: today });
});
it('should update a person visibility', async () => {
personMock.getById.mockResolvedValue(personStub.hidden);
personMock.update.mockResolvedValue(personStub.withName);

View File

@ -199,6 +199,11 @@ export class PersonService {
const { name, birthDate, isHidden, featureFaceAssetId: assetId } = dto;
// Check if the birthDate is in the future
if (birthDate && new Date(birthDate) > new Date()) {
throw new BadRequestException('Date of birth cannot be in the future');
}
if (name !== undefined || birthDate !== undefined || isHidden !== undefined) {
person = await this.repository.update({ id, name, birthDate, isHidden });
}

View File

@ -1,4 +1,5 @@
import {
Check,
Column,
CreateDateColumn,
Entity,
@ -11,6 +12,7 @@ import { AssetFaceEntity } from './asset-face.entity';
import { UserEntity } from './user.entity';
@Entity('person')
@Check(`"birthDate" <= CURRENT_DATE`)
export class PersonEntity {
@PrimaryGeneratedColumn('uuid')
id!: string;

View File

@ -0,0 +1,16 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class NullifyFutureBirthDatesAndAddCheckConstraint1702938928766 implements MigrationInterface {
name = 'NullifyFutureBirthDatesAndAddCheckConstraint1702938928766'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`UPDATE "person" SET "birthDate" = NULL WHERE "birthDate" > CURRENT_DATE;`);
await queryRunner.query(`ALTER TABLE "person" ADD CONSTRAINT "CHK_b0f82b0ed662bfc24fbb58bb45" CHECK ("birthDate" <= CURRENT_DATE)`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
// The down method cannot revert the nullified dates
await queryRunner.query(`ALTER TABLE "person" DROP CONSTRAINT "CHK_b0f82b0ed662bfc24fbb58bb45"`);
}
}

View File

@ -264,19 +264,22 @@
<p class="mt-1 truncate font-medium" title={person.name}>{person.name}</p>
{#if person.birthDate}
{@const personBirthDate = DateTime.fromISO(person.birthDate)}
<p
class="font-light"
title={personBirthDate.toLocaleString(
{
month: 'long',
day: 'numeric',
year: 'numeric',
},
{ locale: $locale },
)}
>
Age {Math.floor(DateTime.fromISO(asset.fileCreatedAt).diff(personBirthDate, 'years').years)}
</p>
{@const age = Math.floor(DateTime.fromISO(asset.fileCreatedAt).diff(personBirthDate, 'years').years)}
{#if age >= 0}
<p
class="font-light"
title={personBirthDate.toLocaleString(
{
month: 'long',
day: 'numeric',
year: 'numeric',
},
{ locale: $locale },
)}
>
Age {age}
</p>
{/if}
{/if}
</a>
</div>

View File

@ -12,8 +12,12 @@
updated: string;
}>();
const todayFormatted = new Date().toISOString().split('T')[0];
const handleCancel = () => dispatch('close');
const handleSubmit = () => dispatch('updated', birthDate);
const handleSubmit = () => {
dispatch('updated', birthDate);
};
</script>
<FullScreenModal on:clickOutside={() => handleCancel()}>
@ -33,7 +37,14 @@
<form on:submit|preventDefault={() => handleSubmit()} autocomplete="off">
<div class="m-4 flex flex-col gap-2">
<input class="immich-form-input" id="birthDate" name="birthDate" type="date" bind:value={birthDate} />
<input
class="immich-form-input"
id="birthDate"
name="birthDate"
type="date"
bind:value={birthDate}
max={todayFormatted}
/>
</div>
<div class="mt-8 flex w-full gap-4 px-4">
<Button color="gray" fullwidth on:click={() => handleCancel()}>Cancel</Button>