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
15 changes: 15 additions & 0 deletions semana19/aula55/src/data/functionGetUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { connection } from "./connection"

const functionGetUser = async(
email:string
) => {

const result = await connection
.select("*")
.from("aula55_User")
.where({email})

return result[0]
}

export default functionGetUser
15 changes: 15 additions & 0 deletions semana19/aula55/src/data/functionGetUserId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

import { connection } from "./connection"

const functionGetUserId = async(
id:string
):Promise<any> => {

const result = await connection
.select("*")
.from("aula55_User")
.where({ id });

return result[0];
}
export default functionGetUserId
2 changes: 1 addition & 1 deletion semana19/aula55/src/data/functionToCreateUser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { connection } from "../connection"
import { connection } from "./connection"

const functionToCreateUser = async(
id:string,
Expand Down
33 changes: 31 additions & 2 deletions semana19/aula55/src/endpoints/createUser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
import { Request, Response } from "express"
import { connection } from "../data/connection"
import functionToCreateUser from "../data/functionToCreateUser"
import AuthenticationData from "../services/AuthenticationData"
import IdGeneration from "../services/generateId"


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

const {email, password} = req.body

if(!email || !password || email.indexOf("@")===-1 || password.length < 6){
res.statusCode = 422
throw new Error("Preencha os campos 'email' e 'password'")
}

//VERIFICAR SE O USUÁRIO JÁ EXISTE
const [user] = await connection("aula55_User")
.where({email})

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

//GERAR ID
const id = new IdGeneration().generateId()

await functionToCreateUser(id,email,password)

//PEGAR O TOKEN

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

res.status(200).send({token});
} catch (error:any) {

res.status(400).send({message: error.message});
}
}

Expand Down
31 changes: 31 additions & 0 deletions semana19/aula55/src/endpoints/getUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Request, Response } from "express"
import functionGetUserId from "../data/functionGetUserId";
import AuthenticationData from "../services/AuthenticationData";

const getUser = async (req: Request, res: Response) => {
try {
const token = req.headers.authorization as string

//VERIFICAR SE O TOKEN É VÁLIDO
const tokenData = new AuthenticationData().getTokenData(token);

if(!tokenData){
res.statusCode = 401
res.statusMessage = "Token invalido"
throw new Error()
}

const user = await functionGetUserId(tokenData.id);

res.status(200).send({
id: user.id,
email: user.email
});
} catch (err:any) {
res.status(400).send({
message: err.message,
});
}
}

export default getUser
40 changes: 40 additions & 0 deletions semana19/aula55/src/endpoints/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Request, Response } from "express"
import { connection } from "../data/connection"
import functionGetUser from "../data/functionGetUser"
import functionToCreateUser from "../data/functionToCreateUser"
import AuthenticationData from "../services/AuthenticationData"
import IdGeneration from "../services/generateId"


const login = async(req:Request, res:Response):Promise<void> => {
try {
const {email, password} = req.body

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

//VERIFICAR SE O USUÁRIO JÁ EXISTE
const user = await functionGetUser(email)

if (!user || user.password !==password) {
res.statusCode = 401
res.statusMessage = "Credenciais inválidas"
throw new Error()
}

//VAI GERAR O TOKEN E DEVOLVE-LO

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

res.status(200).send({token});
} catch (error:any) {
res.status(400).send({message: error.message});
}
}

export default login



9 changes: 6 additions & 3 deletions semana19/aula55/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { Request, Response} from "express"
import app from "./app"
import createUser from "./endpoints/createUser"
import getUser from "./endpoints/getUser"
import login from "./endpoints/login"


app.get("/", (req, res) => {
res.send("hello world!")
})

app.get("/user/profile", getUser)

//criar usuário

app.post("/user/signup", createUser)

//login
app.post("/user/login", login)

33 changes: 25 additions & 8 deletions semana19/aula55/src/services/AuthenticationData.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,32 @@
import { sign } from "jsonwebtoken";
import { JwtPayload, sign, verify } from "jsonwebtoken";
import { Authenticator } from "../types";

class AuthenticationData {
generateToken = (id: Authenticator) => {
const token = sign(
id,
process.env.JWT_SECRET as string,
{expiresIn: "24hr"}

)
return token
}

const AuthenticationData = (id: Authenticator) => {
const token = sign(
id,
process.env.JWT_SECRET as string,
{expiresIn: "1min"}
getTokenData = (token:string) => {
try {
const tokenData = verify(
token,
process.env.JWT_SECRET as string//se eu passar mais caracteres vai dar assinatura inválida, pois não condiz com a palavra secreta que passei no token
) as JwtPayload

)
return token
return {
id: tokenData.id
}
} catch (error) {
console.log(error)
}
}
}


export default AuthenticationData
9 changes: 6 additions & 3 deletions semana19/aula55/src/services/generateId.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { v4 } from "uuid"

const generateId = ():string => {
return v4()
class IdGeneration {
generateId = ():string => {
return v4()
}
}

export default generateId

export default IdGeneration
Loading