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
4 changes: 4 additions & 0 deletions modulo7/cookenu/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
package-lock.json
build
.env
35 changes: 35 additions & 0 deletions modulo7/cookenu/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "cookenu",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "ts-node-dev ./src/index.ts",
"start": "node ./build/index.js",
"build": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/jsonwebtoken": "^8.5.9",
"@types/knex": "^0.16.1",
"@types/mysql": "^2.15.21",
"@types/node": "^18.7.13",
"@types/uuid": "^8.3.4",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"jsonwebtoken": "^8.5.1",
"knex": "^2.2.0",
"mysql": "^2.18.1",
"ts-node-dev": "^2.0.0",
"typescript": "^4.7.4",
"uuid": "^8.3.2"
}
}
58 changes: 58 additions & 0 deletions modulo7/cookenu/request.rest
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//criar usuarios
POST http://localhost:3003/user/signup
Content-Type: application/json

{
"name": "Alice",
"email": "alice@lbn.com",
"password": "123456"
}

###
POST http://localhost:3003/user/login
Content-Type: application/json

{
"email": "alice@lbn.com",
"password": "123456"
}


###
// pegar usuarios
GET http://localhost:3003/user/profile



###
//Pegar perfil de outro usuário
GET http://localhost:3003/user/:id

###
//alterar dados do usuario
PUT http://localhost:3003/user/edit/:id
Content-Type: application/json
Authorization: passar o token

{
"name": "Harry Osbourne",
"nickname": "Globin Green"
}

###
//Criar receita
POST http://localhost:3003/recipe
Content-Type: application/json

{
"title": "título da receita",
"description": "descrição da receita"
}

###
//pegar receita
GET http://localhost:3003/recipe/:id

// deletar usuario
###
DELETE http://localhost:3003/users/:id
Empty file.
91 changes: 91 additions & 0 deletions modulo7/cookenu/src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { UserDatabase } from "../data/UserDatabase"
import { CustomError, InvalidPassword, UserNotFound } from "../error/CustomError"
import { AuthenticationData } from "../model/types"
import { EditUserInput, EditUserInputDTO, LoginUserInputDTO, UserInputDTO, user } from "../model/user"
import Authenticator from "../services/Authenticator"
import HashManager from "../services/HashManager"
import IdGenerator from "../services/IdGenerator"


export class UserBusiness {
private userDB: UserDatabase
constructor(){
this.userDB = new UserDatabase()
}
public createUser = async (input :UserInputDTO) => {
let {name , email, password} = input

if (!name || !email || !password) {
throw new CustomError(422, "Ausência de parâmetro")
}


const id = IdGenerator.generateId()
const hash = await HashManager.generateHash(password)

const user:user = {
id,
name,
email,
password: hash,

}

await this.userDB.insertUser(user)
const token = Authenticator.generateToken({id})

return token
}

public login = async (input:LoginUserInputDTO) => {
let {email, password} = input

if(!email || !password) {
throw new CustomError(400, "Ausência de parâmetros")
}

const user = await this.userDB.findUserByEmail(email)
const hashCompare = await HashManager.compareHash(
password,
user.password
)

if(!hashCompare){
throw new InvalidPassword()
}

const payload :AuthenticationData = {
id: user.id,
}

const token = Authenticator.generateToken(payload)

return token
}

public editUser = async (input:EditUserInputDTO, token: string) => {
let {name , id} = input

if (!name || !token) {
throw new CustomError(422, "Ausência de parâmetro")
}

const userExist = await this.userDB.getUserById(id)
if(!userExist){
throw new UserNotFound()
}

const tokenData = Authenticator.getTokenData(token)
console.log(tokenData)


const editedUser :EditUserInput = {
name,
id
}

await this.userDB.editUser(editedUser)
}


}
19 changes: 19 additions & 0 deletions modulo7/cookenu/src/controller/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import express from "express"
import cors from "cors"
import { AddressInfo } from "net"

export const app = 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}`);
//console.log(`Server is running in ${address.address}:${address.port}`);

} else {
console.error(`Failure upon starting server.`);
}
})
20 changes: 20 additions & 0 deletions modulo7/cookenu/src/data/BaseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import knex from 'knex'
import dotenv from 'dotenv'

dotenv.config()

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
}
})

}
Empty file.
75 changes: 75 additions & 0 deletions modulo7/cookenu/src/data/UserDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { CustomError } from "../error/CustomError";
import { EditUserInput, user } from "../model/user";
import { BaseDatabase } from "./BaseDatabase";

export class UserDatabase extends BaseDatabase {
public insertUser = async (user: user) => {
try {
await UserDatabase.connection
.insert({
id: user.id,
name: user.name,
email: user.email,
password: user.password,

})
.into("cookenu_users");
} catch (error: any) {
throw new CustomError(400, error.sqlMessage);
}
};

public editUser = async (user: EditUserInput) => {
try {
await UserDatabase.connection
.update({ name: user.name})
.where({ id: user.id })
.into("cookenu_users");
} catch (error: any) {
throw new CustomError(400, error.sqlMessage);
}
};

public findUserByEmail = async (email: string) => {
try {
const result = await UserDatabase.connection("cookenu_users")
.select()
.where({email});
return result[0];
} catch (error: any) {
throw new CustomError(400, error.sqlMessage);
}
};

public getUserById = async (id: string) => {
try {
const result = await UserDatabase.connection("cookenu_users")
.select()
.where({id});
return result[0];
} catch (error: any) {
throw new CustomError(400, error.sqlMessage);
}
};

public selectUser = async (id: string) => {
try {
const result = await UserDatabase.connection("cookenu_users")
.select()
.where({id});

} catch (error: any) {
throw new CustomError(400, error.sqlMessage);
}
}


}




function into(arg0: string) {
throw new Error("Function not implemented.");
}

35 changes: 35 additions & 0 deletions modulo7/cookenu/src/error/CustomError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export class CustomError extends Error {
constructor(statusCode: number, message: string){
super(message)
}
}

export class InvalidName extends CustomError{
constructor(){
super(400, "Nome inválido")
}
}

export class InvalidEmail extends CustomError{
constructor(){
super(400, "Email inválido")
}
}

export class InvalidPassword extends CustomError{
constructor(){
super(400, "Senha inválida")
}
}

export class UserNotFound extends CustomError{
constructor(){
super(404, "Usuário não encontrado")
}
}

export class UnathorizedUser extends CustomError{
constructor(){
super(401, "Usuário não autorizado")
}
}
Empty file added modulo7/cookenu/src/index.ts
Empty file.
3 changes: 3 additions & 0 deletions modulo7/cookenu/src/model/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type AuthenticationData = {
id: string
}
41 changes: 41 additions & 0 deletions modulo7/cookenu/src/model/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export type user ={
id: string
name: string
email: string,
password: string
}

export interface UserInputDTO {
name:string
email: string,
password: string

}

export type Post = {
id: string,
title:string
description: string ,
cratedAt:Date
}

export interface PostInputDTO {
title:string
description: string,
cratedAt:Date
}

export interface LoginUserInputDTO {
email: string,
password: string
}

export interface EditUserInputDTO {
name: string,
id: string
}

export interface EditUserInput {
name: string,
id: string
}
Loading