Pagina roles

pull/3/head
Alvaro Puente Mella 2024-05-30 18:38:13 +02:00
parent fdf8659eea
commit 4ba44781cd
15 changed files with 319 additions and 51 deletions

View File

@ -28,6 +28,8 @@ import {MatTableModule} from '@angular/material/table';
import {MatDialogModule} from '@angular/material/dialog';
import { DeleteUserModalComponent } from './components/pages/admin/users/users/delete-user-modal/delete-user-modal.component';
import { AddUserModalComponent } from './components/pages/admin/users/users/add-user-modal/add-user-modal.component';
import {MatSelectModule} from '@angular/material/select';
import { EditUserModalComponent } from './components/pages/admin/users/users/edit-user-modal/edit-user-modal.component';
@NgModule({ declarations: [
@ -42,7 +44,8 @@ import { AddUserModalComponent } from './components/pages/admin/users/users/add-
UsersComponent,
RolesComponent,
DeleteUserModalComponent,
AddUserModalComponent
AddUserModalComponent,
EditUserModalComponent
],
bootstrap: [AppComponent],
imports: [BrowserModule,
@ -60,7 +63,8 @@ import { AddUserModalComponent } from './components/pages/admin/users/users/add-
MatInputModule,
MatListModule,
MatTableModule,
MatDialogModule],
MatDialogModule,
MatSelectModule],
providers: [
{
provide: HTTP_INTERCEPTORS,

View File

@ -14,7 +14,7 @@
<button mat-flat-button color="primary">Calendario</button>
<button mat-flat-button color="primary">Ayuda</button>
<button mat-flat-button color="accent" routerLink="/admin">Admin</button>
<button mat-flat-button color="warn">Salir</button>
<button mat-flat-button color="warn" routerLink="/auth/login">Salir</button>
</div>
</mat-toolbar>

View File

@ -0,0 +1,16 @@
table {
width: 100%;
margin-top: 50px;
}
.header-container {
margin-top: 16px;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.header-container h1 {
margin: 0;
}

View File

@ -1,6 +1,24 @@
<h2>Lista de Roles</h2>
<ul>
<li>Rol 1: Administrador</li>
<li>Rol 2: Editor</li>
<li>Rol 3: Visitante</li>
</ul>
<div class="header-container">
<h1>Gestión de roles</h1>
<button mat-flat-button color="primary">+ Añadir</button>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 demo-table">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let role"> {{ column.cell(role) }} </td>
</ng-container>
<!-- Botones Column -->
<ng-container >
<th mat-header-cell *matHeaderCellDef> Acciones </th>
<td mat-cell *matCellDef="let role">
<button mat-button color="primary" >Editar</button>
<button mat-button color="warn" >Eliminar</button>
</td>
</ng-container>
<!-- Row definition -->
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

View File

@ -1,10 +1,57 @@
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { RoleService } from './roles.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatDialog } from '@angular/material/dialog';
@Component({
selector: 'app-roles',
templateUrl: './roles.component.html',
styleUrl: './roles.component.css'
styleUrls: ['./roles.component.css']
})
export class RolesComponent {
export class RolesComponent implements OnInit {
dataSource = new MatTableDataSource<any>();
columns = [
{
columnDef: 'id',
header: 'ID',
cell: (role: any) => `${role.id}`
},
{
columnDef: 'name',
header: 'Nombre',
cell: (role: any) => `${role.name}`
},
{
columnDef: 'permissions',
header: 'Permisos',
cell: (role: any) => `${role.permissions.join(', ')}`
}
];
displayedColumns = [...this.columns.map(column => column.columnDef)];
constructor(private roleService: RoleService, public dialog: MatDialog) {}
ngOnInit() {
this.loadRoles();
}
loadRoles() {
this.roleService.getRoles().subscribe(response => {
console.log(response);
this.dataSource.data = response['hydra:member'];
});
}
/* deleteRole(role: any) {
const dialogRef = this.dialog.open(DeleteRoleModalComponent, {
data: role
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.loadRoles();
}
});
} */
}

View File

@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Role {
'@id': string;
name: string;
permissions: string[];
}
@Injectable({
providedIn: 'root'
})
export class RoleService {
private apiUrl = 'http://127.0.0.1:8080';
constructor(private http: HttpClient) {}
getRoles(): Observable<{ 'hydra:member': Role[] }> {
return this.http.get<{ 'hydra:member': Role[] }>(`${this.apiUrl}/user-groups?page=1&itemsPerPage=30`);
}
}

View File

@ -9,21 +9,15 @@
<mat-label>Contraseña</mat-label>
<input matInput formControlName="password" required>
</mat-form-field>
<p>Roles:</p>
<div class="checkbox-group" required>
<label>
<input type="checkbox" formControlName="ROLE_SUPER_ADMIN" > Super Administrador
</label>
<label>
<input type="checkbox" formControlName="ROLE_ORGANIZATIONAL_UNIT_ADMIN"> Administrador de Aula
</label>
<label>
<input type="checkbox" formControlName="ROLE_ORGANIZATIONAL_UNIT_OPERATOR"> Operador de Aula
</label>
<label>
<input type="checkbox" formControlName="ROLE_USER"> Usuario
</label>
</div>
<mat-form-field appearance="fill">
<mat-label>Rol</mat-label>
<mat-select formControlName="role">
<mat-option *ngFor="let group of userGroups" [value]="group['@id']">
{{ group.name }}
</mat-option>
</mat-select>
</mat-form-field>
</form>
</div>
<div mat-dialog-actions>

View File

@ -1,54 +1,60 @@
import { Component, EventEmitter, Inject, Output } from '@angular/core';
import { Component, EventEmitter, Inject, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../users.service';
interface UserGroup {
'@id': string;
name: string;
role: string[];
}
@Component({
selector: 'app-add-user-modal',
templateUrl: './add-user-modal.component.html',
styleUrls: ['./add-user-modal.component.css']
})
export class AddUserModalComponent {
export class AddUserModalComponent implements OnInit {
@Output() userAdded = new EventEmitter<void>();
userForm: FormGroup;
userGroups: UserGroup[] = [];
constructor(
public dialogRef: MatDialogRef<AddUserModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private fb: FormBuilder,
private http: HttpClient
private userService: UserService // Inyecta el servicio
) {
this.userForm = this.fb.group({
username: ['', Validators.required],
password: ['', Validators.required],
ROLE_SUPER_ADMIN: [false],
ROLE_ORGANIZATIONAL_UNIT_ADMIN: [false],
ROLE_ORGANIZATIONAL_UNIT_OPERATOR: [false],
ROLE_USER: [false]
role: ['', Validators.required], // Control para el permiso seleccionado
});
}
ngOnInit(): void {
this.userService.getUserGroups().subscribe((data) => {
this.userGroups = data['hydra:member'];
});
}
onNoClick(): void {
this.dialogRef.close();
}
onSubmit(): void {
if (this.userForm.valid) {
const apiUrl = 'http://127.0.0.1:8080/api/users';
const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3MTY5OTI4OTgsImV4cCI6MTcxNjk5NjQ5OCwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoib2dhZG1pbiJ9.dtEsBpYvEbkLLHTfMVvCdK5IMTUJWU7JoE8GIibeA3ltAdS1n-YgOeCplxRJMl5CmktNHeS7mE40u-RGb9ly7zifctK8N7z0uv8Q70nFsq3DBqUDVONusXzdSKABAq7_WIhBPfQBJpG0uzlPMEL9sfch9lvNWOX0k7dE2aLa54ucBrGaR-9p1HEFlQIzlWXkqjmzTDq6PoaRAATUZQXnh95rf8w57O07NylC1SXUfaWGJwdBhTNCfEuSsnhE5fOrBiga2oAOqHM7JgMb4lKDx4TNqrY1YZi0pSvJeD6r7j-ELeSVHgaPzdJeQTFUt0T87ca-GFqjBfUKu-z76c5bBg';
const headers = new HttpHeaders({
'Content-Type': 'application/ld+json',
'Authorization': `Bearer ${token}`
});
const userPayload = {
username: this.userForm.value.username,
allowedOrganizationalUnits: [],
password: this.userForm.value.password,
enabled: true,
userGroups: [this.userForm.value.role ]
};
this.http.post(apiUrl, userPayload, { headers: headers }).subscribe(
this.userService.addUser(userPayload).subscribe(
response => {
console.log('User playload:', userPayload);
console.log('User added successfully:', response);
this.userAdded.emit();
this.dialogRef.close(this.userForm.value);

View File

@ -20,8 +20,7 @@ export class DeleteUserModalComponent {
}
onYesClick(): void {
const apiUrl = `http://127.0.0.1:8080/api/users/${this.data.uuid}`;
const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3MTY5OTI4OTgsImV4cCI6MTcxNjk5NjQ5OCwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoib2dhZG1pbiJ9.dtEsBpYvEbkLLHTfMVvCdK5IMTUJWU7JoE8GIibeA3ltAdS1n-YgOeCplxRJMl5CmktNHeS7mE40u-RGb9ly7zifctK8N7z0uv8Q70nFsq3DBqUDVONusXzdSKABAq7_WIhBPfQBJpG0uzlPMEL9sfch9lvNWOX0k7dE2aLa54ucBrGaR-9p1HEFlQIzlWXkqjmzTDq6PoaRAATUZQXnh95rf8w57O07NylC1SXUfaWGJwdBhTNCfEuSsnhE5fOrBiga2oAOqHM7JgMb4lKDx4TNqrY1YZi0pSvJeD6r7j-ELeSVHgaPzdJeQTFUt0T87ca-GFqjBfUKu-z76c5bBg';
const apiUrl = `http://127.0.0.1:8080/users/${this.data.uuid}`;
const headers = new HttpHeaders({
'Content-Type': 'application/ld+json'
});

View File

@ -0,0 +1,10 @@
.user-form .form-field {
display: block;
margin-bottom: 10px; /* Puedes ajustar el valor para cambiar la separación */
}
.checkbox-group label {
display: block;
margin-bottom: 8px; /* Ajusta este valor según necesites */
}

View File

@ -0,0 +1,26 @@
<h1 mat-dialog-title>Editar Usuario</h1>
<div mat-dialog-content>
<form [formGroup]="userForm" class="user-form">
<mat-form-field class="form-field">
<mat-label>Nombre de usuario</mat-label>
<input matInput formControlName="username">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Contraseña</mat-label>
<input matInput formControlName="password" >
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Rol</mat-label>
<mat-select formControlName="role">
<mat-option *ngFor="let group of userGroups" [value]="group['@id']">
{{ group.name }}
</mat-option>
</mat-select>
</mat-form-field>
</form>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancelar</button>
<button mat-button (click)="onSubmit()">Editar</button>
</div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EditUserModalComponent } from './edit-user-modal.component';
describe('EditUserModalComponent', () => {
let component: EditUserModalComponent;
let fixture: ComponentFixture<EditUserModalComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [EditUserModalComponent]
})
.compileComponents();
fixture = TestBed.createComponent(EditUserModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,66 @@
import { Component, EventEmitter, Inject, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UserService } from '../users.service';
interface UserGroup {
'@id': string;
name: string;
role: string[];
}
@Component({
selector: 'app-edit-user-modal',
templateUrl: './edit-user-modal.component.html',
styleUrls: ['./edit-user-modal.component.css']
})
export class EditUserModalComponent implements OnInit {@Output() userEdited = new EventEmitter<void>();
userForm: FormGroup;
userGroups: UserGroup[] = [];
constructor(
public dialogRef: MatDialogRef<EditUserModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private fb: FormBuilder,
private userService: UserService // Inyecta el servicio
) {
this.userForm = this.fb.group({
username: [this.data.user.username],
password: [''],
role: this.data.user.allowedOrganizationalUnits, // Control para el permiso seleccionado
});
}
ngOnInit(): void {
this.userService.getUserGroups().subscribe((data) => {
this.userGroups = data['hydra:member'];
});
}
onNoClick(): void {
this.dialogRef.close();
}
onSubmit(): void {
const userPayload = {
username: this.userForm.value.username,
allowedOrganizationalUnits: [],
password: this.userForm.value.password,
enabled: true,
userGroups: [this.userForm.value.role ]
};
this.userService.updateUser(this.data.user.uuid, userPayload).subscribe(
response => {
console.log('User added successfully:', response);
this.userEdited.emit();
this.dialogRef.close(this.userForm.value);
},
error => {
console.error('Error adding user:', error);
// Agregar alguna lógica para manejar el error en la interfaz de usuario
}
);
}
}

View File

@ -4,6 +4,7 @@ import { MatTableDataSource } from '@angular/material/table';
import { DeleteUserModalComponent } from './delete-user-modal/delete-user-modal.component';
import { MatDialog } from '@angular/material/dialog';
import { AddUserModalComponent } from './add-user-modal/add-user-modal.component';
import { EditUserModalComponent } from './edit-user-modal/edit-user-modal.component';
@Component({
selector: 'app-users',
@ -59,7 +60,12 @@ export class UsersComponent implements OnInit {
editUser(user: any) {
// Implementar la lógica de edición
console.log('Editar usuario:', user);
const dialogRef = this.dialog.open(EditUserModalComponent, {
data: { user: user }
});
dialogRef.componentInstance.userEdited.subscribe(() => {
this.loadUsers();
});
}
deleteUser(user: any) {

View File

@ -2,17 +2,47 @@ import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
interface UserPayload {
username: string;
password: string;
enabled: boolean;
userGroups: string[];
allowedOrganizationalUnits: any[];
}
interface UserGroup {
'@id': string;
name: string;
role: string[];
}
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'http://127.0.0.1:8080';
private userApiUrl = 'http://127.0.0.1:8080/api/users';
constructor(private http: HttpClient) {}
constructor(private http: HttpClient) { }
addUser(userPayload: UserPayload): Observable<any> {
const headers = new HttpHeaders({
'Content-Type': 'application/ld+json',
});
return this.http.post(`${this.apiUrl}/users`, userPayload, { headers });
}
updateUser(userId: number, userPayload: UserPayload): Observable<any> {
const headers = new HttpHeaders({
'Content-Type': 'application/ld+json',
});
return this.http.put(`${this.apiUrl}/users/${userId}`, userPayload, { headers });
}
getUserGroups(): Observable<{ 'hydra:member': UserGroup[] }> {
return this.http.get<{ 'hydra:member': UserGroup[] }>(`${this.apiUrl}/user-groups`);
}
getUsers(): Observable<any> {
return this.http.get<any>(this.userApiUrl+'?page=1&itemsPerPage=30');
return this.http.get<any>(`${this.apiUrl}/users?page=1&itemsPerPage=30`);
}
}