Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/correct remenber in session #81

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ module.exports = {
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'no-console': 'warn',
},
};
2 changes: 2 additions & 0 deletions prisma/migrations/20240904231016_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "tasks" ALTER COLUMN "quantityPerWeek" DROP NOT NULL;
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ model Task {
date DateTime
description String
checked Boolean @default(false)
quantityPerWeek Int
quantityPerWeek Int?
finallyDate DateTime?
category TaskCategories
type TaskType
Expand Down
2 changes: 1 addition & 1 deletion src/config/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.int

export const corsOptionsConfig: CorsOptions = {
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization'],
};
2 changes: 1 addition & 1 deletion src/config/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const responses: iValidationResponses = {
'Deve conter no mínimo 6 caracteres com uma letra maiúscula, uma letra minúscula, um número e um símbolo',
fullname: 'Deve conter apenas letras e espaço em branco entre palavras',
datePattern: 'Use o padrão ISO 8601 (YYYY-MM-DD hh:mm)',
dateRange: 'A data não pode ser posterior à data atual',
dateRange: 'A data não pode ser anterior à data atual',
monthPattern: 'Use o número relativo ao mês desejado. ex.: (1,2..12)',
yearPattern: 'O ano é composto por 4 números. ex.: 2021',
};
6 changes: 3 additions & 3 deletions src/guards/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import {
BadRequestException,
CanActivate,
ExecutionContext,
Injectable,
BadRequestException,
ForbiddenException,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { SessionService } from 'src/modules/Session/session.service';
import { RoleLevel, Permissions } from './roles.config';
import { CREDENTIALS_KEY } from 'src/utils/constants';
import { Permissions, RoleLevel } from './roles.config';

@Injectable()
export class RolesGuard implements CanActivate {
Expand Down
22 changes: 11 additions & 11 deletions src/modules/Account/account.controller.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
import { Request } from 'express';
import {
Controller,
Body,
Controller,
HttpCode,
Post,
Put,
UseGuards,
HttpCode,
Req,
UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { ThrottlerGuard } from '@nestjs/throttler';
import { Request } from 'express';
import { Permissions, RequirePermissions, RolesGuard } from 'src/guards';
import { CREDENTIALS_KEY } from 'src/utils/constants';
import { SessionService } from '../Session/session.service';
import {
CreateAccountControllerInput,
AccessAccountControllerInput,
RefreshSessionControllerInput,
ResetPasswordInput,
ChangePasswordInput,
CreateAccountControllerInput,
DisconnectAccountControllerInput,
RefreshSessionControllerInput,
ResetPasswordInput,
ValidateTokenInput,
} from './account.dtos';
import { AccountService } from './account.service';
import { SessionService } from '../Session/session.service';
import { Permissions, RequirePermissions, RolesGuard } from 'src/guards';
import { CREDENTIALS_KEY } from 'src/utils/constants';

@UseGuards(ThrottlerGuard, RolesGuard)
@Controller('auth')
Expand Down
8 changes: 4 additions & 4 deletions src/modules/Account/account.dtos.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { ApiProperty, PickType } from '@nestjs/swagger';
import {
IsNotEmpty,
Matches,
IsEmail,
IsStrongPassword,
IsBoolean,
IsEmail,
IsHexadecimal,
IsNotEmpty,
IsString,
IsStrongPassword,
Matches,
} from 'class-validator';
import { responses } from 'src/config/responses';

Expand Down
18 changes: 2 additions & 16 deletions src/modules/Session/session.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,11 @@ export class SessionRepository {
});
}

async createSession({
sessionToken,
refreshToken,
sessionExpiresIn,
refreshExpiresIn,
accountId,
permissions,
name,
}: CreateSessionRepositoryInput): Promise<boolean> {
async createSession(data: CreateSessionRepositoryInput): Promise<boolean> {
return await this.prisma.session
.create({
data: {
sessionToken,
refreshToken,
sessionExpiresIn,
refreshExpiresIn,
accountId,
permissions,
name,
...data,
Copy link

@erickmarx erickmarx Sep 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aqui você pode manter somente .create({ data }) que é equivalente a .create({ data: data })

},
})
.then(() => {
Expand Down
18 changes: 9 additions & 9 deletions src/modules/Session/session.service.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { randomBytes } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import { SessionRepository } from './session.repository';
import { randomBytes } from 'node:crypto';
import { AuthorizationError, InternalServerError } from 'src/config/exceptions';
import {
expirationWhenRememberIsOff,
expirationWhenRememberIsOnn,
} from 'src/utils/constants';
import { hashDataAsync } from 'src/utils/hashes';
import {
CreateSessionServiceInput,
CreateSessionServiceOutput,
ExcludeSessionsServiceInput,
FindSessionServiceOutput,
RefreshTokenServiceOutput,
} from './session.dtos';
import { hashDataAsync } from 'src/utils/hashes';
import { AuthorizationError, InternalServerError } from 'src/config/exceptions';
import {
expirationWhenRememberIsOff,
expirationWhenRememberIsOnn,
} from 'src/utils/constants';
import { SessionRepository } from './session.repository';

@Injectable()
export class SessionService {
Expand Down Expand Up @@ -46,7 +46,7 @@ export class SessionService {
const sessionTokenExpiresIn = remember
? expirationWhenRememberIsOnn
: expirationWhenRememberIsOff;
const refreshTokenExpiresIn = sessionTokenExpiresIn * (remember ? 4 : 1.5);
const refreshTokenExpiresIn = sessionTokenExpiresIn * (remember ? 4 : 2);
const now = new Date().getTime();

return {
Expand Down
3 changes: 2 additions & 1 deletion src/modules/Task/task.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Permissions, RequirePermissions, RolesGuard } from 'src/guards';
import { AccountId } from 'src/utils/decorators/accountid.decorator';
import {
Expand All @@ -24,6 +24,7 @@ import { TaskService } from './task.service';

@ApiTags('Tarefas')
@UseGuards(RolesGuard)
@ApiBearerAuth()
@Controller('/tasks')
export class TaskController {
constructor(private readonly taskService: TaskService) {}
Expand Down
3 changes: 2 additions & 1 deletion src/modules/Task/task.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ export class CreateOneDto {
example: '2024-04-01 04:20',
description: <string>responses.datePattern,
})
@IsOptional()
@IsNotEmpty({ message: responses.notEmpty })
@IsString({ message: responses.string })
@Matches(DateRegex, { message: responses.datePattern })
@IsDateString({ strict: true }, { message: responses.datePattern })
@IsEarlierThanCurrentDate('date', { message: responses.dateRange })
@IsEarlierThanCurrentDate('finallyDate', { message: responses.dateRange })
finallyDate?: string;

@ApiProperty({
Expand Down
1 change: 0 additions & 1 deletion src/modules/Task/task.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,6 @@ export class TaskRepository {
},
})
.catch((error: unknown) => {
console.log(error);
if (error instanceof Prisma.PrismaClientKnownRequestError) {
throw new InternalServerError({
message: 'Erro desconhecido :: '.concat(error.code),
Expand Down
2 changes: 1 addition & 1 deletion src/utils/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export const CREDENTIALS_KEY = 'account.credentials';
export const hexadecimalRegex = /^[a-f0-9]+$/;
export const expirationWhenRememberIsOff =
process.env.NODE_ENV === 'production' ? 36e5 : 3e5;
process.env.NODE_ENV === 'production' ? 36e5 : 6e4; // 3e5;
export const expirationWhenRememberIsOnn = expirationWhenRememberIsOff * 24 * 7;