Skip to content

Commit

Permalink
changed users microservice permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
guipeeix7 committed Jan 12, 2025
1 parent 660245b commit 485bdb5
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 67 deletions.
2 changes: 1 addition & 1 deletion src/Pages/Protected/Organ/ListOrgan/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function OrganList() {
const [organs, setOrgans] = useState([]);
const navigate = useNavigate();

const canCreate = checkAction(permissions,"create");
const canCreate = checkAction(permissions,"orgaos_criar");
useEffect(() => {
const getOrgansInfo = async () => {
const response = await listOrgans();
Expand Down
4 changes: 2 additions & 2 deletions src/Pages/Protected/Organ/OrganUpdate/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export const OrganId = () => {
const organsId = state?.organsId;
const navigate = useNavigate();
const permissions = usePermissions();
const canUpdate = checkAction(permissions, "update");
const canDelete = checkAction(permissions, "delete");
const canUpdate = checkAction(permissions, "orgaos_editar");
const canDelete = checkAction(permissions, "orgaos_deletar");

const [openSave, setOpenSave] = useState(false);
const [openDeleteOrgan, setOpenDeleteOrgan] = useState(false);
Expand Down
90 changes: 60 additions & 30 deletions src/Pages/Protected/Permissions/permissionsHandler.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Box, Button, TextField, Typography, Table, TableBody, TableCell, TableC
import { Delete, Edit, Search } from '@mui/icons-material';

Check failure on line 4 in src/Pages/Protected/Permissions/permissionsHandler.jsx

View workflow job for this annotation

GitHub Actions / lint

'Search' is defined but never used
import { APIUsers } from "./../../../Services/BaseService/index";
import { getToken, getUser } from "./../../../Services/Functions/loader";

Check failure on line 6 in src/Pages/Protected/Permissions/permissionsHandler.jsx

View workflow job for this annotation

GitHub Actions / lint

'getUser' is defined but never used
import { checkAction } from '../../../Utils/permission';


const PermissionCRUD = () => {
Expand All @@ -13,13 +14,23 @@ const PermissionCRUD = () => {
const [search, setSearch] = useState("");

Check failure on line 14 in src/Pages/Protected/Permissions/permissionsHandler.jsx

View workflow job for this annotation

GitHub Actions / lint

'setSearch' is assigned a value but never used
const [editId, setEditId] = useState(null);

const canCreate = checkAction(permissions, "permissoes_criar");
const canUpdate = checkAction(permissions, "permissoes_editar");
const canDelete = checkAction(permissions, "permissoes_deletar");
const canView = checkAction(permissions, "permissoes_visualizar");

Check failure on line 20 in src/Pages/Protected/Permissions/permissionsHandler.jsx

View workflow job for this annotation

GitHub Actions / lint

'canView' is assigned a value but never used

useEffect(() => {
fetchPermissions();
}, []);

const fetchPermissions = async () => {
try {
const response = await APIUsers.get('permission');
const response = await APIUsers.get('permission',
{
headers: {
Authorization: `Bearer ${getToken()}`,
}
});
setPermissions(response.data);
} catch (error) {
console.error('Error fetching permissions:', error);
Expand All @@ -30,7 +41,12 @@ const PermissionCRUD = () => {
e.preventDefault();
try {
if (editId) {
await APIUsers.patch(`permission/patch/${editId}`, form);
await APIUsers.patch(`permission/patch/${editId}`, form,
{
headers: {
Authorization: `Bearer ${getToken()}`,
}
});
} else {
await APIUsers.post('permission/create/', form);
}
Expand All @@ -49,7 +65,12 @@ const PermissionCRUD = () => {

const handleDelete = async (id) => {
try {
await APIUsers.delete(`permission/delete/${id}`);
await APIUsers.delete(`permission/delete/${id}`,
{
headers: {
Authorization: `Bearer ${getToken()}`,
}
});
fetchPermissions();
} catch (error) {
console.error('Error deleting permission:', error);
Expand All @@ -58,11 +79,13 @@ const PermissionCRUD = () => {

const handleSearch = async () => {

Check failure on line 80 in src/Pages/Protected/Permissions/permissionsHandler.jsx

View workflow job for this annotation

GitHub Actions / lint

'handleSearch' is assigned a value but never used
try {
const response = await APIUsers.get(`permissions/search`,
{ name: searchQuery },
{headers: {
Authorization: `Bearer ${getToken()}`,
}}
const response = await APIUsers.get(`permissions/search`,
{ name: searchQuery },
{
headers: {
Authorization: `Bearer ${getToken()}`,
}
}
);
setPermissions(response.data);
} catch (error) {
Expand All @@ -79,40 +102,47 @@ const PermissionCRUD = () => {
<Typography variant="h4" gutterBottom>
Permission Management
</Typography>
{canCreate && (

<Box component="form" onSubmit={handleSubmit} sx={{ marginBottom: 4 }}>
<TextField
label="Permission Name"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
fullWidth
margin="normal"
/>
<Button sx={{ backgroundColor: '#ae883c', '&:hover': { backgroundColor: '#936d30' }}} type="submit" variant="contained" color="primary">
{editId ? 'Atualizar Permissão' : 'Criar Permissão'}
</Button>
</Box>

<Box component="form" onSubmit={handleSubmit} sx={{ marginBottom: 4 }}>
<TextField
label="Permission Name"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
fullWidth
margin="normal"
/>
<Button sx={{ backgroundColor: '#ae883c', '&:hover': { backgroundColor: '#936d30' } }} type="submit" variant="contained" color="primary">
{editId ? 'Atualizar Permissão' : 'Criar Permissão'}
</Button>
</Box>
)}
<TableContainer component={Paper}>
<Table sx={{ backgroundColor: '#eae3d7', '&:hover': { backgroundColor: '#eae3d7' }}}>
<Table sx={{ backgroundColor: '#eae3d7', '&:hover': { backgroundColor: '#eae3d7' } }}>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Actions</TableCell>
{(canUpdate || canDelete) && (
<TableCell>Actions</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{filteredPermissions.map((permission, index) => (
<TableRow key={permission._id}>
<TableCell>{permission.name}</TableCell>
<TableCell>
<IconButton color="primary" onClick={() => handleEdit(permission)}>
<Edit />
</IconButton>
<IconButton color="error" onClick={() => handleDelete(permission._id)}>
<Delete />
</IconButton>
{canUpdate && (
<IconButton color="primary" onClick={() => handleEdit(permission)}>
<Edit />
</IconButton>
)}
{canDelete && (
<IconButton color="error" onClick={() => handleDelete(permission._id)}>
<Delete />
</IconButton>
)}
</TableCell>
</TableRow>
))}
Expand Down
8 changes: 2 additions & 6 deletions src/Pages/Protected/Roles/RolesListPage/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ export default function RolesListPage() {
const storagedUserString = localStorage.getItem("@App:user");
const storagedUser = JSON.parse(storagedUserString);

const response = await APIUsers.get("role", {
headers: {
Authorization: `Bearer ${storagedUser.token}`,
},
});
const response = await APIUsers.get("role");

const data = response.data;
if (Array.isArray(data)) {
Expand All @@ -44,7 +40,7 @@ export default function RolesListPage() {
fetchRoleForm();
}, []);

const hasPermission = checkAction(permissions, "create");
const hasPermission = checkAction(permissions, "perfis_criar");

const handleSubmit = () => {
navigate("/perfis/criar");
Expand Down
2 changes: 1 addition & 1 deletion src/Pages/Protected/Roles/RolesUpdatePage/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export default function RolesUpdatePage() {
placeholder="Digite o nome da permissão"
/>
</div> */}

{/* Lista de permissões */}
<div className="permission-list-box">
<h3>Lista de Permissões</h3>
Expand Down
4 changes: 2 additions & 2 deletions src/Pages/Protected/Users/userUpdatePage/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ export default function UserUpdatePage() {
const [isEmailValid, setIsEmailValid] = useState(true);
const [isCelularValid, setIsCelularValid] = useState(true);

const canDelete = checkAction(permissions, "delete");
const canUpdate = checkAction(permissions, "update");
const canDelete = checkAction(permissions, "usuarios_deletar");
const canUpdate = checkAction(permissions, "usuarios_editar");

useEffect(() => {
const loadRoles = async () => {
Expand Down
11 changes: 11 additions & 0 deletions src/Services/BaseService/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import axios from "axios";
import { getToken } from "../Functions/loader";


const baseBenefitsURL =
import.meta.env.VITE_BENEFIT_DB_URL || "http://localhost:3003/";
Expand All @@ -9,14 +11,23 @@ const baseUserURL =

const APIUsers = axios.create({
baseURL: baseUserURL,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

const APIBank = axios.create({
baseURL: baseBankURL,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

const APIBenefits = axios.create({
baseURL: baseBenefitsURL,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

export { APIUsers, APIBank, APIBenefits };
6 changes: 1 addition & 5 deletions src/Services/Permissions/permissionsService.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ export const getAllPermissions = async () => {
if (!token) {
throw new Error("No token found");
}
const response = await APIUsers.get("/permission", {
headers: {
Authorization: `Bearer ${token}`,
},
});
const response = await APIUsers.get("/permission");
return response.data;
} catch (error) {
console.error("Erro ao buscar permissões:", error.response?.data || error);
Expand Down
26 changes: 6 additions & 20 deletions src/Services/RoleService/roleService.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ export const createRole = async (roleData) => {
moduleName: "users",
action: "create",
},
headers: {
Authorization: `Bearer ${token}`,
},

});
return response.data;
} catch (error) {
Expand All @@ -45,9 +43,7 @@ export const getAllRoles = async () => {
throw new Error("No token found");
}
const response = await APIUsers.get("/role", {
headers: {
Authorization: `Bearer ${token}`,
},

});
return response.data;
} catch (error) {
Expand All @@ -62,11 +58,7 @@ export const getRoleById = async (id) => {
if (!token) {
throw new Error("No token found");
}
const response = await APIUsers.get(`/role/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
const response = await APIUsers.get(`/role/${id}`, );
return response.data;
} catch (error) {
console.error("Erro ao buscar role:", error);
Expand All @@ -83,9 +75,7 @@ export const assignPermissionsToRole = async (roleId, permissions) => {
const response = await APIUsers.put(`/roles/${roleId}/permissions`, {
permissions,
}, {
headers: {
Authorization: `Bearer ${token}`,
},

});

return response.data;
Expand Down Expand Up @@ -121,9 +111,7 @@ export const updateRole = async (id, roleData) => {
moduleName: "users",
action: "update",
},
headers: {
Authorization: `Bearer ${token}`,
},

});
return response.data;
} catch (error) {
Expand Down Expand Up @@ -158,9 +146,7 @@ export const deleteRole = async (id) => {
moduleName: "users",
action: "delete",
},
headers: {
Authorization: `Bearer ${token}`,
},

});
return response.data;
} catch (error) {
Expand Down

0 comments on commit 485bdb5

Please sign in to comment.