1
0
mirror of https://github.com/stonith404/pingvin-share.git synced 2024-11-15 11:50:34 +01:00

refactor: run formatter

This commit is contained in:
Elias Schneider 2024-09-27 16:03:53 +02:00
parent 3310fe53b3
commit 8f16d6b53e
No known key found for this signature in database
GPG Key ID: 07E623B294202B6C
5 changed files with 87 additions and 49 deletions

View File

@ -4,7 +4,7 @@ import { PrismaService } from "./prisma/prisma.service";
@Controller("/") @Controller("/")
export class AppController { export class AppController {
constructor(private prismaService: PrismaService) { } constructor(private prismaService: PrismaService) {}
@Get("health") @Get("health")
async health(@Res({ passthrough: true }) res: Response) { async health(@Res({ passthrough: true }) res: Response) {

View File

@ -29,7 +29,7 @@ export class AuthService {
private emailService: EmailService, private emailService: EmailService,
private ldapService: LdapService, private ldapService: LdapService,
private userService: UserSevice, private userService: UserSevice,
) { } ) {}
private readonly logger = new Logger(AuthService.name); private readonly logger = new Logger(AuthService.name);
async signUp(dto: AuthRegisterDTO, ip: string, isAdmin?: boolean) { async signUp(dto: AuthRegisterDTO, ip: string, isAdmin?: boolean) {
@ -99,10 +99,7 @@ export class AuthService {
dto.password, dto.password,
); );
if (ldapUser) { if (ldapUser) {
const user = await this.userService.findOrCreateFromLDAP( const user = await this.userService.findOrCreateFromLDAP(dto, ldapUser);
dto,
ldapUser,
);
this.logger.log( this.logger.log(
`Successful LDAP login for user ${ldapUsername} (${user.id}) from IP ${ip}`, `Successful LDAP login for user ${ldapUsername} (${user.id}) from IP ${ip}`,
); );

View File

@ -9,7 +9,7 @@ export class LdapService {
constructor( constructor(
@Inject(ConfigService) @Inject(ConfigService)
private readonly serviceConfig: ConfigService, private readonly serviceConfig: ConfigService,
) { } ) {}
private async createLdapConnection(): Promise<Client> { private async createLdapConnection(): Promise<Client> {
const ldapUrl = this.serviceConfig.get("ldap.url"); const ldapUrl = this.serviceConfig.get("ldap.url");
@ -26,7 +26,10 @@ export class LdapService {
const bindDn = this.serviceConfig.get("ldap.bindDn") || null; const bindDn = this.serviceConfig.get("ldap.bindDn") || null;
if (bindDn) { if (bindDn) {
try { try {
await ldapClient.bind(bindDn, this.serviceConfig.get("ldap.bindPassword")); await ldapClient.bind(
bindDn,
this.serviceConfig.get("ldap.bindPassword"),
);
} catch (error) { } catch (error) {
this.logger.warn(`Failed to bind to default user: ${error}`); this.logger.warn(`Failed to bind to default user: ${error}`);
throw new Error("failed to bind to default user"); throw new Error("failed to bind to default user");
@ -41,7 +44,9 @@ export class LdapService {
password: string, password: string,
): Promise<Entry | null> { ): Promise<Entry | null> {
if (!username.match(/^[a-zA-Z0-9-_.@]+$/)) { if (!username.match(/^[a-zA-Z0-9-_.@]+$/)) {
this.logger.verbose(`Username ${username} does not match username pattern. Authentication failed.`); this.logger.verbose(
`Username ${username} does not match username pattern. Authentication failed.`,
);
return null; return null;
} }
@ -57,27 +62,35 @@ export class LdapService {
scope: "sub", scope: "sub",
attributes: ["*"], attributes: ["*"],
returnAttributeValues: true returnAttributeValues: true,
}); });
if (searchEntries.length > 1) { if (searchEntries.length > 1) {
/* too many users found */ /* too many users found */
this.logger.verbose(`Authentication for username ${username} failed. Too many users found with query ${searchQuery}`); this.logger.verbose(
`Authentication for username ${username} failed. Too many users found with query ${searchQuery}`,
);
return null; return null;
} else if (searchEntries.length == 0) { } else if (searchEntries.length == 0) {
/* user not found */ /* user not found */
this.logger.verbose(`Authentication for username ${username} failed. No user found with query ${searchQuery}`); this.logger.verbose(
`Authentication for username ${username} failed. No user found with query ${searchQuery}`,
);
return null; return null;
} }
const targetEntity = searchEntries[0]; const targetEntity = searchEntries[0];
this.logger.verbose(`Trying to authenticate ${username} against LDAP user ${targetEntity.dn}`); this.logger.verbose(
`Trying to authenticate ${username} against LDAP user ${targetEntity.dn}`,
);
try { try {
await ldapClient.bind(targetEntity.dn, password); await ldapClient.bind(targetEntity.dn, password);
return targetEntity; return targetEntity;
} catch (error) { } catch (error) {
if (error instanceof InvalidCredentialsError) { if (error instanceof InvalidCredentialsError) {
this.logger.verbose(`Failed to authenticate ${username} against ${targetEntity.dn}. Invalid credentials.`); this.logger.verbose(
`Failed to authenticate ${username} against ${targetEntity.dn}. Invalid credentials.`,
);
return null; return null;
} }

View File

@ -13,7 +13,12 @@ import { NextFunction, Request, Response } from "express";
import * as fs from "fs"; import * as fs from "fs";
import { AppModule } from "./app.module"; import { AppModule } from "./app.module";
import { ConfigService } from "./config/config.service"; import { ConfigService } from "./config/config.service";
import { DATA_DIRECTORY, LOG_LEVEL_AVAILABLE, LOG_LEVEL_DEFAULT, LOG_LEVEL_ENV } from "./constants"; import {
DATA_DIRECTORY,
LOG_LEVEL_AVAILABLE,
LOG_LEVEL_DEFAULT,
LOG_LEVEL_ENV,
} from "./constants";
function generateNestJsLogLevels(): LogLevel[] { function generateNestJsLogLevels(): LogLevel[] {
if (LOG_LEVEL_ENV) { if (LOG_LEVEL_ENV) {
@ -34,7 +39,7 @@ async function bootstrap() {
Logger.log(`Showing ${logLevels.join(", ")} messages`); Logger.log(`Showing ${logLevels.join(", ")} messages`);
const app = await NestFactory.create<NestExpressApplication>(AppModule, { const app = await NestFactory.create<NestExpressApplication>(AppModule, {
logger: logLevels logger: logLevels,
}); });
app.useGlobalPipes(new ValidationPipe({ whitelist: true })); app.useGlobalPipes(new ValidationPipe({ whitelist: true }));

View File

@ -21,7 +21,7 @@ export class UserSevice {
private emailService: EmailService, private emailService: EmailService,
private fileService: FileService, private fileService: FileService,
private configService: ConfigService, private configService: ConfigService,
) { } ) {}
async list() { async list() {
return await this.prisma.user.findMany(); return await this.prisma.user.findMany();
@ -96,27 +96,38 @@ export class UserSevice {
return await this.prisma.user.delete({ where: { id } }); return await this.prisma.user.delete({ where: { id } });
} }
async findOrCreateFromLDAP(providedCredentials: AuthSignInDTO, ldapEntry: Entry) { async findOrCreateFromLDAP(
providedCredentials: AuthSignInDTO,
ldapEntry: Entry,
) {
const fieldNameMemberOf = this.configService.get("ldap.fieldNameMemberOf"); const fieldNameMemberOf = this.configService.get("ldap.fieldNameMemberOf");
const fieldNameEmail = this.configService.get("ldap.fieldNameEmail"); const fieldNameEmail = this.configService.get("ldap.fieldNameEmail");
let isAdmin = false; let isAdmin = false;
if (fieldNameMemberOf in ldapEntry) { if (fieldNameMemberOf in ldapEntry) {
const adminGroup = this.configService.get("ldap.adminGroups"); const adminGroup = this.configService.get("ldap.adminGroups");
const entryGroups = Array.isArray(ldapEntry[fieldNameMemberOf]) ? ldapEntry[fieldNameMemberOf] : [ldapEntry[fieldNameMemberOf]]; const entryGroups = Array.isArray(ldapEntry[fieldNameMemberOf])
? ldapEntry[fieldNameMemberOf]
: [ldapEntry[fieldNameMemberOf]];
isAdmin = entryGroups.includes(adminGroup) ?? false; isAdmin = entryGroups.includes(adminGroup) ?? false;
} else { } else {
this.logger.warn(`Trying to create/update a ldap user but the member field ${fieldNameMemberOf} is not present.`); this.logger.warn(
`Trying to create/update a ldap user but the member field ${fieldNameMemberOf} is not present.`,
);
} }
let userEmail: string | null = null; let userEmail: string | null = null;
if (fieldNameEmail in ldapEntry) { if (fieldNameEmail in ldapEntry) {
const value = Array.isArray(ldapEntry[fieldNameEmail]) ? ldapEntry[fieldNameEmail][0] : ldapEntry[fieldNameEmail]; const value = Array.isArray(ldapEntry[fieldNameEmail])
? ldapEntry[fieldNameEmail][0]
: ldapEntry[fieldNameEmail];
if (value) { if (value) {
userEmail = value.toString(); userEmail = value.toString();
} }
} else { } else {
this.logger.warn(`Trying to create/update a ldap user but the email field ${fieldNameEmail} is not present.`); this.logger.warn(
`Trying to create/update a ldap user but the email field ${fieldNameEmail} is not present.`,
);
} }
if (providedCredentials.email) { if (providedCredentials.email) {
@ -149,34 +160,46 @@ export class UserSevice {
if (user.username === placeholderUsername) { if (user.username === placeholderUsername) {
/* Give the user a human readable name if the user has been created with a placeholder username */ /* Give the user a human readable name if the user has been created with a placeholder username */
await this.prisma.user.update({ await this.prisma.user
.update({
where: { where: {
id: user.id, id: user.id,
}, },
data: { data: {
username: `user_${user.id}` username: `user_${user.id}`,
} },
}).then(newUser => { })
.then((newUser) => {
user.username = newUser.username; user.username = newUser.username;
}).catch(error => { })
this.logger.warn(`Failed to update users ${user.id} placeholder username: ${inspect(error)}`); .catch((error) => {
this.logger.warn(
`Failed to update users ${user.id} placeholder username: ${inspect(error)}`,
);
}); });
} }
if (userEmail && userEmail !== user.email) { if (userEmail && userEmail !== user.email) {
/* Sync users email if it has changed */ /* Sync users email if it has changed */
await this.prisma.user.update({ await this.prisma.user
.update({
where: { where: {
id: user.id, id: user.id,
}, },
data: { data: {
email: userEmail email: userEmail,
} },
}).then(newUser => { })
this.logger.log(`Updated users ${user.id} email from ldap from ${user.email} to ${userEmail}.`); .then((newUser) => {
this.logger.log(
`Updated users ${user.id} email from ldap from ${user.email} to ${userEmail}.`,
);
user.email = newUser.email; user.email = newUser.email;
}).catch(error => { })
this.logger.error(`Failed to update users ${user.id} email to ${userEmail}: ${inspect(error)}`); .catch((error) => {
this.logger.error(
`Failed to update users ${user.id} email to ${userEmail}: ${inspect(error)}`,
);
}); });
} }