Skip to content
Open

base #58

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 modulo4/iwfs-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 modulo4/iwfs-cookenu/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "iwfs-cookenu",
"version": "1.0.0",
"description": "",
"main": "app.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.4",
"ts-node-dev": "^1.1.8",
"typescript": "^4.5.5"
},
"dependencies": {
"@types/jsonwebtoken": "^8.5.8",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"jsonwebtoken": "^8.5.1",
"knex": "^1.0.3",
"mysql": "^2.18.1",
"uuid": "^8.3.2"
}
}
28 changes: 28 additions & 0 deletions modulo4/iwfs-cookenu/request.rest
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
POST http://localhost:3003/login
Content-Type: application/json
Authorization: "3a297fc1-910e-4fc1-a8b1-5fcc01da752b"

{

"email": "igor@gmail.com",
"password": "igorigor123"
}
###

GET http://localhost:3003/user/profile
Content-Type: application/json
Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNhMjk3ZmMxLTkxMGUtNGZjMS1hOGIxLTVmY2MwMWRhNzUyYiIsImlhdCI6MTY0NjE0MjQwNiwiZXhwIjoxNjQ2MzE1MjA2fQ.49cL29yj9iWoi1CgLgoM-18SHSo7OuSSdI5FwNx7PoU

###
POST http://localhost:3003/recipe
Content-Type: application/json
Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNhMjk3ZmMxLTkxMGUtNGZjMS1hOGIxLTVmY2MwMWRhNzUyYiIsImlhdCI6MTY0NjI1ODk3NSwiZXhwIjoxNjQ2NDMxNzc1fQ.bQiculocWEhoeB3guk3CaXx8vxPBMfv6y-30KipSnpM

{
"title": "Arroz",
"description": "AAAAAAAAAAAAAAAAAAAAAAAA"
}


###
GET http://localhost:3003/recipe
22 changes: 22 additions & 0 deletions modulo4/iwfs-cookenu/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import express, { Express } from "express"
import cors from "cors"
import dotenv from "dotenv"
import { AddressInfo } from "net"

dotenv.config();

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.`);
}
});


export default app
34 changes: 34 additions & 0 deletions modulo4/iwfs-cookenu/src/data/RecipieDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import baseDataBase from "../entities/BaseDataBase";
import { Recipie } from "../entities/Class";


export class RecipieDataBase extends baseDataBase{

async createRecipie(recipie: Recipie):Promise<any>{
try{
const recipies = await baseDataBase.connection('Receitas').insert({
id: recipie.getId(),
criador_id: recipie.getCreator(),
titulo: recipie.getTitle(),
descricao: recipie.getDescription(),
data: recipie.getDate()
})
return recipies[0] && Recipie.toUserModel(recipies[0])
} catch(e:any){
throw new Error(e.sqlMessage || e.message)
}
}

async getRecipie(id:string){
try{
const recipie = await baseDataBase.connection('Receitas')
.select('id', 'titulo', 'descricao', 'data')
.where({id})
return recipie[0] && Recipie.toUserModel(recipie[0])

} catch(e:any){
throw new Error(e.sqlMessage || e.message)
}
}

}
59 changes: 59 additions & 0 deletions modulo4/iwfs-cookenu/src/data/UserDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import baseDataBase from "../entities/BaseDataBase";
import { Recipie, User } from "../entities/Class";


export class UserDataBase extends baseDataBase {

async createUser(user: User) {
console.log(user)
await baseDataBase.connection('Cookenu').insert({
id: user.getId(),
nome: user.getName(),
email: user.getEmail(),
password: user.getPassword()
})
}


async findUserByEmail(email: string): Promise<User> {
try {
const user = await baseDataBase.connection('Cookenu')
.select('*')
.where({ email })

return user[0] && User.toUserModel(user[0])
} catch (e: any) {
throw new Error(e.sqlMessage || e.message)
}
}

async getProfile(id: string): Promise<any> {
try {
const profile = await baseDataBase.connection('Cookenu')
.select("id", "nome", "email")
.where({ id })

return profile[0] && User.toUserModel(profile[0])
} catch (e: any) {

throw new Error(e.sqlMessage || e.message)
}
}

async getProfileById(id: string): Promise<any> {
try {
const profileById = await baseDataBase.connection('Cookenu')
.select('id','nome', 'email')
.where({id})

return profileById[0] && User.toUserModel(profileById[0])
} catch (e: any) {

throw new Error(e.sqlMessage || e.message)
}
}


}


34 changes: 34 additions & 0 deletions modulo4/iwfs-cookenu/src/endpoints/createRecipes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

import { Response, Request } from "express"
import { Authenticator } from "../services/Authenticator"
import { idGen } from "../services/idGen"
import { Recipie } from "../entities/Class"
import { RecipieDataBase } from "../data/RecipieDataBase"

export async function createRecipie(req:Request, res:Response):Promise<any>{
try{
const token = req.headers.authorization as string
const {title, description} = req.body
const idGenerator = new idGen()
const id = idGenerator.generate()
const data = new Date()

if(!title || !description){
res.status(422).send('Preencha todos os campos')
}

const authenticator = new Authenticator()
const tokenIsCorrect = authenticator.getTokenData(token)
console.log(tokenIsCorrect)
if(!tokenIsCorrect){
res.status(422).send('Token inválido')
}
const recipie: Recipie = new Recipie(id, tokenIsCorrect.id, title, description, data)
const recipieDataBase = new RecipieDataBase()
await recipieDataBase.createRecipie(recipie)

res.status(201).send('Receita criada')
} catch(e:any){
res.status(500).send(e.message)
}
}
19 changes: 19 additions & 0 deletions modulo4/iwfs-cookenu/src/endpoints/getProfile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { UserDataBase } from "../data/UserDataBase"
import { Response, Request } from "express"
import { Authenticator } from "../services/Authenticator"

export async function getProfile(req: Request, res: Response): Promise<any>{
try {
const token = req.headers.authorization as string

const authenticator = new Authenticator()
const tokenIsCorrect = authenticator.getTokenData(token)

const userDatabase = new UserDataBase()
const user = await userDatabase.getProfile(tokenIsCorrect.id)

res.status(200).send(user)
} catch (e: any) {
res.status(500).send(e.message)
}
}
25 changes: 25 additions & 0 deletions modulo4/iwfs-cookenu/src/endpoints/getProfileById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Request, Response } from 'express'
import { UserDataBase } from '../data/UserDataBase'
import { Authenticator } from '../services/Authenticator'

export async function getProfileById (req:Request, res:Response):Promise<any>{
try{
const id = req.params.id as string

const token = req.headers.authorization as string

const authenticador = new Authenticator()
const tokenIsCorrect = authenticador.getTokenData(token)

const userDatabase = new UserDataBase()
const profile = await userDatabase.getProfileById(id)

if(!profile){
res.status(404).send('Usuário não existe')
}

res.status(200).send(profile)
} catch(e: any){
res.status(400).send(e.message)
}
}
26 changes: 26 additions & 0 deletions modulo4/iwfs-cookenu/src/endpoints/getRecipeById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Response, Request } from "express"
import { RecipieDataBase } from "../data/RecipieDataBase"
import { Authenticator } from "../services/Authenticator"


export async function getRecipeById(req:Request, res:Response):Promise<any>{
try{
const id = req.params.id as string

if(!id){
res.status(401).send('Receita não encontrada')
}
const token = req.headers.authorization as string

const authenticator = new Authenticator()
const tokenIsCorrect = authenticator.getTokenData(token)

const recipe = new RecipieDataBase()
const getRecipe = await recipe.getRecipie(id)

res.status(200).send(getRecipe)
} catch(e:any){
res.status(500).send(e.message)
}
}

42 changes: 42 additions & 0 deletions modulo4/iwfs-cookenu/src/endpoints/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Request, Response } from 'express'
import { UserDataBase } from '../data/UserDataBase'
import { Authenticator } from '../services/Authenticator'
import { HashManager } from '../services/HashManager'




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


if (!email || !password)
res.status(422).send('Preencha os campos corretamente.')


const userDataBase = new UserDataBase()

const user = await userDataBase.findUserByEmail(email)

if (!user) {
res.status(409).send('O e-mail não está cadastrado')
}

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

if(!passwordIsCorrect){
res.status(401).send('Senha ou e-mail incorretos')
}
const authenticator = new Authenticator()
const token = authenticator.generate({ id: user.getId()})


res.status(200).send(token ? `Usuário logado com sucesso: ${token}` : '')

} catch (e: any) {
res.status(400).send(e.message)
}
}

49 changes: 49 additions & 0 deletions modulo4/iwfs-cookenu/src/endpoints/signup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@

import { Request, Response } from 'express'
import { UserDataBase } from '../data/UserDataBase'
import { User } from '../entities/Class'
import { Authenticator } from '../services/Authenticator'
import { HashManager } from '../services/HashManager'
import { idGen } from '../services/idGen'



export async function signup(req: Request, res: Response) {
try {
const { name, email, password } = req.body
const idGenerator = new idGen()
const id = idGenerator.generate()

if (!name || !email || !password)
res.status(422).send('Preencha os campos corretamente.')

if (password.length < 6) {
res.status(401).send('A senha deve ter 6 ou mais caracteres')
}

const userDataBase = new UserDataBase()

const user = await userDataBase.findUserByEmail(email)

if (user) {
res.status(409).send('O e-mail já está cadastrado')
}

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(token ? `Token de registro: ${token}` : '')

} catch (e: any) {
res.status(400).send(e.message)
}
}

Loading