Skip to content

Commit

Permalink
Merge pull request #59 from mdsreq-fga-unb/feature/us06
Browse files Browse the repository at this point in the history
Feature/us06
  • Loading branch information
xGabrielCv authored Sep 10, 2024
2 parents 7af8f48 + f41c882 commit f3ea0a0
Show file tree
Hide file tree
Showing 47 changed files with 913 additions and 27 deletions.
17 changes: 16 additions & 1 deletion riso_backend/src/controllers/unit.controller.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import unitService from "../services/unit.service.js";
import unitUserService from "../services/unitUser.service.js";
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';

const findAllUnit = async (req, res) => {
try{
Expand Down Expand Up @@ -77,6 +80,18 @@ const createUnit = async (req, res) => {

const unit = await unitService.createService(unitData);

// Extração do ID do usuário a partir do token JWT nos headers
const token = req.headers.authorization.split(' ')[1]; // Obtém o token após o 'Bearer'
const decoded = jwt.verify(token, process.env.SECRET_JWT); // Decodifica o token com a chave secreta do JWT
const userId = decoded._id; // Pega o ID do usuário decodificado

// Criação da relação entre usuário e unidade
await unitUserService.createService({
user: userId,
unit: unit._id,
master_adm: true, // Define como administrador principal ou ajuste conforme necessário
});

return res.status(200).send({message: 'Unity and company successfully created ', unit});
}catch (err){
if (err.code === 11000) { // Código de erro para violação de chave única em MongoDB/Mongoose
Expand Down Expand Up @@ -105,7 +120,7 @@ const updateUnit = async (req, res) => {
}catch (err){
return res.status(500).send({message: err.message});
}
}
};

const deleteUnit = async (req,res) => {
try{
Expand Down
104 changes: 102 additions & 2 deletions riso_backend/src/controllers/unitUser.controller.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,48 @@
import unitUserService from "../services/unitUser.service.js";
import unitService from "../services/unit.service.js";
import jwt from 'jsonwebtoken'; // Biblioteca para manipular o JWT


// Controller para exibir todas as unidades associadas a um usuário pelo código do usuário
const getUnitsByUserCode = async (req, res) => {
try {
// Extração do código do usuário do token JWT
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).send({ message: 'Token not provided', substatus: 1 });
}

let userId;
try {
const decoded = jwt.verify(token, process.env.SECRET_JWT); // Decodifica o token
userId = decoded._id; // Pega o ID do usuário decodificado do token
} catch (err) {
return res.status(401).send({ message: 'Invalid token', substatus: 2 });
}

// Busca todas as associações UnitUser para o ID do usuário
const unitUsers = await unitUserService.findByUserIdService(userId);
if (!unitUsers || unitUsers.length === 0) {
return res.status(404).send({ message: 'No units found for this user', substatus: 3 });
}

// Extrai os IDs das unidades das associações
const unitIds = unitUsers.map((unitUser) => unitUser.unit);

// Busca as unidades correspondentes aos IDs
const units = await unitService.findByIds(unitIds);
if (!units || units.length === 0) {
return res.status(404).send({ message: 'Units not found', substatus: 4 });
}

return res.status(200).send({
message: 'Units retrieved successfully',
units,
});
} catch (err) {
return res.status(500).send({ message: err.message });
}
};

const findAllUnitUser = async (req, res) => {
try{
Expand Down Expand Up @@ -38,6 +82,60 @@ const createUnitUser = async (req, res) => {
}
}

// Controller para criar relação entre usuário e unidade pelo código da unidade
const createRelationByUnitCode = async (req, res) => {
try {
const { code } = req.body; // Recebe o código da unidade do body da requisição

// Verifica se o código foi fornecido
if (!code) {
return res.status(400).send({ message: 'Unit code is required', substatus: 1 });
}

// Extração do ID do usuário do token JWT
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).send({ message: 'Token not provided', substatus: 2 });
}

let userId;
try {
const decoded = jwt.verify(token, process.env.SECRET_JWT); // Decodifica o token
userId = decoded._id; // Pega o ID do usuário decodificado do token
} catch (err) {
return res.status(401).send({ message: 'Invalid token', substatus: 3 });
}

// Busca a unidade pelo código fornecido
const unit = await unitService.findByCode(code);
if (!unit) {
return res.status(404).send({ message: 'Unit not found', substatus: 4 });
}

// Prepara os dados para criar a relação UnitUser
const unitUserData = {
user: userId,
unit: unit._id,
master_adm: false, // Define `master_adm` como necessário, ajuste conforme sua lógica
};

// Cria a relação UnitUser utilizando o serviço
const unitUser = await unitUserService.createService(unitUserData);

return res.status(201).send({
message: 'Relation between user and unit created successfully',
unitUser,
});
} catch (err) {
if (err.code === 11000) {
// Trata o erro de violação de chave única do MongoDB/Mongoose
return res.status(400).send({ message: 'Relation already exists', substatus: 5 });
}

return res.status(500).send({ message: err.message });
}
};

const findByUserIdUnitUser = async (req, res) => {
try {
const { userId } = req.body;
Expand Down Expand Up @@ -95,7 +193,7 @@ const updateUnitUser = async (req, res) => {
}catch(err) {
return res.status(500).send({ message: err.message });
}
}
};

const deleteUnitUser = async (req,res) => {
try{
Expand All @@ -115,13 +213,15 @@ const deleteUnitUser = async (req,res) => {
}catch(err){
return res.status(500).send({ message: err.message });
}
}
};

export default {
getUnitsByUserCode,
findAllUnitUser,
createUnitUser,
findByUserIdUnitUser,
findAllUsersByUnitIdUserUnit,
updateUnitUser,
deleteUnitUser,
createRelationByUnitCode
};
1 change: 0 additions & 1 deletion riso_backend/src/middleware/auth.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ dotenv.config();
export const authMiddleware = (req, res, next) => {
try {
const { authorization } = req.headers;
console.log(authorization);

if (!authorization) return res.status(401).send({message: 'User Unauthorized'});

Expand Down
12 changes: 12 additions & 0 deletions riso_backend/src/models/Facial.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import mongoose from 'mongoose';

const FacialSchema = new mongoose.Schema({
numberOfSmiles: {
type: Number,
required: true,
},

}, {timestamps:true});

const Unit = mongoose.model('Unit', UnitSchema);
export default Unit;
3 changes: 2 additions & 1 deletion riso_backend/src/routes/unitUser.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ const unitUserRouter = express.Router()

unitUserRouter.get('/findAllUnitUser', unitUserController.findAllUnitUser);
unitUserRouter.post('/createUnitUser',unitUserController.createUnitUser);
unitUserRouter.post('/createRelationByUnitCode', unitUserController.createRelationByUnitCode);
unitUserRouter.get('/findByUserId/:UserId', unitUserController.findByUserIdUnitUser);
unitUserRouter.get('/findAllUsersByUnitId/:UnitId', unitUserController.findAllUsersByUnitIdUserUnit);
unitUserRouter.patch('/updateUnitUser/:id', )
unitUserRouter.patch('/updateUnitUser/:id', unitUserController.updateUnitUser);
unitUserRouter.delete('/deleteUnitUser/:id',unitUserController.deleteUnitUser);

export default unitUserRouter;
16 changes: 16 additions & 0 deletions riso_backend/src/services/unit.service.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
import Unit from "../models/Unit.js";

/**
* Encontra todas as associações UnitUser para um ID de usuário específico.
* @param {string} userId - O ID do usuário.
* @returns {Promise<Array>} - Uma promessa que resolve para uma lista de associações UnitUser.
*/

const findAllService = () => Unit.find();
const findByCode = (code) => Unit.findOne({ code });
const createService = (body) => Unit.create(body);
const updateService = (params, body) => Unit.updateOne(params, body, {new: true});
const deleteService = (params) => Unit.deleteOne(params);
const findByIds = async (ids) => {
try {
// Encontra todas as unidades cujos IDs estão na lista fornecida
const units = await Unit.find({ _id: { $in: ids } });
return units;
} catch (err) {
throw new Error('Error finding units by IDs: ' + err.message);
}
};

export default {
findByIds,
findAllService,
findByCode,
createService,
Expand Down
15 changes: 15 additions & 0 deletions riso_backend/src/services/unitUser.service.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import UnitUser from "../models/UnitUser.js";

/**
* Encontra todas as associações UnitUser para um ID de usuário específico.
* @param {string} userId - O ID do usuário.
* @returns {Promise<Array>} - Uma promessa que resolve para uma lista de associações UnitUser.
*/
const findAllService = () => UnitUser.find();
const createService = (params, body) => UnitUser.create(params, body);
const findByUserIdService = (userID) => UnitUser.find({ user: userID });
const findAllUsersByUnitIdService = (unitID) => UnitUser.find({ unit: unitID });
const updateService = (params, body) => UnitUser.updateOne(params, body, {new: true});
const deleteService = (params) => UnitUser.deleteOne(params);
const findByUserId = async (userId) => {
try {
// Encontra todas as associações UnitUser para o ID do usuário
const unitUsers = await UnitUser.find({ user: userId }).populate('unit');
return unitUsers;
} catch (err) {
throw new Error('Error finding UnitUser associations: ' + err.message);
}
};

export default {
findByUserId,
findAllService,
createService,
findByUserIdService,
Expand Down
1 change: 1 addition & 0 deletions riso_facial-service/face-api.min.js

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions riso_facial-service/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script defer src="face-api.min.js"></script>
<script defer src="script.js"></script>
<style>
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}

canvas {
position: absolute;
}
</style>
</head>
<body>
<h1>Hello Word!</h1>
<video id="video" width="720" height="560" autoplay muted></video>
</body>
</html>
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"weights":[{"name":"dense0/conv0/filters","shape":[3,3,3,32],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.0057930146946626555,"min":-0.7125408074435067}},{"name":"dense0/conv0/bias","shape":[32],"dtype":"float32"},{"name":"dense0/conv1/depthwise_filter","shape":[3,3,32,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.006473719839956246,"min":-0.6408982641556684}},{"name":"dense0/conv1/pointwise_filter","shape":[1,1,32,32],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010509579321917366,"min":-1.408283629136927}},{"name":"dense0/conv1/bias","shape":[32],"dtype":"float32"},{"name":"dense0/conv2/depthwise_filter","shape":[3,3,32,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.005666389652326995,"min":-0.7252978754978554}},{"name":"dense0/conv2/pointwise_filter","shape":[1,1,32,32],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010316079270605948,"min":-1.1760330368490781}},{"name":"dense0/conv2/bias","shape":[32],"dtype":"float32"},{"name":"dense0/conv3/depthwise_filter","shape":[3,3,32,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.0063220320963392074,"min":-0.853474333005793}},{"name":"dense0/conv3/pointwise_filter","shape":[1,1,32,32],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010322785377502442,"min":-1.4658355236053466}},{"name":"dense0/conv3/bias","shape":[32],"dtype":"float32"},{"name":"dense1/conv0/depthwise_filter","shape":[3,3,32,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.0042531527724920535,"min":-0.5741756242864272}},{"name":"dense1/conv0/pointwise_filter","shape":[1,1,32,64],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010653339647779278,"min":-1.1825207009035}},{"name":"dense1/conv0/bias","shape":[64],"dtype":"float32"},{"name":"dense1/conv1/depthwise_filter","shape":[3,3,64,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.005166931012097527,"min":-0.6355325144879957}},{"name":"dense1/conv1/pointwise_filter","shape":[1,1,64,64],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.011478300188101974,"min":-1.3888743227603388}},{"name":"dense1/conv1/bias","shape":[64],"dtype":"float32"},{"name":"dense1/conv2/depthwise_filter","shape":[3,3,64,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.006144821410085641,"min":-0.8479853545918185}},{"name":"dense1/conv2/pointwise_filter","shape":[1,1,64,64],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010541967317169788,"min":-1.3809977185492421}},{"name":"dense1/conv2/bias","shape":[64],"dtype":"float32"},{"name":"dense1/conv3/depthwise_filter","shape":[3,3,64,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.005769844849904378,"min":-0.686611537138621}},{"name":"dense1/conv3/pointwise_filter","shape":[1,1,64,64],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010939095534530341,"min":-1.2689350820055196}},{"name":"dense1/conv3/bias","shape":[64],"dtype":"float32"},{"name":"dense2/conv0/depthwise_filter","shape":[3,3,64,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.0037769308277204924,"min":-0.40790852939381317}},{"name":"dense2/conv0/pointwise_filter","shape":[1,1,64,128],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.01188667194516051,"min":-1.4382873053644218}},{"name":"dense2/conv0/bias","shape":[128],"dtype":"float32"},{"name":"dense2/conv1/depthwise_filter","shape":[3,3,128,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.006497045825509464,"min":-0.8381189114907208}},{"name":"dense2/conv1/pointwise_filter","shape":[1,1,128,128],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.011632198913424622,"min":-1.3377028750438316}},{"name":"dense2/conv1/bias","shape":[128],"dtype":"float32"},{"name":"dense2/conv2/depthwise_filter","shape":[3,3,128,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.005947182225246056,"min":-0.7969224181829715}},{"name":"dense2/conv2/pointwise_filter","shape":[1,1,128,128],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.011436844339557722,"min":-1.4524792311238306}},{"name":"dense2/conv2/bias","shape":[128],"dtype":"float32"},{"name":"dense2/conv3/depthwise_filter","shape":[3,3,128,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.006665432686899222,"min":-0.8998334127313949}},{"name":"dense2/conv3/pointwise_filter","shape":[1,1,128,128],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.01283421422920975,"min":-1.642779421338848}},{"name":"dense2/conv3/bias","shape":[128],"dtype":"float32"},{"name":"dense3/conv0/depthwise_filter","shape":[3,3,128,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.004711699953266218,"min":-0.6737730933170692}},{"name":"dense3/conv0/pointwise_filter","shape":[1,1,128,256],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.010955964817720302,"min":-1.3914075318504784}},{"name":"dense3/conv0/bias","shape":[256],"dtype":"float32"},{"name":"dense3/conv1/depthwise_filter","shape":[3,3,256,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.00554193468654857,"min":-0.7149095745647656}},{"name":"dense3/conv1/pointwise_filter","shape":[1,1,256,256],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.016790372250126858,"min":-2.484975093018775}},{"name":"dense3/conv1/bias","shape":[256],"dtype":"float32"},{"name":"dense3/conv2/depthwise_filter","shape":[3,3,256,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.006361540626077091,"min":-0.8142772001378676}},{"name":"dense3/conv2/pointwise_filter","shape":[1,1,256,256],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.01777329678628959,"min":-1.7062364914838006}},{"name":"dense3/conv2/bias","shape":[256],"dtype":"float32"},{"name":"dense3/conv3/depthwise_filter","shape":[3,3,256,1],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.006900275922289082,"min":-0.8625344902861353}},{"name":"dense3/conv3/pointwise_filter","shape":[1,1,256,256],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.015449936717164282,"min":-1.9003422162112067}},{"name":"dense3/conv3/bias","shape":[256],"dtype":"float32"},{"name":"fc/weights","shape":[256,7],"dtype":"float32","quantization":{"dtype":"uint8","scale":0.004834276554631252,"min":-0.7203072066400565}},{"name":"fc/bias","shape":[7],"dtype":"float32"}],"paths":["face_expression_model-shard1"]}]
Binary file not shown.
Loading

0 comments on commit f3ea0a0

Please sign in to comment.