Skip to content

Commit

Permalink
feat: adding providers to project
Browse files Browse the repository at this point in the history
  • Loading branch information
lucsimao committed Oct 4, 2021
1 parent 6678071 commit 70948c5
Show file tree
Hide file tree
Showing 3 changed files with 167 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/providers/SignInProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import AuthService from '../services/AuthService';
import EncryptService from '../services/EncryptService';
import { IHttpRequest } from '../interfaces/IHttpRequest';
import { IHttpResponse } from '../interfaces/IHttpResponse';
import { IUser } from '../models/user/IUser';
import Logger from '../util/logger';
import { UnauthorizedError } from '../util/errors/UnauthorizedError';
import UserRepository from '../repositories/users';

export default class UserService {
public static async authenticateUser(
httpRequest: IHttpRequest
): Promise<IHttpResponse> {
Logger.info({ msg: 'Authenticating user' });
const user = await this.authenticate(httpRequest.body as IUser);
return {
statusCode: 200 || httpRequest,
body: user,
};
}

private static async authenticate(user: IUser) {
const email = user.email;

const result = await UserRepository.findOne({ email });

if (!result) {
Logger.error({ msg: `${user.email} not found in database` });
throw new UnauthorizedError('Usuário e/ou senha inválidos');
}

const passwordsMatch = await EncryptService.compareHash(
user.senha,
result.senha
);

if (!passwordsMatch) {
Logger.error({
msg: `Authentication error of user with email: ${result.email}`,
});
throw new UnauthorizedError('Usuário e/ou senha inválidos');
}

const token = AuthService.generateUserToken(result);

const dataAtual = new Date().toLocaleString();

await UserRepository.update(
{ email: result.email },
{
token,
data_atualizacao: dataAtual,
ultimo_login: dataAtual,
}
);

return {
...result,
token,
data_atualizacao: dataAtual,
ultimo_login: dataAtual,
};
}
}
39 changes: 39 additions & 0 deletions src/providers/SignUpProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import AuthService from '../services/AuthService';
import { DuplicationError } from '../util/errors/DuplicationError';
import EncryptService from '../services/EncryptService';
import { IHttpResponse } from '../interfaces/IHttpResponse';
import { IUser } from '../models/user/IUser';
import UserSchema from '../schemas/UserSchema';
import httpStatus from 'http-status-codes';
import userRepository from '../repositories/users';
import validator from '../validators';
export class SignUpProvider {
public static async generateUser(user: IUser): Promise<IHttpResponse> {
const validatedUserData = await validator.validateSchema<IUser>(
UserSchema,
user,
'error validating schema'
);

const token = AuthService.generateUserToken(validatedUserData);

const senha = await EncryptService.generateHash(user.senha);
user.senha = senha;

const userInDatabase = await userRepository.findOne({ email: user.email });

if (userInDatabase) {
throw new DuplicationError('Email');
}

const result = await userRepository.create({
...user,
token,
});

return {
body: result,
statusCode: httpStatus.CREATED,
};
}
}
64 changes: 64 additions & 0 deletions src/providers/UserProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { IHttpRequest } from '../interfaces/IHttpRequest';
import { IHttpResponse } from '../interfaces/IHttpResponse';
import { IUser } from '../models/user/IUser';
import Logger from '../util/logger';
import { UnauthorizedError } from '../util/errors/UnauthorizedError';
import UserRepository from '../repositories/users';
import { differenceInMinutes } from 'date-fns';
import httpStatus from 'http-status-codes';
export class UserProvider {
public static async getUser(
httpRequest: IHttpRequest
): Promise<IHttpResponse> {
const id = httpRequest.params?.id;
const token = httpRequest.headers?.authorization;

if (!id || !token) {
Logger.error({ msg: 'id do usuário ou token não fornecidos' });
throw new UnauthorizedError('Sessão inválida');
}

const [, tokenBody] = token.split(' ');

const user = await this.findUser(id, tokenBody);
return {
statusCode: httpStatus.OK,
body: user,
};
}

private static async findUser(userId: string, token: string): Promise<IUser> {
const user = await UserRepository.findOneByIdAndToken(userId, token);
if (!user) {
Logger.error({
msg: 'Usuário não encontrado com o id e token informados',
userId,
token,
});
throw new UnauthorizedError('Não Autorizado');
}

if (
this.checkIfTheDateHasBeenPassedInMinutes(user.ultimo_login as string)
) {
Logger.error({ msg: 'Sessão inválida pois o token já está expirado' });
throw new UnauthorizedError('Sessão inválida');
}

return user;
}

private static checkIfTheDateHasBeenPassedInMinutes(
referenceDate: string,
limit = 30
) {
const actualDate = new Date().toLocaleTimeString();

const diffInMinutes = differenceInMinutes(
new Date(actualDate),
new Date(referenceDate)
);

return diffInMinutes >= limit;
}
}

0 comments on commit 70948c5

Please sign in to comment.