-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(createUnitInCompany/createUser): add new authController and create
Controller
- Loading branch information
Fabio Brasileiro
authored and
Fabio Brasileiro
committed
Sep 24, 2024
1 parent
14a409c
commit 6c5bc56
Showing
11 changed files
with
244 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* | ||
Warnings: | ||
- A unique constraint covering the columns `[name]` on the table `Company` will be added. If there are existing duplicate values, this will fail. | ||
- A unique constraint covering the columns `[document]` on the table `Company` will be added. If there are existing duplicate values, this will fail. | ||
- Added the required column `document` to the `Company` table without a default value. This is not possible if the table is not empty. | ||
*/ | ||
-- AlterTable | ||
ALTER TABLE "Company" ADD COLUMN "document" TEXT NOT NULL; | ||
|
||
-- AlterTable | ||
ALTER TABLE "User" ADD COLUMN "companyId" INTEGER; | ||
|
||
-- CreateIndex | ||
CREATE UNIQUE INDEX "Company_name_key" ON "Company"("name"); | ||
|
||
-- CreateIndex | ||
CREATE UNIQUE INDEX "Company_document_key" ON "Company"("document"); | ||
|
||
-- AddForeignKey | ||
ALTER TABLE "User" ADD CONSTRAINT "User_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE SET NULL ON UPDATE CASCADE; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { PrismaClient } from '@prisma/client' | ||
import type { Request, Response } from 'express' | ||
|
||
const prisma = new PrismaClient() | ||
|
||
export const createUnitInCompany = async (req: Request, res: Response) => { | ||
const { name } = req.body | ||
|
||
// Verificar se o usuário está autenticado | ||
if (!req.user || !req.user.id) { | ||
return res.status(401).json({ message: 'User not authenticated' }) | ||
} | ||
|
||
const adminUserId = req.user.id // Pega o ID do usuário autenticado | ||
|
||
try { | ||
// Verificar se o usuário autenticado é realmente um ADMIN | ||
const adminUser = await prisma.user.findUnique({ | ||
where: { id: adminUserId }, | ||
include: { company: true }, // Incluir a empresa relacionada | ||
}) | ||
|
||
if (!adminUser || adminUser.role !== 'ADMIN') { | ||
return res.status(403).json({ message: 'Only administrators can create units.' }) | ||
} | ||
|
||
// Verifica se o adminUser tem uma empresa associada | ||
if (!adminUser.companyId) { | ||
return res.status(400).json({ message: 'Admin user does not have a company associated.' }) | ||
} | ||
|
||
// Criar a nova unidade e associá-la à empresa do administrador | ||
const newUnit = await prisma.unit.create({ | ||
data: { | ||
name, | ||
company: { connect: { id: adminUser.companyId } }, // Associa a unidade à empresa do administrador | ||
}, | ||
}) | ||
|
||
res.status(201).json({ | ||
message: 'Unit created successfully', | ||
unit: newUnit, | ||
}) | ||
} catch (error) { | ||
console.error(error) | ||
res.status(500).json({ message: 'Server error' }) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import { PrismaClient } from '@prisma/client' | ||
import bcrypt from 'bcrypt' | ||
import type { Request, Response } from 'express' | ||
|
||
const prisma = new PrismaClient() | ||
const saltRounds = 10 | ||
|
||
export const createUserInCompany = async (req: Request, res: Response) => { | ||
const { email, password, name, role } = req.body | ||
|
||
// Verifica se req.user existe antes de tentar acessá-lo | ||
if (!req.user || !req.user.id) { | ||
return res.status(401).json({ message: 'User not authenticated' }) | ||
} | ||
|
||
const adminUserId = req.user.id // Pega o ID do usuário autenticado (administrador) | ||
|
||
try { | ||
// Verificar se o usuário autenticado é realmente um ADMIN | ||
const adminUser = await prisma.user.findUnique({ | ||
where: { id: adminUserId }, | ||
include: { company: true }, // Incluir a empresa relacionada | ||
}) | ||
|
||
if (!adminUser || adminUser.role !== 'ADMIN') { | ||
return res.status(403).json({ message: 'Only administrators can create users.' }) | ||
} | ||
|
||
// Verifica se o adminUser tem uma empresa associada | ||
if (!adminUser.companyId) { | ||
return res.status(400).json({ message: 'Admin user does not have a company associated.' }) | ||
} | ||
|
||
// Verificar se o email já existe | ||
const existingUser = await prisma.user.findUnique({ | ||
where: { email }, | ||
}) | ||
|
||
if (existingUser) { | ||
return res.status(400).json({ message: 'User already exists' }) | ||
} | ||
|
||
// Criptografar a senha | ||
const hashedPassword = await bcrypt.hash(password, saltRounds) | ||
|
||
// Criar o novo usuário e associá-lo à mesma empresa do administrador | ||
const newUser = await prisma.user.create({ | ||
data: { | ||
email, | ||
password: hashedPassword, | ||
name, | ||
role: role || 'USER', // Por padrão, novos usuários são do tipo 'USER' | ||
company: { connect: { id: adminUser.companyId } }, // Associa o novo usuário à empresa do admin | ||
}, | ||
}) | ||
|
||
res.status(201).json({ | ||
message: 'User created successfully', | ||
user: newUser, | ||
}) | ||
} catch (error) { | ||
console.error(error) | ||
res.status(500).json({ message: 'Server error' }) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import express from 'express' | ||
import { createUnitInCompany } from '@/controllers/createUnitInCompany' | ||
import authenticate from '../middleware/authenticate' | ||
import authorize from '../middleware/authorize' | ||
|
||
const createUnitRouter = express.Router() | ||
|
||
// Rota protegida para criar unidades dentro da empresa do administrador | ||
createUnitRouter.post('/create-unit', authenticate, authorize(['ADMIN']), createUnitInCompany) | ||
|
||
export default createUnitRouter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import express from 'express' | ||
import { createUserInCompany } from '@/controllers/createUserController' | ||
import authenticate from '../middleware/authenticate' | ||
import authorize from '../middleware/authorize' | ||
|
||
const createUserRouter = express.Router() | ||
|
||
// Rota protegida para criar usuários dentro da empresa do administrador | ||
createUserRouter.post('/create-user', authenticate, authorize(['ADMIN']), createUserInCompany) | ||
|
||
export default createUserRouter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export const validateCNPJ = (cnpj: string) => { | ||
// Adicione aqui a lógica de validação de CNPJ | ||
return true // Retorne true se for válido, false se não for | ||
} | ||
|
||
export const validateCPF = (cpf: string) => { | ||
// Adicione aqui a lógica de validação de CPF | ||
return true // Retorne true se for válido, false se não for | ||
} |