This commit is contained in:
Bastian Wagner
2024-09-12 21:33:11 +02:00
parent 6abfdcb632
commit c00aad559d
36 changed files with 1118 additions and 397 deletions

View File

@@ -0,0 +1,2 @@
export * from './user.repository';
export * from './ssouser.repository';

View File

@@ -0,0 +1,18 @@
import { Injectable } from '@nestjs/common';
import { Repository, DataSource } from 'typeorm';
import { SSOUser } from '../entitites';
@Injectable()
export class SsoUserRepository extends Repository<SSOUser> {
constructor(dataSource: DataSource) {
super(SSOUser, dataSource.createEntityManager());
}
findOneByUserId(id: string): Promise<SSOUser> {
return this.findOne({ where: { user: { id: id } } });
}
findByExternalId(id: string): Promise<SSOUser> {
return this.findOne({ where: { externalId: id } });
}
}

View File

@@ -0,0 +1,61 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Repository, DataSource } from 'typeorm';
import { User } from '../entitites';
import { CreateUserDto } from '../dto/create-user.dto';
import { SsoUserRepository } from './ssouser.repository';
@Injectable()
export class UserRepository extends Repository<User> {
constructor(
dataSource: DataSource,
private ssoRepo: SsoUserRepository,
) {
super(User, dataSource.createEntityManager());
}
findByUsername(username: string): Promise<User> {
return this.findOne({ where: { username }, relations: ['external'] });
}
findById(id: string): Promise<User> {
return this.findOne({ where: { id }, relations: ['external'] });
}
async createUser(createUserDto: CreateUserDto): Promise<User> {
if (
!(await this.checkIfCanInserted(
createUserDto.username,
createUserDto.externalId,
))
) {
throw new HttpException('user_exists', HttpStatus.UNPROCESSABLE_ENTITY);
}
try {
const created = this.create(createUserDto);
const sso = this.ssoRepo.create({
user: created,
externalId: createUserDto.externalId,
});
created.external = sso;
const user = await this.save(created);
sso.user = user;
this.ssoRepo.save(sso);
return user;
} catch {
throw new HttpException(
'not_successfull',
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
private async checkIfCanInserted(
username: string,
externalId: string,
): Promise<boolean> {
const user = await this.findOneBy({ username });
const sso = await this.ssoRepo.findByExternalId(externalId);
return user == null && sso == null;
}
}