Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • web-et-numerique/factory/pamn_plateforme-des-acteurs-de-la-mediation-numerique/pamn_server
1 result
Show changes
......@@ -2,7 +2,7 @@ import { HttpModule } from '@nestjs/axios';
import { HttpException, HttpStatus } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import * as bcrypt from 'bcrypt';
import { Types } from 'mongoose';
import { employersMockData } from '../../../test/mock/data/employers.mock.data';
......@@ -131,7 +131,7 @@ describe('UsersService', () => {
let usersService: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
const module = await Test.createTestingModule({
imports: [HttpModule, MailerModule, ConfigurationModule],
providers: [
UsersService,
......@@ -313,7 +313,6 @@ describe('UsersService', () => {
jest.spyOn(usersService, 'findById').mockResolvedValue(null);
try {
await usersService.addPersonalOffer('abcd', personalOfferDocumentMock);
// Fail test if above expression doesn't throw anything.
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe('User not found for the personal offer attachment');
......@@ -324,7 +323,6 @@ describe('UsersService', () => {
jest.spyOn(usersService, 'findById').mockResolvedValue(usersMockData[1]);
try {
await usersService.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock);
// Fail test if above expression doesn't throw anything.
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe('Personal offer already exist in the user');
......
......@@ -46,7 +46,6 @@ export class UsersService {
/**
* Create a user account
* @param createUserDto CreateUserDto
*/
public async create(createUserDto: CreateUserDto): Promise<IUser> {
const userInDb = await this.findOne(createUserDto.email);
......@@ -79,13 +78,12 @@ export class UsersService {
}
/**
* Verify password strenth with the following rule:
* Verify password strength with the following rule:
* - The string must contain at least 1 lowercase alphabetical character
* - The string must contain at least 1 uppercase alphabetical character
* - The string must contain at least 1 numeric character
* - The string must contain at least one special character, reserved RegEx characters are escaped to avoid conflict
* - The string must be eight characters or longer
* @param password string
*/
public isStrongPassword(password: string): boolean {
const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[*.! @#$%^&(){}\[\]:;<>,?\/\\~_+\-=|])(?=.{8,})/; //NOSONAR
......@@ -194,7 +192,6 @@ export class UsersService {
/**
* Return a user after credential checking.
* Use for login action
* @param param LoginDto
*/
public async checkLogin({ email, password }: LoginDto): Promise<IUser> {
const user = await this.findOne(email, true);
......@@ -217,7 +214,6 @@ export class UsersService {
/**
* Generate activation token and send it to user by email, in order to validate
* a new account.
* @param user User
*/
private async verifyUserMail(user: IUser): Promise<IUser> {
const token = crypto.randomBytes(64).toString('hex');
......@@ -233,7 +229,6 @@ export class UsersService {
/**
* Send verification email to user
* @param user User
*/
public async sendVerifyUserMail(user: IUser): Promise<AxiosResponse> {
const config = this.mailerService.config;
......@@ -268,8 +263,6 @@ export class UsersService {
/**
* Check that the given token is associated to userId. If it's true, validate user account.
* @param userId string
* @param token string
*/
public async validateUser(userId: string, token: string): Promise<User | HttpException> {
const user = await this.findById(userId);
......@@ -360,7 +353,6 @@ export class UsersService {
/**
* Send reset password email based on ejs template
* @param email string
*/
public async sendResetPasswordEmail(email: string): Promise<void> {
const user = await this.findOne(email);
......@@ -385,7 +377,6 @@ export class UsersService {
/**
* Verify reset password token existence
* @param token string
*/
public async checkPasswordResetToken(token: string): Promise<boolean> {
const user = await this.userModel.findOne({ resetPasswordToken: token }).exec();
......@@ -395,8 +386,6 @@ export class UsersService {
/**
* Change password with the given token and password
* Token existence and password strength are verified
* @param password string
* @param token string
*/
public async resetPassword(password: string, token: string): Promise<void> {
const user = await this.userModel.findOne({ resetPasswordToken: token }).exec();
......@@ -446,11 +435,11 @@ export class UsersService {
}
public getJobAttachedUsers(jobId: JobDocument): Promise<IUser[]> {
return this.userModel.find({ job: jobId._id }).select('-password -job').exec();
return this.userModel.find({ job: jobId._id.toString() }).select('-password -job').exec();
}
public getEmployerAttachedUsers(employerId: EmployerDocument): Promise<IUser[]> {
return this.userModel.find({ employer: employerId._id }).select('-password -employer').exec();
return this.userModel.find({ employer: employerId._id.toString() }).select('-password -employer').exec();
}
public async populateJobswithUsers(jobs: JobDocument[]) {
......@@ -523,9 +512,6 @@ export class UsersService {
/**
* Creates a 1 month valid token for a pending structure request
* @param user
* @param idStructure
* @returns
*/
private createPendingToken(user: IUser, idStructure: string): { token: string; createdAt: string } {
const local = DateTime.local().setZone('Europe/Paris');
......@@ -537,9 +523,6 @@ export class UsersService {
/**
* Updates the array of user's pending structures
* @param userEmail
* @param idStructure
* @returns
*/
public async updatePendingStructureLinked(
userEmail: string,
......@@ -566,10 +549,7 @@ export class UsersService {
}
/**
* Removes a strcture from the users's pending list
* @param userEmail
* @param idStructure
* @returns
* Removes a structure from the users's pending list
*/
public async removeFromPendingStructureLinked(
userEmail: string,
......@@ -779,8 +759,6 @@ export class UsersService {
/**
* Add the personal offer to the user
* @param userId string
* @param personalOfferDocument PersonalOfferDocument
* @returns {IUser} user with personal offer added
*/
public async addPersonalOffer(userId: string, personalOfferDocument: PersonalOfferDocument): Promise<IUser> {
......@@ -816,7 +794,6 @@ export class UsersService {
/**
* Updates the denormalized fields of the structures of the user
* @param user
*/
public updateStructuresDenormalizedFields(user: IUser) {
user.structuresLink.forEach(async (structureId) => {
......@@ -824,13 +801,6 @@ export class UsersService {
});
}
/**
*
* @param profile
* @param userId
* @param employer
* @param job
*/
public async updateUserProfile(
userId: Types.ObjectId,
employer: EmployerDocument,
......@@ -861,11 +831,6 @@ export class UsersService {
return updated;
}
/**
*
* @param job
* @param userId
*/
public async updateUserJob(userId: Types.ObjectId, job: JobDocument): Promise<IUser> {
this.logger.debug(`updateUserProfile - Job | ${userId}`);
const updated = await this.userModel
......@@ -882,10 +847,6 @@ export class UsersService {
return updated;
}
/**
*
* @param userId
*/
public async removeUserJob(userId: Types.ObjectId): Promise<IUser> {
this.logger.debug(`updateUserProfile - RemoveJob | ${userId}`);
const updated = await this.userModel
......@@ -902,11 +863,6 @@ export class UsersService {
return updated;
}
/**
*
* @param employer
* @param userId
*/
public async updateUserEmployer(userId: Types.ObjectId, employer: EmployerDocument): Promise<IUser> {
this.logger.debug(`updateUserProfile - Employer | ${userId}`);
const updated = await this.userModel
......@@ -919,10 +875,6 @@ export class UsersService {
return updated;
}
/**
*
* @param userId
*/
public async removeUserEmployer(userId: Types.ObjectId): Promise<IUser> {
this.logger.debug(`updateUserProfile - RemoveEmployer | ${userId}`);
const updated = await this.userModel.findByIdAndUpdate({ _id: userId }, { $unset: { employer: 1 } }).exec();
......@@ -935,8 +887,6 @@ export class UsersService {
/**
* Update user details (name, surname and phone number)
* @param {UpdateDetailsDto}
* @returns {User}
*/
public async updateUserDetails(userId: string, updatedDetails: UpdateDetailsDto): Promise<IUser> {
this.logger.debug(`updateUserDetails | ${userId}`);
......@@ -951,8 +901,6 @@ export class UsersService {
/**
* Update user's description
* @param {DescriptionDto}
* @returns {User}
*/
public async updateDescription(userId: string, description: DescriptionDto) {
this.logger.debug(`updateUserDescription | ${userId}`);
......@@ -970,7 +918,6 @@ export class UsersService {
/**
* Update user's lastLoginDate
* @returns {User}
*/
public async updateLastLoginDate(user: IUser) {
this.logger.debug(`updateLastLoginDate | ${user._id}`);
......
import { Types } from 'mongoose';
import { IUser } from '../../../src/users/interfaces/user.interface';
import { IUserRegistry } from '../../../src/users/interfaces/userRegistry.interface';
import { User } from '../../../src/users/schemas/user.schema';
export const usersMockData: IUser[] = [
{
......@@ -222,8 +223,8 @@ export const userRegistryMockData: IUserRegistry = {
save: jest.fn(),
} as any;
export const mockUser = {
_id: 'id',
export const mockUser: User = {
// _id: 'id',
validationToken:
'cf1c74c22cedb6b575945098db42d2f493fb759c9142c6aff7980f252886f36ee086574ee99a06bc99119079257116c959c8ec870949cebdef2b293666dbca42',
emailVerified: true,
......@@ -234,4 +235,13 @@ export const mockUser = {
surname: 'Pauline',
personalOffers: [],
structuresLink: [new Types.ObjectId('6093ba0e2ab5775cfc01ed3e')],
createdAt: new Date(2024, 1, 1),
phone: '',
resetPasswordToken: '',
changeEmailToken: '',
newEmail: '',
pendingStructuresLink: [],
structureOutdatedMailSent: [],
unattachedSince: new Date(2024, 1, 1),
lastLoginDate: new Date(2024, 1, 1),
};
......@@ -1309,6 +1309,9 @@ export class StructuresServiceMock {
async updateDenormalizedFields() {
return;
}
async getInseeCode() {
return null;
}
}
export const mockSearchAdressBan: { features: PhotonPoints[] } = {
......
{
"include": ["src/**/*.ts"],
"exclude": ["src/test.ts", "src/**/*.spec.ts"]
}