-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
167 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |