fixes
This commit is contained in:
@@ -1,7 +1,3 @@
|
||||
export enum AuthProvidersEnum {
|
||||
email = 'email',
|
||||
facebook = 'facebook',
|
||||
google = 'google',
|
||||
twitter = 'twitter',
|
||||
apple = 'apple',
|
||||
}
|
||||
|
||||
@@ -72,82 +72,6 @@ describe('AuthService inactive-user enforcement and safe logging', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects social login when the existing account is inactive', async () => {
|
||||
const inactive = socialUser(
|
||||
AuthProvidersEnum.google,
|
||||
RoleEnum.user,
|
||||
StatusEnum.inactive,
|
||||
);
|
||||
configureSocialQueries([inactive], inactive);
|
||||
|
||||
await expect(
|
||||
service.validateSocialLogin(AuthProvidersEnum.google, {
|
||||
id: 'social-id',
|
||||
email: inactive.email,
|
||||
firstName: 'Inactive',
|
||||
lastName: 'User',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
|
||||
expect(usersService.update).not.toHaveBeenCalled();
|
||||
expect(jwtService.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reloads and rejects a concurrently deactivated social user instead of signing stale state', async () => {
|
||||
const stale = socialUser(
|
||||
AuthProvidersEnum.google,
|
||||
RoleEnum.admin,
|
||||
StatusEnum.active,
|
||||
);
|
||||
const current = socialUser(
|
||||
AuthProvidersEnum.google,
|
||||
RoleEnum.user,
|
||||
StatusEnum.inactive,
|
||||
);
|
||||
configureSocialQueries([stale], current);
|
||||
|
||||
await expect(
|
||||
service.validateSocialLogin(AuthProvidersEnum.google, {
|
||||
id: stale.socialId,
|
||||
email: 'updated@example.com',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
|
||||
expect(dataSource.transaction).toHaveBeenCalledTimes(1);
|
||||
expect(userRepository.save).not.toHaveBeenCalledWith(stale);
|
||||
expect(usersService.update).not.toHaveBeenCalled();
|
||||
expect(jwtService.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
AuthProvidersEnum.facebook,
|
||||
AuthProvidersEnum.google,
|
||||
AuthProvidersEnum.twitter,
|
||||
AuthProvidersEnum.apple,
|
||||
])(
|
||||
'locks and reloads an existing %s user, narrowly updates email, and signs the current role',
|
||||
async (provider) => {
|
||||
const stale = socialUser(provider, RoleEnum.admin, StatusEnum.active);
|
||||
const current = socialUser(provider, RoleEnum.user, StatusEnum.active);
|
||||
configureSocialQueries([stale], current);
|
||||
|
||||
const result = await service.validateSocialLogin(provider, {
|
||||
id: stale.socialId,
|
||||
email: 'updated@example.com',
|
||||
});
|
||||
|
||||
expect(userRepository.update).toHaveBeenCalledWith(stale.id, {
|
||||
email: 'updated@example.com',
|
||||
});
|
||||
expect(userRepository.save).not.toHaveBeenCalledWith(stale);
|
||||
expect(jwtService.sign).toHaveBeenCalledWith({
|
||||
id: current.id,
|
||||
role: current.role,
|
||||
});
|
||||
expect(result.user).toBe(current);
|
||||
},
|
||||
);
|
||||
|
||||
it('never includes an email in an unknown-user login audit event', async () => {
|
||||
usersService.findOne.mockResolvedValue(undefined);
|
||||
|
||||
@@ -204,11 +128,7 @@ describe('AuthService inactive-user enforcement and safe logging', () => {
|
||||
await service.confirmEmail('confirmation-hash');
|
||||
|
||||
expect(dataSource.transaction).toHaveBeenCalledTimes(1);
|
||||
expect(lockedUserQuery.setLock).toHaveBeenCalledWith(
|
||||
'pessimistic_write',
|
||||
undefined,
|
||||
['user'],
|
||||
);
|
||||
expect(lockedUserQuery.setLock).toHaveBeenCalledWith('pessimistic_write');
|
||||
expect(confirmationUser.status).toEqual({ id: StatusEnum.active });
|
||||
expect(confirmationUser.hash).toBeNull();
|
||||
expect(userRepository.save).toHaveBeenCalledWith(confirmationUser);
|
||||
@@ -247,45 +167,4 @@ describe('AuthService inactive-user enforcement and safe logging', () => {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function socialUser(
|
||||
provider: AuthProvidersEnum,
|
||||
roleId: RoleEnum,
|
||||
statusId: StatusEnum,
|
||||
) {
|
||||
return {
|
||||
...user(statusId),
|
||||
email: 'old@example.com',
|
||||
socialId: `${provider}-id`,
|
||||
provider,
|
||||
role: { id: roleId, name: roleId === RoleEnum.admin ? 'Admin' : 'User' },
|
||||
hash: 'stale-hash',
|
||||
};
|
||||
}
|
||||
|
||||
function configureSocialQueries(candidates: any[], current: any) {
|
||||
const candidateQuery = chain({ getMany: jest.fn(() => candidates) });
|
||||
const reloadQuery = chain({ getOne: jest.fn(() => current) });
|
||||
userRepository.createQueryBuilder = jest.fn((alias: string) =>
|
||||
alias === 'socialCandidate' ? candidateQuery : reloadQuery,
|
||||
);
|
||||
userRepository.update = jest.fn();
|
||||
}
|
||||
|
||||
function chain(overrides: Record<string, jest.Mock>) {
|
||||
const query: Record<string, jest.Mock> = {};
|
||||
[
|
||||
'leftJoinAndSelect',
|
||||
'where',
|
||||
'orWhere',
|
||||
'andWhere',
|
||||
'setParameter',
|
||||
'setParameters',
|
||||
'setLock',
|
||||
'orderBy',
|
||||
].forEach((method) => {
|
||||
query[method] = jest.fn(() => query);
|
||||
});
|
||||
return Object.assign(query, overrides);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -18,7 +18,6 @@ import { plainToClass } from 'class-transformer';
|
||||
import { Status } from 'src/statuses/entities/status.entity';
|
||||
import { Role } from 'src/roles/entities/role.entity';
|
||||
import { AuthProvidersEnum } from './auth-providers.enum';
|
||||
import { SocialInterface } from 'src/social/interfaces/social.interface';
|
||||
import { AuthRegisterLoginDto } from './dto/auth-register-login.dto';
|
||||
import { UsersService } from 'src/users/users.service';
|
||||
import { ForgotService } from 'src/forgot/forgot.service';
|
||||
@@ -113,74 +112,6 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
async validateSocialLogin(
|
||||
authProvider: string,
|
||||
socialData: SocialInterface,
|
||||
): Promise<{ token: string; user: User }> {
|
||||
const socialEmail = socialData.email?.toLowerCase();
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const repository = manager.getRepository(User);
|
||||
const candidateQuery = repository
|
||||
.createQueryBuilder('socialCandidate')
|
||||
.where(
|
||||
'socialCandidate.socialId = :socialId AND socialCandidate.provider = :authProvider',
|
||||
{ socialId: socialData.id, authProvider },
|
||||
);
|
||||
if (socialEmail) {
|
||||
candidateQuery.orWhere('socialCandidate.email = :socialEmail', {
|
||||
socialEmail,
|
||||
});
|
||||
}
|
||||
const candidates = await candidateQuery
|
||||
.setLock('pessimistic_write', undefined, ['socialCandidate'])
|
||||
.orderBy('socialCandidate.id', 'ASC')
|
||||
.getMany();
|
||||
const socialUser = candidates.find(
|
||||
(candidate) =>
|
||||
candidate.socialId === socialData.id &&
|
||||
candidate.provider === authProvider,
|
||||
);
|
||||
const emailUser = socialEmail
|
||||
? candidates.find((candidate) => candidate.email === socialEmail)
|
||||
: undefined;
|
||||
let user = socialUser ?? emailUser;
|
||||
if (!user) {
|
||||
user = await repository.save(
|
||||
repository.create({
|
||||
email: socialEmail,
|
||||
firstName: socialData.firstName,
|
||||
lastName: socialData.lastName,
|
||||
socialId: socialData.id,
|
||||
provider: authProvider,
|
||||
role: { id: RoleEnum.user } as Role,
|
||||
status: { id: StatusEnum.active } as Status,
|
||||
}),
|
||||
);
|
||||
} else if (
|
||||
socialUser &&
|
||||
socialEmail &&
|
||||
!emailUser &&
|
||||
socialUser.email !== socialEmail
|
||||
) {
|
||||
await repository.update(socialUser.id, { email: socialEmail });
|
||||
}
|
||||
const currentUser = await repository
|
||||
.createQueryBuilder('currentSocialUser')
|
||||
.leftJoinAndSelect('currentSocialUser.role', 'role')
|
||||
.leftJoinAndSelect('currentSocialUser.status', 'status')
|
||||
.where('currentSocialUser.id = :userId', { userId: user.id })
|
||||
.setLock('pessimistic_write', undefined, ['currentSocialUser'])
|
||||
.getOne();
|
||||
if (!currentUser) throw new UnauthorizedException();
|
||||
await this.assertActiveUser(currentUser);
|
||||
const token = await this.jwtService.sign({
|
||||
id: currentUser.id,
|
||||
role: currentUser.role,
|
||||
});
|
||||
return { token, user: currentUser };
|
||||
});
|
||||
}
|
||||
|
||||
async register(dto: AuthRegisterLoginDto): Promise<void> {
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
@@ -222,7 +153,7 @@ export class AuthService {
|
||||
const user = await repository
|
||||
.createQueryBuilder('user')
|
||||
.where('user.hash = :hash', { hash })
|
||||
.setLock('pessimistic_write', undefined, ['user'])
|
||||
.setLock('pessimistic_write')
|
||||
.getOne();
|
||||
if (!user) {
|
||||
throw new HttpException(
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Allow, IsNotEmpty } from 'class-validator';
|
||||
import { Tokens } from 'src/social/tokens';
|
||||
import { AuthProvidersEnum } from '../auth-providers.enum';
|
||||
|
||||
export class AuthSocialLoginDto {
|
||||
@Allow()
|
||||
@ApiProperty({ type: () => Tokens })
|
||||
tokens: Tokens;
|
||||
|
||||
@ApiProperty({ enum: AuthProvidersEnum })
|
||||
@IsNotEmpty()
|
||||
socialType: AuthProvidersEnum;
|
||||
|
||||
@Allow()
|
||||
@ApiProperty({ required: false })
|
||||
firstName?: string;
|
||||
|
||||
@Allow()
|
||||
@ApiProperty({ required: false })
|
||||
lastName?: string;
|
||||
}
|
||||
Reference in New Issue
Block a user