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 changes: 2 additions & 0 deletions semana19/aula56/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
"typescript": "^4.5.4"
},
"dependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/jsonwebtoken": "^8.5.6",
"@types/knex": "^0.16.1",
"@types/uuid": "^8.3.3",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
Expand Down
50 changes: 50 additions & 0 deletions semana19/aula56/src/endpoints/createUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Request, Response } from "express";
import connection from "../data/connection";
import { Authenticator } from "../services/Authenticator";
import { HashManager } from "../services/HashManager";
import { IdGeneration } from "../services/IdGeneration";
import { user } from "../types";

export const createUser = async (req: Request, res: Response):Promise<void> => {
try {

const {email, password} = req.body
if(!email || !password){
res.statusCode = 422
throw new Error("Preencha os campos 'email' e 'password' ")
}

const [user] = await connection("aula56_users")
.where({email})

if(user){
res.statusCode = 409
throw new Error('Email já cadastrado')
}


//gerar o id
const id:string = new IdGeneration().generateId()

//antes de slvar no banco, tenho que criptografar
const cypherPassword:string = new HashManager().generateHash(password)

const newUser:user = {
id,
email,
password : cypherPassword
}
//Inserir na tabela
await connection("aula56_users")
.insert(newUser)

//autenticar, ou seja, gerar o token

const token = new Authenticator().generateToken({id})

res.status(201).send({newUser,token})

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

export default async function login(
req: Request,
res: Response
): Promise<void> {
try {

const { email, password } = req.body;

if (!email || !password) {
res.statusCode = 422
throw new Error("Preencha os campos 'email' e 'password' ")
}

// select * from to_do_list_users where email = email
const [user] = await connection("to_do_list_users").where({ email })

//VERIFICANDO SE O A SENHA PASSADA É GUAL AO HASH QUE ESTÁ NO BANCO
const passwordIsCorrect:boolean = new HashManager().compareHash(password, user?user.password:"")

if (!user || !passwordIsCorrect) {
res.statusCode = 401
res.statusMessage = "Credenciais invalidas"
throw new Error()
}

const token = new Authenticator().generateToken({id: user.id})

res.status(200).send({ token })

} catch (error) {

if (res.statusCode === 200) {
console.log(error)
res.status(500).send({ message: "Internal server error" })
} else {
res.end()
}
}
}
9 changes: 5 additions & 4 deletions semana19/aula56/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Request, Response } from "express"

import app from "./app"
import { createUser } from "./endpoints/createUser"



app.get("/", (req, res) => {
res.send("Hello world!")
})
app.post("/signup", createUser)
17 changes: 17 additions & 0 deletions semana19/aula56/src/services/Authenticator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { sign } from "jsonwebtoken"
import { authenticatorData } from "../types"

export class Authenticator {

generateToken = (payload:authenticatorData)=>{
const token = sign(
payload,
process.env.JWT_SECRET as string
)

return token
}


getToken = ()=>{}
}
18 changes: 18 additions & 0 deletions semana19/aula56/src/services/HashManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { compareSync, genSaltSync, hashSync } from "bcryptjs"

export class HashManager {

generateHash = (plainText:string):string => {
const cost:number = 12

const salt:string = genSaltSync(cost)

const cypherText:string = hashSync(plainText,salt)

return cypherText
}

compareHash = (plainText:string, cypherText:string):boolean => {
return compareSync(plainText, cypherText)
}
}
8 changes: 8 additions & 0 deletions semana19/aula56/src/services/IdGeneration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { v4 } from "uuid"

export class IdGeneration {

generateId = ():string => {
return v4()
}
}
9 changes: 9 additions & 0 deletions semana19/aula56/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface authenticatorData {
id:string
}

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