Skip to content

Commit

Permalink
Finalização da estrutura do Backend
Browse files Browse the repository at this point in the history
  • Loading branch information
PhMoraiis committed Oct 30, 2023
1 parent 603d040 commit aaa28b1
Show file tree
Hide file tree
Showing 18 changed files with 4,568 additions and 0 deletions.
5 changes: 5 additions & 0 deletions backend/.docker/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
Dockerfile
docker-compose.yml
.dockerignore
.env
17 changes: 17 additions & 0 deletions backend/.docker/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM node:18-alpine

RUN npm install -g yarn@latest mysql2

RUN mkdir -p /home/node/src/node_modules && chown -R node:node /home/node/src

WORKDIR /home/node/src

COPY package.json ./

RUN yarn

COPY --chown=node:node . .

EXPOSE 3001

CMD ["yarn", "dev"]
20 changes: 20 additions & 0 deletions backend/.docker/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
version: '3'

services:
database:
image: postgres
container_name: Matcher_DB
restart: always
ports:
- 5432:5432
environment:
- POSTGRES_HOST=localhost
- POSTGRES_USER=dev_usermatcher
- POSTGRES_PASSWORD=matcher_devpass
- POSTGRES_DB=matcher_db
volumes:
- pgdata:/data/postgres

volumes:
pgdata:
driver: local
42 changes: 42 additions & 0 deletions backend/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"env": {
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"no-unused-vars": [
"off"
],
"no-console": [
0
]
}
}
3 changes: 3 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules

.env
21 changes: 21 additions & 0 deletions backend/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Matcher

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Empty file added backend/README.md
Empty file.
38 changes: 38 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "backend_matcher",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "tsx src/index.ts",
"dev": "tsx watch src/index.ts",
"build": "tsup src",
"test": "vitest",
"coverage": "vitest run --coverage"
},
"dependencies": {
"@prisma/client": "^5.5.2",
"bcrypt": "^5.1.1",
"eslint": "^8.52.0",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mysql": "^2.18.1"
},
"devDependencies": {
"@rocketseat/eslint-config": "^2.1.0",
"@types/bcrypt": "^5.0.1",
"@types/express": "^4.17.20",
"@types/jsonwebtoken": "^9.0.4",
"@types/node": "^20.8.9",
"@typescript-eslint/eslint-plugin": "^6.9.0",
"@typescript-eslint/parser": "^6.9.0",
"@vitest/coverage-v8": "^0.34.6",
"dotenv": "^16.3.1",
"prisma": "^5.5.2",
"tsup": "^7.2.0",
"tsx": "^3.14.0",
"typescript": "^5.2.2",
"vitest": "^0.34.6",
"zod": "^3.22.4"
}
}
12 changes: 12 additions & 0 deletions backend/prisma/migrations/20231030163615_test_table/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT,
"password" TEXT NOT NULL,

CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
3 changes: 3 additions & 0 deletions backend/prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
18 changes: 18 additions & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
password String
}
60 changes: 60 additions & 0 deletions backend/src/controllers/Users/UsersController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* eslint-disable @typescript-eslint/no-unused-vars */

import { Request, Response } from 'express'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export class UserController {
async create(req: Request, res: Response) {
const { name, email, password } = req.body

const userExists = await prisma.user.findUnique({ where: { email } })

if (userExists) {
return res.status(400).json({ error: 'Email already exists!' })
}

const hashPassword = await bcrypt.hash(password, 10)

const newUser = await prisma.user.create({
data: { name, email, password: hashPassword },
})

const { password: _, ...user } = newUser

return res.status(201).json(user)
}

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

const user = await prisma.user.findUnique({ where: { email } })

if (!user) {
return res.status(400).json({ error: 'Email or password invalids' })
}

const verifyPass = await bcrypt.compare(password, user.password)

if (!verifyPass) {
return res.status(400).json({ error: 'Email or password invalids' })
}

const token = jwt.sign({ id: user.id }, process.env.JWT_PASS ?? '', {
expiresIn: '1d',
})

const { password: _, ...userLogin } = user

return res.status(200).json({ user: userLogin, token: token })
}

async getProfile(req: Request, res: Response) {
const user = await prisma.user.findUnique({ where: { id: req.user.id } })

return res.json(user)
}
}
41 changes: 41 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { z } from 'zod'
import express from 'express'
import { PrismaClient } from '@prisma/client'
import { routes } from './routes'

const prisma = new PrismaClient()

const userSchema = z.object({
name: z.string()
.min(3, { message: 'Name must be at least 3 characters long' })
.transform(name => name.toLocaleUpperCase()),
age: z.number().min(18, { message: 'You must be at least 18 years old' })
})

type User = z.infer<typeof userSchema>

function saveUserToDatabase(user: User) {
const { name, age } = userSchema.parse(user)

console.log(`Saving user ${name} with age ${age} to database...`)
}

saveUserToDatabase({ name: 'Philipe Morais', age: 18 })

const startServer = async () => {
const app = express()

app.use(express.json())

app.use(routes)

app.listen(process.env.PORT ? Number(process.env.PORT) : 3000, () => {
console.log('HTTP Server running')
})
}

startServer()
.catch((error) => console.log(error))
.finally(async () => {
await prisma.$disconnect()
})
38 changes: 38 additions & 0 deletions backend/src/middlewares/authMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { NextFunction, Request, RequestHandler, Response } from 'express'
import jwt from 'jsonwebtoken'
import { PrismaClient } from '@prisma/client'

type JwtPayload = {
id: number
}

const prisma = new PrismaClient()

export const authMiddleware: RequestHandler = async (
req: Request,
res: Response,
next: NextFunction
) => {
const { authorization } = req.headers

if (!authorization) {
return res.status(401).json({ error: 'Token not authorized' })
}

const token = authorization.split(' ')[1]

const { id } = jwt.verify(token, process.env.JWT_PASS ?? '') as JwtPayload

const user = await prisma.user.findUnique({ where: { id } })

if (!user) {
return res.status(400).json({ error: 'User not found' })
}

const { password: _, ...loggedUser } = user

req.user = { ...loggedUser }

next()
}
14 changes: 14 additions & 0 deletions backend/src/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Router } from 'express'
import { UserController } from './controllers/Users/UsersController'

const routes = Router()

routes.get('/', (req, res) => {
res.send('Hello World! Você está na raiz da API!')
})

routes.post('/user', new UserController().create)
routes.post('/login', new UserController().login)
routes.get('/profile', new UserController().getProfile)

export { routes }
9 changes: 9 additions & 0 deletions backend/src/types/express.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { User } from '@prisma/client'

declare global {
namespace Express {
export interface Request {
user: Partial<User>
}
}
}
Loading

0 comments on commit aaa28b1

Please sign in to comment.