Skip to content

Commit

Permalink
Merge pull request #2 from ViLiFYKiNG/SONAR_FIXES
Browse files Browse the repository at this point in the history
FIX SONAR ISSUES
  • Loading branch information
ViLiFYKiNG committed Jul 7, 2024
2 parents fd293fe + 6132258 commit cebd4ac
Show file tree
Hide file tree
Showing 13 changed files with 29 additions and 59 deletions.
16 changes: 16 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,19 @@ npm run migration:run -- -d <path/to/datasource>

//FOR MIGRATION CREATE
typeorm migration:generate -d <path/to/datasource> path/to/migrations/<migration-name>

// READ PRIVSTE KEY FORM FILE
let privateKey: Buffer;

try {
privateKey = fs.readFileSync(
path.join(__dirname, '../../certs/private.pem'),
);
} catch (err) {
const error = createHttpError(
500,
'Fail to read private key. Make sure the private.pem file is present in the certs folder.',
);

throw error;
}
2 changes: 1 addition & 1 deletion src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { config } from 'dotenv';
import path from 'path';

config({
path: path.join(__dirname, `../../.env.${process.env.NODE_ENV || 'dev'}`),
path: path.join(__dirname, `../../.env.${process.env.NODE_ENV ?? 'dev'}`),
});

const {
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/AuthController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export class AuthController {
this.logger.info('User has been registered:', user);

const payLoad: JwtPayload = {
sub: user.id.toString() || '1',
role: user.role || ROLES.CUSTOMER,
sub: user.id.toString() ?? '1',
role: user.role ?? ROLES.CUSTOMER,
};

const accessToken = this.tokenService.generateAccessToken(payLoad);
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { AuthCookie } from '../types';

export default expressjwt({
secret: jwksClient.expressJwtSecret({
jwksUri: Config.JWKS_URI || '',
jwksUri: Config.JWKS_URI ?? '',
cache: true,
rateLimit: true,
}) as GetVerificationKey,
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/parseRefreshToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Request } from 'express';
import { AuthCookie } from '../types';

export default expressjwt({
secret: Config.REFRESH_TOKEN_SECRET || '',
secret: Config.REFRESH_TOKEN_SECRET ?? 'HOLA_SECRET',
algorithms: ['HS256'],
getToken(req: Request) {
const { refreshToken } = req.cookies as AuthCookie;
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/validateRefreshToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { RefreshToken } from '../entity/RefreshToken';
import logger from '../config/logger';

export default expressjwt({
secret: Config.REFRESH_TOKEN_SECRET || '',
secret: Config.REFRESH_TOKEN_SECRET ?? 'HOLA_SECRET',
algorithms: ['HS256'],
getToken(req: Request) {
const { refreshToken } = req.cookies as AuthCookie;
Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const startServer = async () => {
try {
await AppDataSource.initialize();
logger.info('Database connection established successfully.');
await app.listen(Config.PORT, () => {
app.listen(Config.PORT, () => {
logger.info(`Server is running on port ${Config.PORT}.`);
});
} catch (error) {
Expand Down
18 changes: 0 additions & 18 deletions src/services/TenantService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,6 @@ export class TenantService {
return await this.tenantRepository.update(id, tenantData);
}

// async getAll(validatedQuery: TenantQueryParams) {
// const queryBuilder = this.tenantRepository.createQueryBuilder('tenant');

// if (validatedQuery.q) {
// const searchTerm = `%${validatedQuery.q}%`;
// queryBuilder.where("CONCAT(tenant.name, ' ', tenant.address) ILike :q", {
// q: searchTerm,
// });
// }

// const result = await queryBuilder
// .skip((validatedQuery.currentPage - 1) * validatedQuery.perPage)
// .take(validatedQuery.perPage)
// .orderBy('tenant.id', 'DESC')
// .getManyAndCount();
// return result;
// }

async getById(tenantId: number) {
return await this.tenantRepository.findOne({ where: { id: tenantId } });
}
Expand Down
4 changes: 2 additions & 2 deletions src/services/TokenService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class TokenService {
throw createHttpError(500, 'SECRET_KEY is not set..!');
}

const privateKey = Config.PRIVATE_KEY || 'PRIVATE_KEY';
const privateKey = Config.PRIVATE_KEY ?? 'PRIVATE_KEY';

const accessToken = sign(payLoad, privateKey, {
algorithm: 'RS256',
Expand All @@ -24,7 +24,7 @@ export class TokenService {
}

generateRefreshToken(payLoad: JwtPayload) {
const secret = Config.REFRESH_TOKEN_SECRET || 'secret';
const secret = Config.REFRESH_TOKEN_SECRET ?? 'HOLA_SECRET';
const refreshToken = sign(payLoad, secret, {
algorithm: 'HS256',
expiresIn: '1y',
Expand Down
29 changes: 0 additions & 29 deletions src/services/UserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,35 +91,6 @@ export class UserService {
}
}

// async getAll(validatedQuery: UserQueryParams) {
// const queryBuilder = this.userRepository.createQueryBuilder('user');

// if (validatedQuery.q) {
// const searchTerm = `%${validatedQuery.q}%`;
// queryBuilder.where(
// new Brackets((qb) => {
// qb.where("CONCAT(user.firstName, ' ', user.lastName) ILike :q", {
// q: searchTerm,
// }).orWhere('user.email ILike :q', { q: searchTerm });
// }),
// );
// }

// if (validatedQuery.role) {
// queryBuilder.andWhere('user.role = :role', {
// role: validatedQuery.role,
// });
// }

// const result = await queryBuilder
// .leftJoinAndSelect('user.tenant', 'tenant')
// .skip((validatedQuery.currentPage - 1) * validatedQuery.perPage)
// .take(validatedQuery.perPage)
// .orderBy('user.id', 'DESC')
// .getManyAndCount();
// return result;
// }

async deleteById(userId: number) {
return await this.userRepository.delete(userId);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/users/login.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe('POST /auth/login', () => {
let accessToken: string | null = null;
let refreshToken: string | null = null;
const cookies =
(response.headers as unknown as Headers)['set-cookie'] || [];
(response.headers as unknown as Headers)['set-cookie'] ?? [];
cookies.forEach((cookie) => {
if (cookie.startsWith('accessToken=')) {
accessToken = cookie.split(';')[0].split('=')[1];
Expand Down
2 changes: 1 addition & 1 deletion tests/users/register.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ describe('POST /auth/register', () => {
}

const cookies =
(response.headers as unknown as Headers)['set-cookie'] || [];
(response.headers as unknown as Headers)['set-cookie'] ?? [];

cookies.forEach((cookie) => {
if (cookie.startsWith('accessToken=')) {
Expand Down
3 changes: 2 additions & 1 deletion tests/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export const isJWT = (token: string | null): boolean => {
parts.forEach((part) => {
Buffer.from(part, 'base64').toString('utf-8');
});
} catch (e) {
} catch (error) {
console.log(`Error {}`, error);
return false;
}

Expand Down

0 comments on commit cebd4ac

Please sign in to comment.