Skip to content
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
2,502 changes: 2,502 additions & 0 deletions semana18/aula53/aula53/package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions semana19/semana19-cookenu/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
package-lock.json
build
.env
34 changes: 34 additions & 0 deletions semana19/semana19-cookenu/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "semana19-cookenu",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "ts-node-dev ./src/index.ts",
"start": "tsc && node ./build/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/knex": "^0.16.1",
"@types/uuid": "^8.3.3",
"ts-node-dev": "^1.1.8",
"typescript": "^4.5.4"
},
"dependencies": {
"@types/jsonwebtoken": "^8.5.6",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"jsonwebtoken": "^8.5.1",
"knex": "^0.95.14",
"mysql": "^2.18.1",
"uuid": "^8.3.2"
}
}
19 changes: 19 additions & 0 deletions semana19/semana19-cookenu/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import express, { Express } from "express";
import cors from "cors";
import { AddressInfo } from "net";
import dotenv from "dotenv";

dotenv.config();

export const app: Express = express();
app.use(express.json());
app.use(cors());

const server = app.listen(process.env.PORT || 3003, () => {
if (server) {
const address = server.address() as AddressInfo;
console.log(`Server is running in http://localhost: ${address.port}`);
} else {
console.error(`Failure upon starting server.`);
}
});
15 changes: 15 additions & 0 deletions semana19/semana19-cookenu/src/data/BaseDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import knex from "knex";

export class BaseDatabase {
protected static connection = knex({
client: "mysql",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_SCHEMA,
port: 3306,
multipleStatements: true,
},
});
}
27 changes: 27 additions & 0 deletions semana19/semana19-cookenu/src/data/RecipeDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { BaseDatabase } from "./BaseDataBase";
import { Recipe } from "../types/types";

export class RecipeDataBase extends BaseDatabase {
async createRecipe(recipe: Recipe) {
try {
await BaseDatabase.connection("cookenu_recipes").insert({
id: recipe.getId(),
title: recipe.getTitle(),
description: recipe.getDescription(),
date: recipe.getDate(),
});
} catch (error) {
throw new Error((error as any).sqlMessage || (error as any).message);
}
}
async findRecipeById(id: string): Promise<Recipe> {
try {
const recipeId = await BaseDatabase.connection("cookenu_recipes")
.select("*")
.where({ id });
return recipeId[0] && Recipe.toRecipeModel(recipeId[0]);
} catch (error) {
throw new Error((error as any).sqlMessage || (error as any).message);
}
}
}
51 changes: 51 additions & 0 deletions semana19/semana19-cookenu/src/data/UserDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { BaseDatabase } from "./BaseDataBase";
import { User } from "../types/types";
import { AuthenticationData } from "../services/Authenticator";

export class UserDataBase extends BaseDatabase {
async createUser(user: User) {
try {
await BaseDatabase.connection("cookenu_users").insert({
id: user.getId(),
name: user.getName(),
email: user.getEmail(),
password: user.getPassword(),
});
} catch (error) {
throw new Error((error as any).sqlMessage || (error as any).message);
}
}

async findUserByEmail(email: string): Promise<User> {
try {
const user = await BaseDatabase.connection("cookenu_users")
.select("*")
.where({ email });
return user[0] && User.toUserModel(user[0]);
} catch (error) {
throw new Error((error as any).sqlMessage || (error as any).message);
}
}

async findUserById(id: string): Promise<User> {
try {
const userId = await BaseDatabase.connection("cookenu_users")
.select("*")
.where({ id });
return userId[0] && User.toUserModel(userId[0]);
} catch (error) {
throw new Error((error as any).sqlMessage || (error as any).message);
}
}

public async findUserProfile(id1: AuthenticationData): Promise<User[]> {
try {
const result = await BaseDatabase.connection("cookenu_users")
.select("id", "name", "email")
.where({ id: id1.id });
return result.map((user: any) => User.toUserModel(user));
} catch (error: any) {
throw new Error(error.sqlMessage || error.message);
}
}
}
38 changes: 38 additions & 0 deletions semana19/semana19-cookenu/src/endpoints/createRecipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Request, Response } from "express";
import { Authenticator } from "../services/Authenticator";
import { Recipe } from "../types/types";
import { IdGenerator } from "../services/IdGenerator";
import { RecipeDataBase } from "../data/RecipeDataBase";

export async function createRecipe(req: Request, res: Response) {
try {
const { title, description, date } = req.body;

if (!title || !description || !date) {
res
.status(422)
.send("Informe corretamente as informações de 'title' e 'description'");
}
const token = req.headers.authorization;

if (!token) {
res
.status(422)
.send("Esse input exige uma autorização a ser passada nos headers");
}

const authenticator = new Authenticator();
const tokenData = authenticator;

const idGenerator = new IdGenerator();
const id = idGenerator.generate();

const newRecipe = new Recipe(id, title, description, date);
const recipeDataBase = new RecipeDataBase();
await recipeDataBase.createRecipe(newRecipe);

res.status(200).send({ "Receita criada com sucesso": newRecipe });
} catch (error) {
res.status(400).send((error as Error).message);
}
}
29 changes: 29 additions & 0 deletions semana19/semana19-cookenu/src/endpoints/getOwnUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Request, Response } from "express";
import { Authenticator } from "../services/Authenticator";
import { UserDataBase } from "../data/UserDataBase";
import { User } from "../types/types";

export async function getOwnUser(req: Request, res: Response) {
try {
const token = req.headers.authorization as any;

if (!token) {
res.statusCode = 401;
throw new Error("Token inválido");
}

const authenticator = new Authenticator();
const resultToken = authenticator.getTokenData(token);

const userDataBase = new UserDataBase();
const [user]: User[] = await userDataBase.findUserProfile(resultToken);

res.status(200).send({
id: user.getId(),
name: user.getName(),
email: user.getEmail(),
});
} catch (error) {
res.status(400).send((error as any).message);
}
}
26 changes: 26 additions & 0 deletions semana19/semana19-cookenu/src/endpoints/getRecipeById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Request, Response } from "express";
import { Authenticator } from "../services/Authenticator";
import { RecipeDataBase } from "../data/RecipeDataBase";

export async function getRecipeById(req: Request, res: Response) {
try {
const { id } = req.params;

const token = req.headers.authorization;

if (!token) {
res
.status(422)
.send("Esse input exige uma autorização a ser passada nos headers");
}
const authenticator = new Authenticator();
const tokenData = authenticator.getTokenData(token as string);

const recipeDataBase = new RecipeDataBase();
const recipes = await recipeDataBase.findRecipeById(id);

res.status(200).send(recipes);
} catch (error) {
res.status(400).send((error as any).message);
}
}
27 changes: 27 additions & 0 deletions semana19/semana19-cookenu/src/endpoints/getUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Request, Response } from "express";
import { Authenticator } from "../services/Authenticator";
import { UserDataBase } from "../data/UserDataBase";

export async function getUser(req: Request, res: Response) {
try {
const { id } = req.params;

const token = req.headers.authorization;

if (!token) {
res
.status(422)
.send("Esse input exige uma autorização a ser passada nos headers");
}

const authenticator = new Authenticator();
const tokenData = authenticator.getTokenData(token as string);

const userDataBase = new UserDataBase();
const users = await userDataBase.findUserById(id);

res.status(200).send(users);
} catch (error) {
res.status(400).send((error as any).message);
}
}
43 changes: 43 additions & 0 deletions semana19/semana19-cookenu/src/endpoints/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Request, Response } from "express";
import { UserDataBase } from "../data/UserDataBase";
import { HashManager } from "../services/HashManager";
import { Authenticator } from "../services/Authenticator";

export async function login(req: Request, res: Response) {
try {
const { email, password } = req.body;

if (!email! || !password) {
res
.status(422)
.send("Informe corretamente as informações de 'email' e 'password'");
}
if (req.body.password.length < 6) {
res.status(400).send("Senha inválida!");
}

const userDataBase = new UserDataBase();
const user = await userDataBase.findUserByEmail(email);

if (!user as any) {
res.status(404).send("Esse email não está cadastrado!");
}

const hashManager = new HashManager();
const passwordIsCorrect = await hashManager.compare(
password,
user.getPassword()
);

if (!passwordIsCorrect) {
res.status(401).send("email ou senha incorretos");
}

const authenticator = new Authenticator();
const token = authenticator.generate({ id: user.getId() });

res.status(200).send({ message: "Usuário logado com sucesso", token });
} catch (error) {
res.status(400).send((error as Error).message);
}
}
46 changes: 46 additions & 0 deletions semana19/semana19-cookenu/src/endpoints/signup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Request, Response } from "express";
import { IdGenerator } from "../services/IdGenerator";
import { UserDataBase } from "../data/UserDataBase";
import { HashManager } from "../services/HashManager";
import { User } from "../types/types";
import { Authenticator } from "../services/Authenticator";

export async function signUp(req: Request, res: Response) {
try {
const { name, email, password } = req.body;

if (!name || !email! || !password) {
res
.status(422)
.send(
"Informe corretamente as informações de 'name', 'email' e 'password'"
);
}
if (req.body.password.length < 6) {
res.status(400).send("Senha inválida!");
}

const userDataBase = new UserDataBase();
const user = await userDataBase.findUserByEmail(email);

if (user as any) {
res.status(409).send("Esse email já está cadastrado!");
}

const idGenerator = new IdGenerator();
const id = idGenerator.generate();

const hashManager = new HashManager();
const hashPassword = await hashManager.hash(password);

const newUser = new User(id, name, email, hashPassword);
await userDataBase.createUser(newUser);

const authenticator = new Authenticator();
const token = authenticator.generate({ id });

res.status(200).send({ message: "Usuário criado com sucesso", token });
} catch (error) {
res.status(400).send((error as Error).message);
}
}
14 changes: 14 additions & 0 deletions semana19/semana19-cookenu/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { app } from "./app";
import { signUp } from "./endpoints/signup";
import { login } from "./endpoints/login";
import { getUser } from "./endpoints/getUser";
import { createRecipe } from "./endpoints/createRecipe";
import { getRecipeById } from "./endpoints/getRecipeById";
import { getOwnUser } from "./endpoints/getOwnUser";

app.get("/user/profile", getOwnUser);
app.get("/user/profile/:id", getUser);
app.post("/user/signup", signUp);
app.post("/user/login", login);
app.get("/recipe/:id", getRecipeById);
app.post("/recipe", createRecipe);
Loading