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
Binary file added semana20/projeto-Labook/.DS_Store
Binary file not shown.
93 changes: 93 additions & 0 deletions semana20/projeto-Labook/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# LABOOK

## Primeiros Passos

* Clonar este repositório
* Executar `npm install` para adicionar as dependências
* Criar um arquivo .env na raiz do projeto e preencher as chaves a seguir com os valores apropriados:
```
DB_HOST =
DB_USER =
DB_PASSWORD =
DB_SCHEMA =

JWT_KEY =

BCRYPT_COST =
```
* Executar `npm run migrations` para adicionar as tabelas ao banco de dados (em caso de sucesso, o servidor já estará pronto para receber requisições )

## Endpoints

1. Cadastro
* Exemplo de requisição:
```bash
curl -i -X POST http://localhost:3003/users/signup -H "Content-Type: application/json" -d '{"name":"Alice","email":"alice@gmail.com","password":"pass123"}'
```
* Exemplo de resposta (sucesso):
```bash
HTTP/1.1 201 Created
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 220
ETag: W/"dc-ec7r4rkKsMBe/V0SGyUkO6Vyto0"
Date: Tue, 17 Nov 2020 14:33:15 GMT
Connection: keep-alive

{"message":"Success!", "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Ijg5OGJjNDVlLTExZjEtNGEyMy04OTZhLTdmMmUyOWNmZTAxMiIsImlhdCI6MTYwNTYyMzU5NSwiZXhwIjoxNjA1NzA5OTk1fQ.pWxV2vtLnp0hKm0CXXnLpnDu6PEPkZM27A71oTTCYfE"}%
```
1. Login
* Exemplo de requisição:
```bash
curl -i -X POST http://localhost:3003/users/login -H "Content-Type: application/json" -d '{"email":"alice@gmail.com","password":"pass123"}'
```
* Exemplo de resposta (sucesso):
```bash
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 220
ETag: W/"dc-IBDYVXSmDzdFsqHXhPCAutzNwn8"
Date: Tue, 17 Nov 2020 14:39:23 GMT
Connection: keep-alive

{"message":"Success!","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Ijg5OGJjNDVlLTExZjEtNGEyMy04OTZhLTdmMmUyOWNmZTAxMiIsImlhdCI6MTYwNTYyMzk2MywiZXhwIjoxNjA1NzEwMzYzfQ.9JvXRQpazI5k6GAnc1lFcVcTbZ_ElASnwyybU_tRU48"}%
```
1. Criar Post
* Exemplo de requisição:
```bash
curl -i -X POST http://localhost:3003/posts/create -H "Content-Type: application/json" -H "authorization:$token" -d '{"photo":"https://i.picsum.photos/id/238/200/200.jpg?hmac=O4Jc6lqHVfaKVzLf8bWssNTbWzQoaRUC0TDXod9xDdM","description":"My city is beautiful =D","type":"normal"}'
```
* Exemplo de resposta (sucesso):
```bash
HTTP/1.1 201 Created
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 22
ETag: W/"16-ChcZhlw1slqtGuDwxLsUclql5gE"
Date: Tue, 17 Nov 2020 14:47:15 GMT
Connection: keep-alive

{"message":"Success!"}%
```
1. Buscar Post por id
* Exemplo de requisição:
```bash
curl -i http://localhost:3003/posts/$id -H "Content-Type: application/json" -H "authorization:$token"
```
* Exemplo de resposta (sucesso):
```bash
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 322
ETag: W/"142-IYRwCODXZBltXE3MydHuIDB8M3w"
Date: Tue, 17 Nov 2020 14:52:19 GMT
Connection: keep-alive

{"message":"Success!","post":{"id":"e4eb1531-d814-4742-b614-be2a36602548","photo":"https://i.picsum.photos/id/238/200/200.jpg?hmac=O4Jc6lqHVfaKVzLf8bWssNTbWzQoaRUC0TDXod9xDdM","description":"My city is beautiful =D","type":"normal","createdAt":"2020-11-17T17:47:15.000Z","authorId":"898bc45e-11f1-4a23-896a-7f2e29cfe012"}}%
```
23 changes: 23 additions & 0 deletions semana20/projeto-Labook/migrations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { connection } from "./src/index"

connection
.raw(`
CREATE TABLE IF NOT EXISTS labook_users(
id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);

CREATE TABLE IF NOT EXISTS labook_posts(
id VARCHAR(255) PRIMARY KEY,
photo VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
type ENUM("normal","event") DEFAULT "normal",
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
author_id VARCHAR(255),
FOREIGN KEY (author_id) REFERENCES labook_users (id)
)
`)
.then(console.log)
.catch(console.log)
37 changes: 37 additions & 0 deletions semana20/projeto-Labook/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "projeto-labook-semana20",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"migrations": "tsc && node ./build/migrations.js",
"start": "npm run build && node --inspect ./build/src/index.js",
"dev": "clear && ts-node-dev ./src/index.ts",
"build": "clear && echo \"Transpiling files...\" && tsc && echo \"Done!\" ",
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"knex": "^0.21.5",
"mysql": "^2.18.1",
"uuid": "^8.3.0"
},
"devDependencies": {
"@types/cors": "^2.8.7",
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.8",
"@types/jsonwebtoken": "^8.5.0",
"@types/knex": "^0.16.1",
"@types/node": "^14.11.2",
"@types/uuid": "^8.3.0",
"ts-node-dev": "^1.0.0-pre.63",
"typescript": "^4.0.3"
}
}
Empty file.
34 changes: 34 additions & 0 deletions semana20/projeto-Labook/src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import HashManager from "../services/HashManager";
import IdGenerator from "../services/IdGenerator";

export default class UserBusiness {
async signup(input: SignupInputDTO) {

try {
//Nesse caso, vou reqalizar as validações conforme o que foi estabelecido no body (req.body.name, req.body.email, req.body.password). Demonstrado na linha 10.
if (!input.name || !input.email || !input.password) {
throw new Error(`"name", "email" and "password" must be provided'`);
}

const idGenerator = new IdGenerator()

const id: string = new IdGenerator().generateId();

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

const user:user = {
id,
name: input.name,
email: input.email,
password: cypherPassword
}
await insertUser(user)

const token: string = generateToken({ id });

} catch (error) {

}
}
}
1 change: 1 addition & 0 deletions semana20/projeto-Labook/src/controller/PostController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
//Se tem req e res = Controller
24 changes: 24 additions & 0 deletions semana20/projeto-Labook/src/controller/UserController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//Se tem req e res = Controller
import express from 'express'
import { SignupInputDTO } from '../entities/User'

export default class UserController {
async signup(req: express.Request, res: express.Response) {
try {
let message = "Success!"
const { name, email, password } = req.body
const input :SignupInputDTO = {
name: req.body.name,
email: req.body.Email,
password: req.body.password
}
res.status(201).send({ message, token })

} catch (error:any) {
res.statusCode = 400
let message = error.sqlMessage || error.message

res.send({ message })
}
}
}
4 changes: 4 additions & 0 deletions semana20/projeto-Labook/src/data/BaseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

export class BaseDatabase {

}
Empty file.
17 changes: 17 additions & 0 deletions semana20/projeto-Labook/src/data/UserDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { BaseDatabase } from "./BaseDatabase";

export class UserDatabase extends BaseDatabase {
async insertUser(user:User) {
try {
await this.connection("labook_users")
.insert({
id,
name,
email,
password: cypherPassword,
});
} catch (error:any) {
throw new Error(error.sqlMessage || error.Message);
}
}
}
Empty file.
16 changes: 16 additions & 0 deletions semana20/projeto-Labook/src/entities/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export interface authenticationData {
id: string
}

export interface user {
id: string,
name: string,
email: string,
password: string
}

export interface SignupInputDTO {
name:string,
email:string,
password:string
}
Loading