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/criptografia-e-user-roles/.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 modulo7/criptografia-e-user-roles/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "criptografia-e-user-roles",
"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.8",
"@types/knex": "^0.16.1",
"@types/node": "^18.7.6",
"@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"
}
}
28 changes: 28 additions & 0 deletions modulo7/criptografia-e-user-roles/request.rest
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
POST http://localhost:3003/user/signup
Content-Type: application/json

{
"name": "Norman Osbourne",
"nickname": "Green Goblin",
"email": "osbourne@oscorp.com" ,
"password": "ihatepeter"
}
###

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

{
"email": "osbourne@oscorp.com",
"password": "ihatepeter"
}

###
PUT http://localhost:3003/user/edit/20bd6989-35f6-46a0-9ee5-caddc4e1b4c0
Content-Type: application/json
Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjIwYmQ2OTg5LTM1ZjYtNDZhMC05ZWU1LWNhZGRjNGUxYjRjMCIsImlhdCI6MTY1NDY0NzU4MSwiZXhwIjoxNjU0NjUxMTgxfQ.QjnFbW9cy_PH9CkJO6clhBaFJq6leqtkW0slrhkrcaI

{
"name": "Harry Osbourne",
"nickname": "Harry"
}
123 changes: 123 additions & 0 deletions modulo7/criptografia-e-user-roles/src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { UserDatabase } from "../data/UserDatabase";
import { CustomError, InvalidEmail, InvalidName, InvalidPassword, Unauthorized, UserNotFound } from "../error/customError";
import { UserInputDTO,user,EditUserInputDTO,EditUserInput,LoginInputDTO} from "../model/user";
import { HashManager } from "../services/HashManager";
import { IdGenerator } from "../services/IdGenerator";
import { TokenGenerator } from "../services/TokenGenerator";

const idGenerator = new IdGenerator()
const tokenGenerator = new TokenGenerator()
const userDatabase = new UserDatabase();
const hashManager = new HashManager()

export class UserBusiness {
public createUser = async (input: UserInputDTO): Promise<string> => {
try {
const { name, nickname, email, password } = input;

if (!name || !nickname || !email || !password) {
throw new CustomError(
400,
'Preencha os campos "name","nickname", "email" e "password"'
);
}

if (name.length < 4) {
throw new InvalidName();
}

if (!email.includes("@")) {
throw new InvalidEmail();
}

const id: string = idGenerator.generateId()

const hashPassword = await hashManager.generateHash(password)
// hashPassword: $2a$12$dUVoq2Zb7BbHNhS.awWxUu2K39F71jmPh27eUt.hsAWGGcJpqbcmC

const user: user = {
id,
name,
nickname,
email,
password: hashPassword,
};

await userDatabase.insertUser(user);
const token = tokenGenerator.generateToken(id)

return token
} catch (error: any) {
throw new CustomError(400, error.message);
}
};

public login = async (input: LoginInputDTO): Promise<string> => {
try {
const { email, password } = input;

if (!email || !password) {
throw new CustomError(
400,
'Preencha os campos"email" e "password"'
);
}

if (!email.includes("@")) {
throw new InvalidEmail();
}

const user = await userDatabase.findUser(email);

if (!user) {
throw new UserNotFound()
}

const hashCompare = await hashManager.compareHash(password, user.password)

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

const token = tokenGenerator.generateToken(user.id)

return token
} catch (error: any) {
throw new CustomError(400, error.message);
}
};

public editUser = async (input: EditUserInputDTO) => {
try {
const { name, nickname, id, token } = input;

if (!name || !nickname || !id || !token) {
throw new CustomError(
400,
'Preencha os campos "id", "name", "nickname" e "token"'
);
}

const data = tokenGenerator.tokenData(token)

if(!data.id) {
throw new Unauthorized()
}

if (name.length < 4) {
throw new InvalidName();
}

const editUserInput: EditUserInput = {
id,
name,
nickname,
};

const userDatabase = new UserDatabase();
await userDatabase.editUser(editUserInput);
} catch (error: any) {
throw new CustomError(400, error.message);
}
};
}
63 changes: 63 additions & 0 deletions modulo7/criptografia-e-user-roles/src/controller/UserController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Request, Response } from "express";
import { UserBusiness } from "../business/UserBusiness";
import { EditUserInputDTO, LoginInputDTO, UserInputDTO } from "../model/user";

export class UserController {

public signup = async (req: Request, res: Response) => {
try {
const { name, nickname, email, password } = req.body;

const input: UserInputDTO = {
name,
nickname,
email,
password,
};
const userBusiness = new UserBusiness()
const token = await userBusiness.createUser(input);

res.status(201).send({ message: "Usuário criado!", token });
} catch (error: any) {
res.status(400).send(error.message);
}
};

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

const input: LoginInputDTO = {
email,
password,
};
const userBusiness = new UserBusiness()
const token = await userBusiness.login(input);

res.status(200).send({ message: "Usuário logado!", token });
} catch (error: any) {
res.status(400).send(error.message);
}
};

public editUser = async (req: Request, res: Response) => {
try {

const input: EditUserInputDTO = {
name: req.body.name,
nickname: req.body.nickname,
id: req.params.id,
token: req.headers.authorization as string
};

const userBusiness = new UserBusiness()
console.log(input)
await userBusiness.editUser(input);

res.status(201).send({ message: "Usuário alterado!" });
} catch (error: any) {
res.status(400).send(error.message);
}
};

}
19 changes: 19 additions & 0 deletions modulo7/criptografia-e-user-roles/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"

// Configuração do Express
export const app = express()

app.use(express.json())
app.use(cors())

// Função que faz o servidor escutar as requisições vindas da porta definida.
const server = app.listen(process.env.PORT || 3000, () => {
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.`);
}
})
11 changes: 11 additions & 0 deletions modulo7/criptografia-e-user-roles/src/controller/userRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from "express";

import { UserController } from "../controller/UserController";

export const userRouter = express.Router()

const userController = new UserController()

userRouter.post('/signup', userController.signup)
userRouter.post('/login', userController.login )
userRouter.put('/edit/:id',userController.editUser )
20 changes: 20 additions & 0 deletions modulo7/criptografia-e-user-roles/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
}
})

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

export class UserDatabase extends BaseDatabase {
public findUser = async(email: string)=> {
try {
const result = await UserDatabase.connection("Auth_users")
.select()
.where({email});


return result[0];
} catch (error: any) {
throw new CustomError(400, error.message);
}
};

public insertUser = async (user: user) => {
try {
await UserDatabase.connection
.insert({
id: user.id,
name: user.name,
nickname: user.nickname,
email: user.email,
password: user.password,
})
.into("Auth_users");
} catch (error: any) {
throw new CustomError(400, error.message);
}
};

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



}
35 changes: 35 additions & 0 deletions modulo7/criptografia-e-user-roles/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 Unauthorized extends CustomError{
constructor(){
super(401, "Usuário não autorizado")
}
}
Loading