Skip to content
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
15 changes: 8 additions & 7 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
testPathIgnorePatterns: ["node_modules"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
};
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['node_modules'],
setupFilesAfterEnv: ['jest-extended'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"jest-extended": "^0.11.5",
"module-alias": "^2.2.2",
"prettier": "^2.2.1",
"ts-jest": "^26.5.0",
Expand Down
1 change: 0 additions & 1 deletion src/lib/websocket/events/client/voter/join.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { EligibleVoterService } from '@/services/EligibleVoterService'
import { EncryptionService } from '@/services/EncryptionService'
import { MailService } from '@/services/MailService'
import { VoterVerificationService } from '@/services/VoterVerificationService'
import { eventRegistration } from './eventRegistration'
import { enterElection } from './enterElection'

export const join: EventHandlerAcknowledges<{ email: string; electionCode: string }> = async (event) => {
Expand Down
17 changes: 16 additions & 1 deletion src/models/ElectionOrganizer/ElectionOrganizerEntity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { Election } from '@/models/Election/ElectionEntity'
import { Exclude } from 'class-transformer'
import { IsEmail, IsString, MaxLength, MinLength } from 'class-validator'
import { Column, CreateDateColumn, Entity, OneToMany, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm'
import {
BeforeInsert,
BeforeUpdate,
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn
} from 'typeorm'
import { IsElectionOrganizerUnique } from './constraints/IsElectionOrganizerUniqueConstraint'

/**
Expand All @@ -10,6 +19,12 @@ import { IsElectionOrganizerUnique } from './constraints/IsElectionOrganizerUniq
*/
@Entity()
export class ElectionOrganizer {
@BeforeInsert()
@BeforeUpdate()
emailToLowercase() {
this.email = this.email.toLowerCase()
}

Comment on lines +24 to +27
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldnt this be done by the election organizer service class?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, not really. Either the entity itself should make sure the values are saved correctly, or if we have a persistence layer/repository, that's more appropriate than the service layer. At least, that's what I think. Otherwise, the service layer does a lot of very specific things.

@PrimaryGeneratedColumn()
id!: number

Expand Down
8 changes: 7 additions & 1 deletion src/models/EligibleVoter/EligibleVoterEntity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Exclude } from 'class-transformer'
import { IsEmail } from 'class-validator'
import { Column, Entity, ManyToMany, PrimaryGeneratedColumn } from 'typeorm'
import { BeforeInsert, BeforeUpdate, Column, Entity, ManyToMany, PrimaryGeneratedColumn } from 'typeorm'
import { Election } from '../Election/ElectionEntity'

/**
Expand All @@ -11,6 +11,12 @@ import { Election } from '../Election/ElectionEntity'

@Entity()
export class EligibleVoter implements IEligibleVoter {
@BeforeInsert()
@BeforeUpdate()
emailToLowercase() {
this.identification = this.identification.toLowerCase()
}

Comment thread
sanderhurlen marked this conversation as resolved.
@PrimaryGeneratedColumn()
id!: number

Expand Down
2 changes: 1 addition & 1 deletion src/services/AuthenticationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class AuthenticationService {
*/
async login(payload: LoginPayload): Promise<string | undefined> {
const electionOrg = await getRepository(ElectionOrganizer).findOne({
email: payload.email
email: payload.email.toLowerCase()
})

if (!electionOrg) return
Expand Down
4 changes: 2 additions & 2 deletions src/services/EligibleVoterService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,15 @@ export class EligibleVoterService extends BaseEntityService<EligibleVoter> {

/**
* Creates an array of identifications from a given array
* of eligible voters.
* of eligible voters, the identification is also made to lowercase.
* @param eligibleVoters list of eligible voters
* @returns array of identifications
*/
private createArrayOfIdentifications(eligibleVoters: IEligibleVoter[]): string[] {
const array: string[] = []

for (let i = 0; i < eligibleVoters.length; i++) {
array.push(eligibleVoters[i].identification)
array.push(eligibleVoters[i].identification.toLowerCase())
}

return array
Expand Down
1 change: 1 addition & 0 deletions tests/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'jest-extended'
41 changes: 30 additions & 11 deletions tests/services/ElectionOrganizerService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,11 @@ describe('election organizer service', () => {
const organizers: ElectionOrganizer[] = []

const passwordPassedIn = '@passwordIsSecret1099'
const rand = Math.random() * 10
const rand = () => (Math.random() * 100000).toFixed()
const createEmail = () => rand() + 'VerYniCeEmail@DoMAin.cOm'
beforeAll(async () => {
db = await getTestDatabase()
service = new ElectionOrganizerService(db)
seedOrganizer = await (service.createAndSaveElectionOrganizer({
firstName: 'First organizer',
lastName: 'Last name org',
email: rand + 'testing@gmail.com',
password: passwordPassedIn
}) as Promise<ElectionOrganizer>)

organizers.push(seedOrganizer)
})
Expand All @@ -28,11 +23,35 @@ describe('election organizer service', () => {
await db.close()
})

it('should create a election organizer', () => {
expect(seedOrganizer).toBeInstanceOf(ElectionOrganizer)
it('should create a election organizer', async () => {
const organizer = await service.createAndSaveElectionOrganizer({
firstName: 'first',
lastName: 'last',
email: createEmail(),
password: passwordPassedIn
})
expect(organizer).toBeInstanceOf(ElectionOrganizer)
expect(organizer.firstName).toBe('first')
})

it('should create organizer with lowercase email address', async () => {
const email = createEmail()
const organizer = await service.createAndSaveElectionOrganizer({
firstName: 'first',
lastName: 'last',
email,
password: passwordPassedIn
})
expect(organizer.email).toBe(email.toLowerCase())
})

it('should generate a hash for the password', () => {
expect(seedOrganizer.password).not.toBe(passwordPassedIn)
it('should generate a hash for the password', async () => {
const organizer = await service.createAndSaveElectionOrganizer({
firstName: 'first',
lastName: 'last',
email: createEmail(),
password: passwordPassedIn
})
expect(organizer.password).not.toBe(passwordPassedIn)
})
})
72 changes: 36 additions & 36 deletions tests/services/EligibleVoterService.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { EligibleVoter, IEligibleVoter } from '@/models/EligibleVoter/EligibleVoterEntity'
import { EligibleVoterService } from '@/services/EligibleVoterService'
import { HashService } from '@/services/HashService'
import { Connection } from 'typeorm'
import { getTestDatabase } from '../helpers/database'
import { clearDatabaseEntityTable } from '../Tests.utils'
Expand All @@ -9,38 +8,40 @@ describe('election organizer service', () => {
let eligibleVoters: IEligibleVoter[]
let eligibleVoterService: EligibleVoterService
let db: Connection
let service: EligibleVoterService
let seedEligibleVoter: EligibleVoter
let hashService: HashService

const camelCaseEmail = 'CamelCaseEmail@kamelen.NO'
const cleanCamelCaseEmail = camelCaseEmail.toLowerCase()

const whiteSpaceEmail = ' moffeloff@svg.no '
const cleanWhiteSpaceEmail = whiteSpaceEmail.trim()

const duplicateEmail = 'test@test.com'

const validVoters = [{ identification: 'hallai@nrk.no' }, { identification: 'hissig@sturla.net' }]

const invalidVoters: IEligibleVoter[] = [
{
identification: '123.com'
},
{
identification: 'hello'
}
]
const validMustCleanVoters: IEligibleVoter[] = [
{ identification: camelCaseEmail },
{ identification: whiteSpaceEmail }
]

const duplicateVoters: IEligibleVoter[] = [{ identification: duplicateEmail }, { identification: duplicateEmail }]

beforeAll(async () => {
db = await getTestDatabase()
hashService = new HashService()
service = new EligibleVoterService(db)
seedEligibleVoter = db.getRepository(EligibleVoter).create()
seedEligibleVoter.identification = 'test@gmail.com'
await db.getRepository(EligibleVoter).save(seedEligibleVoter)
const eligibleVoter = db.getRepository(EligibleVoter).create()
eligibleVoter.identification = 'test@gmail.com'
seedEligibleVoter = await db.getRepository(EligibleVoter).save(eligibleVoter)
eligibleVoterService = new EligibleVoterService(db)
eligibleVoters = [
{
identification: 'hallai@nrk.no'
},
{
identification: 'hissig@sturla.net'
},
{
identification: 'hissig@sturla.net'
},
{
identification: 'hissig@sturla.net'
},
{
identification: ' moffeloff@svg.no '
},
{
identification: 'hello'
}
]
eligibleVoters = [...invalidVoters, ...validVoters, ...validMustCleanVoters, ...duplicateVoters]
})

afterAll(async () => {
Expand All @@ -59,14 +60,13 @@ describe('election organizer service', () => {
it('should correct the list of eligible voters', () => {
let copy: IEligibleVoter[] = []
copy = eligibleVoterService.correctListOfEligibleVoters(eligibleVoters)
expect(copy.length).toBe(3)
expect(copy[2].identification).toContain('moffeloff@svg.no')
})

it('should not change already correct identifications', () => {
let copy: IEligibleVoter[] = []
copy = eligibleVoterService.correctListOfEligibleVoters(eligibleVoters)
expect(copy[0].identification).toContain('hallai@nrk.no')
expect(copy[1].identification).toContain('hissig@sturla.net')
// Should contain all valid voters, plus half of duplicates
expect(copy.length).toBe(validVoters.length + validMustCleanVoters.length + duplicateVoters.length / 2)
expect(copy).not.toIncludeAnyMembers([{ identification: camelCaseEmail }])
expect(copy).toIncludeAnyMembers([{ identification: cleanCamelCaseEmail }])

expect(copy).not.toIncludeAnyMembers([{ identification: whiteSpaceEmail }])
expect(copy).toIncludeAnyMembers([{ identification: cleanWhiteSpaceEmail }])
})
})
Loading