@tomei/sso
Version:
Tomei SSO Package
1,165 lines (1,034 loc) • 40.7 kB
text/typescript
import { SessionService } from '../../../../src/session/session.service';
import { LoginUser } from '../../../../src/components/login-user/login-user';
import { ApplicationConfig, ComponentConfig } from '@tomei/config';
import { UserRepository } from '../../../../src/components/login-user/user.repository';
import { ClassError } from '@tomei/general';
import { Activity } from '@tomei/activity-history';
import { UserStatus } from '../../../../src/enum/user-status.enum';
import { YN } from '../../../../src/enum/yn.enum';
import SystemPrivilegeModel from '../../../../src/models/system-privilege.entity';
import { GroupSystemAccessRepository } from '../../../../src/components/group-system-access/group-system-access.repository';
import { GroupRepository } from '../../../../src/components/group/group.repository';
// describe('LoginUser', () => {
// afterAll(() => {
// jest.restoreAllMocks();
// });
// describe('init', () => {
// let sessionService: any;
// let userId: number;
// let dbTransaction: any;
// beforeEach(() => {
// sessionService = {};
// userId = 1;
// dbTransaction = null;
// });
// it('should initialize LoginUser with valid userId', async () => {
// const user = {
// UserId: 1,
// FullName: 'John Doe',
// Email: 'john.doe@example.com',
// Password: 'password',
// Status: 'active',
// DefaultPasswordChangedYN: 'yes',
// FirstLoginAt: new Date(),
// LastLoginAt: new Date(),
// MFAEnabled: 1,
// MFAConfig: 'config',
// RecoveryEmail: 'john.doe@example.com',
// FailedLoginAttemptCount: 0,
// LastFailedLoginAt: null,
// LastPasswordChangedAt: new Date(),
// NeedToChangePasswordYN: 'no',
// CreatedById: 1,
// CreatedAt: new Date(),
// UpdatedById: 1,
// UpdatedAt: new Date(),
// Staff: {
// FullName: 'John Doe',
// IdNo: '1234567890',
// Mobile: '1234567890',
// },
// };
// const findOneMock = jest
// .spyOn(UserRepository.prototype, 'findOne')
// .mockResolvedValueOnce(user as any);
// const result = await LoginUser.init(
// sessionService,
// userId,
// dbTransaction,
// );
// expect(findOneMock).toHaveBeenCalledTimes(1);
// expect(findOneMock).toHaveBeenCalledWith({
// where: {
// UserId: userId,
// },
// include: [
// {
// model: expect.anything(),
// },
// ],
// });
// expect(result).toBeInstanceOf(LoginUser);
// expect(result.UserId).toBe(user.UserId);
// expect(result.FullName).toBe(user.FullName);
// expect(result.Email).toBe(user.Email);
// expect(result.Password).toBe(user.Password);
// expect(result.Status).toBe(user.Status);
// expect(result.DefaultPasswordChangedYN).toBe(
// user.DefaultPasswordChangedYN,
// );
// expect(result.FirstLoginAt).toBe(user.FirstLoginAt);
// expect(result.LastLoginAt).toBe(user.LastLoginAt);
// expect(result.MFAEnabled).toBe(user.MFAEnabled);
// expect(result.MFAConfig).toBe(user.MFAConfig);
// expect(result.RecoveryEmail).toBe(user.RecoveryEmail);
// expect(result.FailedLoginAttemptCount).toBe(user.FailedLoginAttemptCount);
// expect(result.LastFailedLoginAt).toBe(user.LastFailedLoginAt);
// expect(result.LastPasswordChangedAt).toBe(user.LastPasswordChangedAt);
// expect(result.NeedToChangePasswordYN).toBe(user.NeedToChangePasswordYN);
// expect(result.CreatedById).toBe(user.CreatedById);
// expect(result.CreatedAt).toBe(user.CreatedAt);
// expect(result.UpdatedById).toBe(user.UpdatedById);
// expect(result.UpdatedAt).toBe(user.UpdatedAt);
// });
// it('should throw an error when user is not found', async () => {
// const findOneMock = jest
// .spyOn(UserRepository.prototype, 'findOne')
// .mockResolvedValueOnce(null);
// await expect(
// LoginUser.init(sessionService, userId, dbTransaction),
// ).rejects.toThrow(Error);
// expect(findOneMock).toHaveBeenCalledTimes(1);
// expect(findOneMock).toHaveBeenCalledWith({
// where: {
// UserId: userId,
// },
// include: [
// {
// model: expect.anything(),
// },
// ],
// });
// });
// });
// // describe('checkSession', () => {
// // it('should throw an error if session expired', async () => {
// // // Arrange
// // const systemCode = 'EZC';
// // const sessionId = 'ckymxuh8t000137t011w89zgk';
// // const userId = '755';
// // const sessionService = await SessionService.init();
// // const loginUser = await LoginUser.init(sessionService);
// // // Act
// // const checkSessionPromise = loginUser.checkSession(
// // systemCode,
// // sessionId,
// // userId,
// // );
// // // Assert
// // await expect(checkSessionPromise).rejects.toThrow('Session expired.');
// // });
// // it('should refresh the session duration if session is valid', async () => {
// // // Arrange
// // const systemCode = 'EZC';
// // const sessionId = 'ckymxuh8t000137t011w89zgk';
// // const userId = '755';
// // const sessionService = await SessionService.init();
// // const loginUser = await LoginUser.init(sessionService);
// // // Mock the _SessionService.retrieveUserSession method
// // loginUser['_SessionService'].retrieveUserSession = jest
// // .fn()
// // .mockResolvedValue({
// // systemLogins: [
// // {
// // code: systemCode,
// // sessionId: sessionId,
// // privileges: [],
// // },
// // ],
// // });
// // // Mock the _SessionService.refreshDuration method
// // loginUser['_SessionService'].refreshDuration = jest.fn();
// // // Act
// // const systemLogin = await loginUser.checkSession(
// // systemCode,
// // sessionId,
// // userId,
// // );
// // // Assert
// // expect(
// // loginUser['_SessionService'].retrieveUserSession,
// // ).toHaveBeenCalledWith(userId);
// // expect(loginUser['_SessionService'].refreshDuration).toHaveBeenCalledWith(
// // userId,
// // );
// // expect(systemLogin).toEqual({
// // code: systemCode,
// // sessionId: sessionId,
// // privileges: [],
// // });
// // });
// // });
// describe('shouldReleaseLock', () => {
// const minuteToAutoRelease = 5;
// const autoReleaseYN = 'Y';
// beforeEach(() => {
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementation((componentName: string, configKey: string) => {
// if (configKey === 'minuteToAutoRelease') {
// return minuteToAutoRelease as any;
// }
// if (configKey === 'autoReleaseYN') {
// return autoReleaseYN as any;
// }
// });
// });
// it('should return true if autoReleaseYN is "Y" and time difference is greater than minuteToAutoRelease', async () => {
// // Arrange
// const lastFailedLoginAt = new Date();
// lastFailedLoginAt.setMinutes(lastFailedLoginAt.getMinutes() - 10); // Set last failed login time to 10 minutes ago
// // Act
// const result = LoginUser.shouldReleaseLock(lastFailedLoginAt);
// // Assert
// expect(result).toBe(true);
// });
// it('should return false if autoReleaseYN is "Y" and time difference is less than or equal to minuteToAutoRelease', async () => {
// // Arrange
// const lastFailedLoginAt = new Date();
// lastFailedLoginAt.setMinutes(lastFailedLoginAt.getMinutes() - 3); // Set last failed login time to 3 minutes ago
// // Act
// const result = LoginUser.shouldReleaseLock(lastFailedLoginAt);
// // Assert
// expect(result).toBe(false);
// });
// it('should return false if autoReleaseYN is "N"', async () => {
// // Arrange
// const lastFailedLoginAt = new Date();
// // Act
// const result = LoginUser.shouldReleaseLock(lastFailedLoginAt);
// // Assert
// expect(result).toBe(false);
// });
// });
// describe('releaseLock', () => {
// it('should release the lock for a user', async () => {
// // Mock the necessary dependencies and setup the test data
// const UserId = 1;
// const dbTransaction = null;
// const updateMock = jest
// .spyOn(LoginUser['_Repository'], 'update')
// .mockImplementationOnce(() => Promise.resolve({}) as any);
// // Call the method under test
// LoginUser['releaseLock'](UserId, dbTransaction);
// // Verify the expected behavior
// expect(updateMock).toHaveBeenCalledTimes(1);
// expect(updateMock).toHaveBeenCalledWith(
// {
// FailedLoginAttemptCount: 0,
// Status: 'Active',
// },
// {
// where: {
// UserId,
// },
// transaction: dbTransaction,
// },
// );
// });
// });
// describe('checkUserInfoDuplicated', () => {
// it('should throw an error if duplicate user info is found', async () => {
// // Mock the dependencies and setup the test data
// const dbTransaction = null;
// const query = {
// Email: 'test@example.com',
// IdType: 'passport',
// IdNo: '123456789',
// ContactNo: '1234567890',
// };
// // Mock the LoginUser['_Repository'].findAll method to return a user
// jest
// .spyOn(LoginUser['_Repository'], 'findAll')
// .mockResolvedValueOnce([{ id: 1 }] as any);
// // Assert that the method throws an error
// await expect(
// LoginUser['checkUserInfoDuplicated'](dbTransaction, query),
// ).rejects.toThrowError();
// });
// it('should not throw an error if duplicate user info is not found', async () => {
// // Mock the dependencies and setup the test data
// const dbTransaction = null;
// const query = {
// Email: 'test@example.com',
// IdType: 'passport',
// IdNo: '123456789',
// ContactNo: '1234567890',
// };
// // Mock the LoginUser['_Repository'].findAll method to return an empty array
// jest.spyOn(LoginUser['_Repository'], 'findAll').mockResolvedValueOnce([]);
// // Assert that the method does not throw an error
// await expect(
// LoginUser['checkUserInfoDuplicated'](dbTransaction, query),
// ).resolves.not.toThrowError();
// });
// });
// describe('generateDefaultPassword', () => {
// const passwordPolicy = {
// minLen: 6,
// maxLen: 10,
// nonAcceptableChar: 'i,l,o',
// numOfCapitalLetters: 1,
// numOfNumbers: 1,
// numOfSpecialChars: 1,
// };
// beforeEach(() => {
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementation((componentName: string, configKey: string) => {
// if (configKey === 'passwordPolicy') {
// return passwordPolicy as any;
// }
// });
// });
// it('should generate a default password with the specified length', () => {
// const password = LoginUser['generateDefaultPassword']();
// expect(password.length).toBeGreaterThanOrEqual(6);
// expect(password.length).toBeLessThanOrEqual(10);
// });
// it('should generate a default password with at least one capital letter', () => {
// const password = LoginUser['generateDefaultPassword']();
// expect(/[A-Z]/.test(password)).toBe(true);
// });
// it('should generate a default password with at least one number', () => {
// const password = LoginUser['generateDefaultPassword']();
// expect(/[0-9]/.test(password)).toBe(true);
// });
// it('should generate a default password with at least one special character', () => {
// const password = LoginUser['generateDefaultPassword']();
// expect(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.test(password)).toBe(true);
// });
// it('should generate a default password without any non-acceptable characters', () => {
// const password = LoginUser['generateDefaultPassword']();
// const nonAcceptableChars = ['i', 'l', 'o'];
// expect(nonAcceptableChars.some((char) => password.includes(char))).toBe(
// false,
// );
// });
// });
// describe('setPassword', () => {
// const passwordPolicy = {
// minLen: 6,
// maxLen: 10,
// nonAcceptableChar: 'i,l,o',
// numOfCapitalLetters: 1,
// numOfNumbers: 1,
// numOfSpecialChars: 1,
// };
// beforeEach(() => {
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementation((componentName: string, configKey: string) => {
// if (configKey === 'passwordPolicy') {
// return passwordPolicy as any;
// }
// });
// });
// it('should set the password for the user', async () => {
// // Arrange
// const dbTransaction = null;
// const sessionService = await SessionService.init();
// const user = await LoginUser.init(sessionService);
// const password = 'N3wP@ssw0';
// // Act
// const result = await LoginUser['setPassword'](
// dbTransaction,
// user,
// password,
// );
// // Assert
// expect(result).toBeInstanceOf(LoginUser);
// await expect(
// LoginUser['setPassword'](dbTransaction, user, password),
// ).resolves.not.toThrowError();
// expect(result.Password).toBeDefined();
// });
// it('should throw an error if the password does not meet the security requirements', async () => {
// // Arrange
// const dbTransaction = null;
// const sessionService = await SessionService.init();
// const user = await LoginUser.init(sessionService);
// const password = 'weakpassword';
// // Act & Assert
// await expect(
// LoginUser['setPassword'](dbTransaction, user, password),
// ).rejects.toThrow();
// });
// });
// // describe('create', () => {
// // let loginUser: LoginUser;
// // let dbTransaction: any;
// // let user: LoginUser;
// // let newUser: any;
// // beforeEach(async () => {
// // const sessionService = await SessionService.init();
// // loginUser = await LoginUser.init(sessionService);
// // dbTransaction = null;
// // newUser = {
// // UserId: 1,
// // FullName: 'John Doe',
// // Email: 'john.doe@example.com',
// // Password: 'password',
// // Status: 'Active',
// // DefaultPasswordChangedYN: 'N',
// // FirstLoginAt: null,
// // LastLoginAt: null,
// // MFAEnabled: null,
// // MFAConfig: null,
// // RecoveryEmail: null,
// // FailedLoginAttemptCount: 0,
// // LastFailedLoginAt: null,
// // LastPasswordChangedAt: new Date(),
// // NeedToChangePasswordYN: 'N',
// // CreatedById: 1,
// // CreatedAt: new Date(),
// // UpdatedById: 1,
// // UpdatedAt: new Date(),
// // Staff: {
// // FullName: 'John Doe',
// // IdNo: '1234567890',
// // Mobile: '1234567890',
// // },
// // };
// // user = new (LoginUser as any)(sessionService, null, newUser);
// // });
// // afterEach(() => {
// // jest.clearAllMocks();
// // });
// // it('should create a new user record', async () => {
// // const checkPrivilegesMock = jest
// // .spyOn(loginUser, 'checkPrivileges')
// // .mockResolvedValueOnce(true);
// // const checkUserInfoDuplicatedMock = jest
// // .spyOn(LoginUser as any, 'checkUserInfoDuplicated')
// // .mockResolvedValueOnce(undefined);
// // const generateDefaultPasswordMock = jest
// // .spyOn(LoginUser as any, 'generateDefaultPassword')
// // .mockReturnValueOnce('defaultPassword');
// // const setPasswordMock = jest
// // .spyOn(LoginUser as any, 'setPassword')
// // .mockResolvedValueOnce(user);
// // const createMock = jest
// // .spyOn((LoginUser as any)['_Repository'], 'create')
// // .mockResolvedValueOnce({
// // ...newUser,
// // get: () => newUser,
// // });
// // const activityCreateMock = jest
// // .spyOn((Activity as any).prototype, 'create')
// // .mockResolvedValueOnce(undefined);
// // jest
// // .spyOn(ApplicationConfig, 'getComponentConfigValue')
// // .mockImplementation((configKey: string) => {
// // if (configKey === 'system-code') {
// // return 'SC';
// // }
// // });
// // const result = await LoginUser.create(loginUser, dbTransaction, user);
// // expect(checkPrivilegesMock).toHaveBeenCalledTimes(1);
// // expect(checkPrivilegesMock).toHaveBeenCalledWith(
// // ApplicationConfig.getComponentConfigValue('system-code'),
// // 'User - Create',
// // );
// // expect(checkUserInfoDuplicatedMock).toHaveBeenCalledTimes(1);
// // expect(checkUserInfoDuplicatedMock).toHaveBeenCalledWith(dbTransaction, {
// // Email: user.Email,
// // IdType: user.IDType,
// // IdNo: user.IDNo,
// // ContactNo: user.ContactNo,
// // });
// // expect(generateDefaultPasswordMock).toHaveBeenCalledTimes(1);
// // expect(setPasswordMock).toHaveBeenCalledTimes(1);
// // expect(setPasswordMock).toHaveBeenCalledWith(
// // dbTransaction,
// // user,
// // 'defaultPassword',
// // );
// // expect(createMock).toHaveBeenCalledTimes(1);
// // const userInfo = {
// // FullName: user.FullName,
// // IDNo: user.IDNo,
// // Email: user.Email,
// // ContactNo: user.ContactNo,
// // Password: user.Password,
// // Status: UserStatus.ACTIVE,
// // FirstLoginAt: null,
// // LastLoginAt: null,
// // MFAEnabled: null,
// // MFAConfig: null,
// // RecoveryEmail: null,
// // FailedLoginAttemptCount: 0,
// // LastFailedLoginAt: null,
// // LastPasswordChangedAt: null,
// // DefaultPasswordChangedYN: YN.No,
// // NeedToChangePasswordYN: YN.Yes,
// // CreatedById: loginUser.UserId,
// // CreatedAt: new Date(),
// // UpdatedById: loginUser.UserId,
// // UpdatedAt: new Date(),
// // UserId: null,
// // };
// // expect(createMock).toHaveBeenCalledWith(
// // {
// // Email: userInfo.Email,
// // Password: userInfo.Password,
// // Status: userInfo.Status,
// // DefaultPasswordChangedYN: userInfo.DefaultPasswordChangedYN,
// // FirstLoginAt: userInfo.FirstLoginAt,
// // LastLoginAt: userInfo.LastLoginAt,
// // MFAEnabled: userInfo.MFAEnabled,
// // MFAConfig: userInfo.MFAConfig,
// // RecoveryEmail: userInfo.RecoveryEmail,
// // FailedLoginAttemptCount: userInfo.FailedLoginAttemptCount,
// // LastFailedLoginAt: userInfo.LastFailedLoginAt,
// // LastPasswordChangedAt: userInfo.LastPasswordChangedAt,
// // NeedToChangePasswordYN: userInfo.NeedToChangePasswordYN,
// // CreatedById: userInfo.CreatedById,
// // CreatedAt: expect.any(Date),
// // UpdatedById: userInfo.UpdatedById,
// // UpdatedAt: expect.any(Date),
// // },
// // {
// // transaction: dbTransaction,
// // },
// // );
// // expect(activityCreateMock).toHaveBeenCalledTimes(1);
// // expect(result).toBeInstanceOf(LoginUser);
// // expect(result.Email).toBe(userInfo.Email);
// // expect(result.Password).toBe(userInfo.Password);
// // expect(result.Status).toBe(userInfo.Status);
// // expect(result.DefaultPasswordChangedYN).toBe(
// // userInfo.DefaultPasswordChangedYN,
// // );
// // expect(result.FirstLoginAt).toBe(null);
// // expect(result.LastLoginAt).toBe(null);
// // expect(result.MFAEnabled).toBe(userInfo.MFAEnabled);
// // expect(result.MFAConfig).toBe(userInfo.MFAConfig);
// // expect(result.RecoveryEmail).toBe(userInfo.RecoveryEmail);
// // expect(result.FailedLoginAttemptCount).toBe(
// // userInfo.FailedLoginAttemptCount,
// // );
// // expect(result.LastFailedLoginAt).toBe(userInfo.LastFailedLoginAt);
// // expect(result.LastPasswordChangedAt).toBe(userInfo.LastPasswordChangedAt);
// // expect(result.NeedToChangePasswordYN).toBe(
// // userInfo.NeedToChangePasswordYN,
// // );
// // expect(result.CreatedById).toBe(userInfo.CreatedById);
// // expect(result.UpdatedById).toBe(userInfo.UpdatedById);
// // });
// // it('should throw an error if user dont have the privilege to create new user', async () => {
// // jest.spyOn(loginUser, 'checkPrivileges').mockResolvedValueOnce(false);
// // await expect(
// // LoginUser.create(loginUser, dbTransaction, user),
// // ).rejects.toThrow(ClassError);
// // });
// // it('should throw an error if user email is missing', async () => {
// // user.Email = undefined;
// // jest.spyOn(loginUser, 'checkPrivileges').mockResolvedValueOnce(true);
// // await expect(
// // LoginUser.create(loginUser, dbTransaction, user),
// // ).rejects.toThrow(ClassError);
// // });
// // });
// describe('incrementFailedLoginAttemptCount', () => {
// afterAll(() => {
// jest.restoreAllMocks();
// });
// it('should increment FailedLoginAttemptCount and update user status', async () => {
// // Arrange
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser['FailedLoginAttemptCount'] = 2;
// loginUser['LastFailedLoginAt'] = new Date();
// loginUser['Status'] = UserStatus.ACTIVE;
// const dbTransaction = null;
// // Mock the static methods and properties
// jest
// .spyOn((LoginUser as any)['_Repository'], 'update')
// .mockReturnValueOnce(null);
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementation((componentName: string, configKey: string) => {
// if (configKey === 'maxFailedLoginAttempts') {
// return 3;
// }
// if (configKey === 'autoReleaseYN') {
// return 'Y';
// }
// });
// // Act
// await loginUser['incrementFailedLoginAttemptCount'](dbTransaction);
// // Assert
// expect(LoginUser['_Repository'].update).toHaveBeenCalledWith(
// {
// FailedLoginAttemptCount: 3,
// LastFailedLoginAt: expect.any(Date),
// Status: UserStatus.ACTIVE,
// },
// {
// where: {
// UserId: loginUser.UserId,
// },
// transaction: dbTransaction,
// },
// );
// });
// it('should throw an error if maxFailedLoginAttempts or autoReleaseYN is missing', async () => {
// // Arrange
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser['FailedLoginAttemptCount'] = 2;
// loginUser['LastFailedLoginAt'] = new Date();
// loginUser['Status'] = UserStatus.ACTIVE;
// const dbTransaction = null;
// // Mock the static methods and properties
// jest
// .spyOn((LoginUser as any)['_Repository'], 'update')
// .mockReturnValueOnce(null);
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementationOnce((componentName: string, configKey: string) => {
// if (configKey === 'maxFailedLoginAttempts') {
// return undefined;
// }
// if (configKey === 'autoReleaseYN') {
// return undefined;
// }
// });
// // Act and Assert
// await expect(
// loginUser['incrementFailedLoginAttemptCount'](dbTransaction),
// ).rejects.toThrow(
// new ClassError(
// 'LoginUser',
// 'LoginUserErrMsg0X',
// 'Missing maxFailedLoginAttempts and or autoReleaseYN. Please set in config file.',
// ),
// );
// });
// it('should lock the user account if the failed login attempts exceed the maximum allowed', async () => {
// // Arrange
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser['FailedLoginAttemptCount'] = 3;
// loginUser['LastFailedLoginAt'] = new Date();
// loginUser['Status'] = UserStatus.ACTIVE;
// const dbTransaction = null;
// // Mock the static methods and properties
// jest
// .spyOn((LoginUser as any)['_Repository'], 'update')
// .mockReturnValueOnce(null);
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementation((componentName: string, configKey: string) => {
// if (configKey === 'maxFailedLoginAttempts') {
// return 3;
// }
// if (configKey === 'autoReleaseYN') {
// return 'Y';
// }
// });
// // Act
// try {
// await loginUser['incrementFailedLoginAttemptCount'](dbTransaction);
// expect(false).toBe(true);
// } catch (error) {
// // Assert
// expect(LoginUser['_Repository'].update).toHaveBeenCalledWith(
// {
// FailedLoginAttemptCount: 4,
// LastFailedLoginAt: expect.any(Date),
// Status: UserStatus.LOCKED,
// },
// {
// where: {
// UserId: loginUser.UserId,
// },
// transaction: dbTransaction,
// },
// );
// expect(error).toBeInstanceOf(ClassError);
// expect(error.message).toBe(
// 'Your account has been temporarily locked due to too many failed login attempts, please try again later.',
// );
// }
// });
// it('should permanently lock the user account if the failed login attempts exceed the maximum allowed and autoReleaseYN is N', async () => {
// // Arrange
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser['FailedLoginAttemptCount'] = 3;
// loginUser['LastFailedLoginAt'] = new Date();
// loginUser['Status'] = UserStatus.ACTIVE;
// const dbTransaction = null;
// // Mock the static methods and properties
// jest
// .spyOn((LoginUser as any)['_Repository'], 'update')
// .mockReturnValueOnce(null);
// jest
// .spyOn(ComponentConfig, 'getComponentConfigValue')
// .mockImplementation((componentName: string, configKey: string) => {
// if (configKey === 'maxFailedLoginAttempts') {
// return 3;
// }
// if (configKey === 'autoReleaseYN') {
// return 'N';
// }
// });
// // Act
// try {
// await loginUser['incrementFailedLoginAttemptCount'](dbTransaction);
// expect(false).toBe(true);
// } catch (error) {
// // Assert
// expect(LoginUser['_Repository'].update).toHaveBeenCalledWith(
// {
// FailedLoginAttemptCount: 4,
// LastFailedLoginAt: expect.any(Date),
// Status: UserStatus.LOCKED,
// },
// {
// where: {
// UserId: loginUser.UserId,
// },
// transaction: dbTransaction,
// },
// );
// expect(error).toBeInstanceOf(ClassError);
// expect(error.message).toBe(
// 'Your account has been locked due to too many failed login attempts, please contact IT Support for instructions on how to unlock your account',
// );
// }
// });
// });
// describe('combineSystemAccess', () => {
// it('should combine user and group system access and remove duplicates', async () => {
// // Mock the necessary dependencies
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// const dbTransaction = null;
// const groups = [
// { InheritParentSystemAccessYN: true },
// { InheritParentSystemAccessYN: false },
// ];
// // Mock the necessary repository methods
// jest
// .spyOn(LoginUser as any, 'getInheritedSystemAccess')
// .mockResolvedValueOnce([
// { SystemCode: 'system1' },
// { SystemCode: 'system2' },
// ]);
// jest
// .spyOn((LoginUser as any)['_UserSystemAccessRepo'], 'findAll')
// .mockResolvedValueOnce([{ SystemCode: 'system3' }]);
// // Call the method
// const result = await LoginUser['combineSystemAccess'](
// loginUser,
// dbTransaction,
// groups,
// );
// // Assert the result
// expect(result).toEqual([
// { SystemCode: 'system3' },
// { SystemCode: 'system1' },
// { SystemCode: 'system2' },
// ]);
// });
// });
// describe('checkPrivileges', () => {
// it('should return true if user has the specified privilege', async () => {
// // Arrange
// const systemCode = 'SS';
// const privilegeName = 'Privilege 1';
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser.ObjectId = '1';
// // Mock the necessary methods
// const rus = jest
// .spyOn(SessionService.prototype, 'retrieveUserSession')
// .mockResolvedValueOnce({
// systemLogins: [
// {
// id: '1',
// sessionId: 'sessionId',
// code: systemCode,
// privileges: [privilegeName],
// },
// ],
// });
// // Act
// const hasPrivilege = await loginUser.checkPrivileges(
// systemCode,
// privilegeName,
// );
// // Assert
// expect(hasPrivilege).toBe(true);
// expect(rus).toHaveBeenCalledWith(loginUser.ObjectId);
// });
// it('should return false if user does not have the specified privilege', async () => {
// // Arrange
// const systemCode = 'SS';
// const privilegeName = 'Privilege 1';
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser.ObjectId = '1';
// // Mock the necessary methods
// const rus = jest
// .spyOn(SessionService.prototype, 'retrieveUserSession')
// .mockResolvedValueOnce({
// systemLogins: [
// {
// id: '1',
// sessionId: 'sessionId',
// code: systemCode,
// privileges: [],
// },
// ],
// });
// // Act
// const hasPrivilege = await loginUser.checkPrivileges(
// systemCode,
// privilegeName,
// );
// // Assert
// expect(hasPrivilege).toBe(false);
// expect(rus).toHaveBeenCalledWith(loginUser.ObjectId);
// });
// it('should throw an error if ObjectId is not set', async () => {
// // Arrange
// const systemCode = 'SS';
// const privilegeName = 'Privilege 1';
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// loginUser.ObjectId = null;
// // Act & Assert
// await expect(
// loginUser.checkPrivileges(systemCode, privilegeName),
// ).rejects.toThrowError();
// });
// });
// describe('getObjectPrivileges', () => {
// it('should return an array of privileges', async () => {
// // Mock the dependencies and setup the test data
// const systemCode = 'system1';
// const dbTransaction = null;
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// // Mock the UserObjectPrivilegeRepo findAll method
// const findAllMock = jest
// .spyOn(LoginUser['_UserObjectPrivilegeRepo'], 'findAll')
// .mockResolvedValue([
// {
// PrivilegeCode: 'privilege1',
// Privilege: {
// PrivilegeCode: 'privilege1',
// SystemCode: systemCode,
// Name: 'privilege1',
// },
// },
// {
// PrivilegeCode: 'privilege2',
// Privilege: {
// PrivilegeCode: 'privilege2',
// Name: 'privilege2',
// },
// },
// ] as any);
// // Call the getObjectPrivileges method
// const result = await loginUser['getObjectPrivileges'](
// systemCode,
// dbTransaction,
// );
// // Assertions
// expect(findAllMock).toHaveBeenCalledTimes(1);
// expect(findAllMock).toHaveBeenCalledWith({
// where: {
// UserId: loginUser.UserId,
// },
// include: {
// model: SystemPrivilegeModel,
// where: {
// SystemCode: systemCode,
// Status: 'Active',
// },
// },
// transaction: dbTransaction,
// });
// expect(result).toEqual(['privilege1', 'privilege2']);
// });
// it('should throw an error if an exception occurs', async () => {
// // Mock the dependencies and setup the test data
// const systemCode = 'system1';
// const dbTransaction = null;
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// // Mock the UserObjectPrivilegeRepo findAll method to throw an error
// jest
// .spyOn(LoginUser['_UserObjectPrivilegeRepo'], 'findAll')
// .mockRejectedValue(new Error('Database error'));
// // Call the getObjectPrivileges method and expect it to throw an error
// await expect(
// loginUser['getObjectPrivileges'](systemCode, dbTransaction),
// ).rejects.toThrow(Error);
// });
// });
// describe('getUserPersonalPrivileges', () => {
// it('should return an array of privileges', async () => {
// // Arrange
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// const systemCode = 'system1';
// const dbTransaction = null;
// // Mock the findAll method of UserPrivilegeRepo
// const findAllMock = jest.spyOn(
// LoginUser['_UserPrivilegeRepo'],
// 'findAll',
// );
// findAllMock.mockResolvedValue([
// { Privilege: { Name: 'privilege1' } },
// { Privilege: { Name: 'privilege2' } },
// ] as any);
// // Act
// const privileges = await loginUser['getUserPersonalPrivileges'](
// systemCode,
// dbTransaction,
// );
// // Assert
// expect(privileges).toEqual(['privilege1', 'privilege2']);
// expect(findAllMock).toHaveBeenCalledTimes(1);
// expect(findAllMock).toHaveBeenCalledWith({
// where: {
// UserId: loginUser.UserId,
// Status: 'Active',
// },
// include: {
// model: SystemPrivilegeModel,
// where: {
// SystemCode: systemCode,
// Status: 'Active',
// },
// },
// transaction: dbTransaction,
// });
// });
// it('should throw an error if an error occurs', async () => {
// // Arrange
// const sessionService = await SessionService.init();
// const loginUser = await LoginUser.init(sessionService);
// const systemCode = 'system1';
// const dbTransaction = null;
// // Mock the findAll method of UserPrivilegeRepo to throw an error
// const findAllMock = jest.spyOn(
// LoginUser['_UserPrivilegeRepo'],
// 'findAll',
// );
// findAllMock.mockRejectedValue(new Error('Database error'));
// // Act and Assert
// await expect(
// loginUser['getUserPersonalPrivileges'](systemCode, dbTransaction),
// ).rejects.toThrow(Error);
// expect(findAllMock).toHaveBeenCalledTimes(1);
// expect(findAllMock).toHaveBeenCalledWith({
// where: {
// UserId: loginUser.UserId,
// Status: 'Active',
// },
// include: {
// model: SystemPrivilegeModel,
// where: {
// SystemCode: systemCode,
// Status: 'Active',
// },
// },
// transaction: dbTransaction,
// });
// });
// });
// describe('getInheritedSystemAccess', () => {
// it('should return group system access with its parent group system access if applicable', async () => {
// // Mock the necessary dependencies
// const dbTransaction = null;
// const group = {
// GroupCode: 'group1',
// InheritParentPrivilegeYN: 'Y',
// ParentGroupCode: 'parentGroup',
// } as any;
// const parentGroup = {
// GroupCode: 'parentGroup',
// InheritParentPrivilegeYN: 'N',
// ParentGroupCode: null,
// } as any;
// const systemAccess = [
// {
// SystemCode: 'system1',
// GroupCode: 'group1',
// System: { SystemCode: 'system1' },
// },
// {
// SystemCode: 'system2',
// GroupCode: 'group1',
// System: { SystemCode: 'system1' },
// },
// ] as any;
// const parentSystemAccess = [
// {
// SystemCode: 'system3',
// GroupCode: 'parentGroup',
// System: { SystemCode: 'system3' },
// },
// ] as any;
// // Mock the necessary repository methods
// const groupFindByPkMock = jest
// .spyOn(GroupRepository.prototype, 'findByPk')
// .mockResolvedValueOnce(parentGroup as any);
// const systemAccessFindAllMock = jest
// .spyOn(GroupSystemAccessRepository.prototype, 'findAll')
// .mockImplementation((options: any) => {
// if (options.where.GroupCode === group.GroupCode) {
// return Promise.resolve(systemAccess);
// } else if (options.where.GroupCode === parentGroup.GroupCode) {
// return Promise.resolve(parentSystemAccess);
// }
// });
// // Call the method
// const result = await LoginUser['getInheritedSystemAccess'](
// dbTransaction,
// group,
// );
// console.log(result);
// // Assert the result
// expect(result).toEqual([
// {
// SystemCode: 'system1',
// GroupCode: 'group1',
// System: { SystemCode: 'system1' },
// },
// {
// SystemCode: 'system2',
// GroupCode: 'group1',
// System: { SystemCode: 'system1' },
// },
// {
// SystemCode: 'system3',
// GroupCode: 'parentGroup',
// System: { SystemCode: 'system3' },
// },
// ]);
// expect(groupFindByPkMock).toHaveBeenCalledWith(
// group.ParentGroupCode,
// dbTransaction,
// );
// expect(systemAccessFindAllMock).toHaveBeenCalledTimes(2);
// });
// });
// });