Skip to content

Commit

Permalink
Merge pull request #3 from mibrito1/users
Browse files Browse the repository at this point in the history
parte de usuario termanada ( login e signup)
  • Loading branch information
mibrito1 authored Sep 27, 2023
2 parents aec4a4f + ac25e3d commit 0785fa6
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 4 deletions.
30 changes: 29 additions & 1 deletion src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { IdGenerator } from "../services/IdGenerator";
import { HashManager } from "../services/HashManager";
import { Users, userRole } from "../models/Users";
import { TokenManager, TokenPayload } from "../services/TokenManager";
import { LoginInputDTO, LoginOutputDTO } from "../dtos/users/login.dto";
import { NotfoundError } from "../erros/NotFoundError";
import { BadError } from "../erros/BadError";

export class UserBusiness { // aqui vai tratar as regras do negocio, as regras do projeto
constructor(private idGenerator: IdGenerator,
Expand All @@ -23,7 +26,7 @@ export class UserBusiness { // aqui vai tratar as regras do negocio, as regras
if (
userExist
) {
throw new Error(
throw new BadError(
"usuario ja existe"
)
}
Expand All @@ -45,5 +48,30 @@ export class UserBusiness { // aqui vai tratar as regras do negocio, as regras
return output
}

public login = async (input: LoginInputDTO): Promise<LoginOutputDTO> => {
const {
email, password
} = input
const emailExiste = await this.userDataBase.getUserByEmail(email)
if (
!emailExiste
) {
throw new NotfoundError()
}
const passwordValido = await this.hashManager.compare(password, emailExiste.password)
if (
!passwordValido
) {
throw new BadError("Senha invalida!")
}
const tokenPayload: TokenPayload = {
id: emailExiste.id,
name: emailExiste.name,
role: emailExiste.role
}
const token = this.tokenManager.createToken(tokenPayload)
return { message: "Login feito com sucesso!", token: token }
}

}

25 changes: 25 additions & 0 deletions src/controller/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { UserBusiness } from "../business/UserBusiness";
import { SignupSchema } from "../dtos/users/signup.dto";
import { ZodError } from "zod";
import { BaseError } from "../erros/BaseError";
import { LoginSchema } from "../dtos/users/login.dto";


export class UserController {
Expand Down Expand Up @@ -34,4 +35,28 @@ export class UserController {

}
}
public login = async (req: Request, res: Response) => {
try {
const input = LoginSchema.parse({
email: req.body.email,
password: req.body.password
})
const output = await this.userBusiness.login(input)
res.status(200).send(output)

} catch (error) {
console.log(error)
if (error instanceof ZodError) {
res.status(400).send(error.issues)
} else if (error instanceof BaseError) {
res.status(error.statusCode).send(error.message)
} else {
res.status(500).send("Erro inesperado")
}

}
}



}
2 changes: 1 addition & 1 deletion src/dataBase/BaseDataBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export abstract class BaseDatabase {
protected static connection = knex({
client: "sqlite3",
connection: {
filename: "./labook.db"
filename: "./src/dataBase/labook.db"
},
useNullAsDefault: true,
pool: {
Expand Down
14 changes: 13 additions & 1 deletion src/dataBase/labook.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,16 @@ CREATE TABLE

DROP TABLE users;

SELECT * FROM users;
SELECT * FROM users;

CREATE TABLE
posts(
id TEXT UNIQUE PRIMARY KEY NOT NULL,
creator_id TEXT NOT NULL,
content TEXT NOT NULL,
likes INTEGER NOT NULL,
dislikes INTEGER NOT NULL,
created_at TEXT DEFAULT (DATE('now', 'localtime')),
updated_at TEXT NOT NULL,
Foreign Key (creator_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE
);
2 changes: 1 addition & 1 deletion src/dtos/users/login.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import z from "zod"

export interface LoginInputDTO {
email: string,
password: String // aqui tipei a entrada de dados
password: string // aqui tipei a entrada de dados
}

export interface LoginOutputDTO {
Expand Down
10 changes: 10 additions & 0 deletions src/erros/BadError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { BaseError } from "./BaseError";

export class BadError extends BaseError {
constructor(
message: string = "Requisição invalida!"
) {
super(400, message)
}

}
8 changes: 8 additions & 0 deletions src/erros/NotFoundError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { BaseError } from "./BaseError";

export class NotfoundError extends BaseError {
constructor(message: string = "recurso não encontrado") {
super(404, message)

}
}
2 changes: 2 additions & 0 deletions src/router/userRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ const userController = new UserController(
userRouter.get("/", userController.oiMirian)

userRouter.post('/signup', userController.signup)

userRouter.post('/login', userController.login)

0 comments on commit 0785fa6

Please sign in to comment.