Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

59 admin crud #9

Merged
merged 21 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
"private": true,
"dependencies": {
"@angular/animations": "^15.2.0",
"@angular/cdk": "^15.2.9",
"@angular/common": "^15.2.0",
"@angular/compiler": "^15.2.0",
"@angular/core": "^15.2.0",
"@angular/forms": "^15.2.0",
"@angular/material": "^15.2.9",
"@angular/platform-browser": "^15.2.0",
"@angular/platform-browser-dynamic": "^15.2.0",
"@angular/router": "^15.2.0",
Expand Down
4 changes: 3 additions & 1 deletion src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { CheckCodeRestPasswordComponent } from './pages/check-code-rest-password
import { ResetPasswordComponent } from './pages/reset-password/reset-password.component';
import { AuthGuard } from './services/auth.guard';
import { EditUserComponent } from './pages/edit-user/edit-user.component';
import { UpdateRoleComponent } from './pages/update-role/update-role.component';

const routes: Routes = [
{ path: 'login', component: LoginComponent },
Expand All @@ -24,7 +25,8 @@ const routes: Routes = [
{ path: 'changePassword', component: ResetPasswordComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard], },
{ path: 'editUser/:id', component: EditUserComponent, canActivate: [AuthGuard], },
{ path: '', component: HomePageComponent, canActivate: [AuthGuard], }
{ path: 'update-role', component: UpdateRoleComponent, canActivate: [AuthGuard], data:{roles:["ADMIN"]} },
{ path: '', component: HomePageComponent, canActivate: [AuthGuard], },
];

@NgModule({
Expand Down
9 changes: 8 additions & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
Expand All @@ -22,6 +22,9 @@ import { CheckCodeRestPasswordComponent } from './pages/check-code-rest-password
import { AuthGuard } from './services/auth.guard';
import { AuthService } from './services/auth.service';
import { EditUserComponent } from './pages/edit-user/edit-user.component';
import { UpdateRoleComponent } from './pages/update-role/update-role.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatPaginatorModule} from '@angular/material/paginator';

@NgModule({
declarations: [
Expand All @@ -40,13 +43,17 @@ import { EditUserComponent } from './pages/edit-user/edit-user.component';
ResetPasswordComponent,
CheckCodeRestPasswordComponent,
EditUserComponent,
UpdateRoleComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ReactiveFormsModule,
HttpClientModule,
FormsModule,
BrowserAnimationsModule,
MatPaginatorModule
],
providers: [
AuthGuard,
Expand Down
2 changes: 2 additions & 0 deletions src/app/pages/profile/profile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { NavigationExtras, Router } from '@angular/router';
import { UserService } from 'src/app/services/user.service';
import jwt_decode from 'jwt-decode';


@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
Expand Down Expand Up @@ -33,6 +34,7 @@ export class ProfileComponent {
this.userService.getUser(this.userId).subscribe({
next: (data) => {
console.log(data);
localStorage.setItem('role', data.role);
this.user = data;
},
error: (error) => {
Expand Down
39 changes: 39 additions & 0 deletions src/app/pages/update-role/update-role.component.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
table {
border-collapse: collapse;
width: 100%;
border: 1px solid #ccc;
}


th {
background-color: #f2f2f2;
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}


tr:nth-child(even) {
background-color: #f2f2f2;
}

tr:nth-child(odd) {
background-color: #ffffff;
}


td {
border: 1px solid #ccc;
padding: 8px;
}


tr:hover {
background-color: #e0e0e0;
}

.filter-container {
display: flex;
align-items: flex-start;
column-gap: 6px;
}
66 changes: 66 additions & 0 deletions src/app/pages/update-role/update-role.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<div class="mx-5">
<div class="filter-container">
<div>
<label>Nome ou Email:</label>
<input
[(ngModel)]="filterInputValue"
(change)="filterUser()"
placeholder="Filtrar pelo nome do usuário"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-100 p-2.5 outline-none"
/>
</div>
<div>
<label>Vínculo:</label>
<select
(change)="filterUser()"
[(ngModel)]="filterConnectionValue"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-100 p-2.5 outline-none"
>
<option disabled hidden value="">Selecione um vínculo</option>
<option value="ALUNO">Aluno</option>
<option value="PROFESSOR">Professor</option>
<option value="COMUNIDADE">Comunidade</option>
<option value="EXTERNO">Externo</option>
</select>
</div>
</div>
<table class="table-auto mt-3" style="border-collapse: collapse !important;" >
<thead>
<tr>
<th>Nome</th>
<th>Email</th>
<th>Vínculo</th>
<th>Cargo</th>
<th>Ativo</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.connection }}</td>
<td>
<select
class="bg-gray-100 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 outline-none"
[(ngModel)]="user.role"
(change)="updateUserRole(user.id)" *ngIf="user.id !== userId; else readOnly"
>
<option value="USER">Usuário</option>
<option value="ADMIN">Administrador</option>
</select>
<ng-template #readOnly>
Administrador
</ng-template>
</td>
<td>{{ user.is_active ? "Sim" : "Não" }}</td>
</tr>
</tbody>
</table>
<mat-paginator
[length]="total"
[pageSize]="pageSize"
[pageSizeOptions]="[5, 10, 25]"
aria-label="User Pagination"
(page)="onPaginateChange($event)"
></mat-paginator>
</div>
23 changes: 23 additions & 0 deletions src/app/pages/update-role/update-role.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { UpdateRoleComponent } from './update-role.component';

describe('UpdateRoleComponent', () => {
let component: UpdateRoleComponent;
let fixture: ComponentFixture<UpdateRoleComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ UpdateRoleComponent ]
})
.compileComponents();

fixture = TestBed.createComponent(UpdateRoleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
80 changes: 80 additions & 0 deletions src/app/pages/update-role/update-role.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { UserService } from './../../services/user.service';
import { Component } from '@angular/core';
import { PageEvent } from '@angular/material/paginator';
import jwt_decode from 'jwt-decode';

@Component({
selector: 'app-update-role',
templateUrl: './update-role.component.html',
styleUrls: ['./update-role.component.css'],
})
export class UpdateRoleComponent {
users: any = [];
userId: number = 0;

filterInputValue: string = "";
filterConnectionValue: string = ""

total: number = 0;
pageSize: number = 10;
pageIndex: number = 0;

constructor(private userService: UserService) {}

ngOnInit(): void {
this.getUserid();
this.getAllUsers();
};

updateUserRole(id: number) {
this.userService.updateUserRole(id).subscribe({
next: (data) => {
console.log(data);
},
error: (erro) => {
console.error('Erro', erro);
},
});
};

getUserid() {
const decodedToken: any = jwt_decode(
localStorage.getItem('token') as string
);
this.userId = decodedToken.id;
};

filterUser() {
this.getAllUsers()
};

onPaginateChange(event: PageEvent) {
this.pageSize = event.pageSize;
this.pageIndex = event.pageIndex;

this.getAllUsers();
};

getAllUsers() {
this.userService.getAllUsers({
nameEmail: this.filterInputValue,
connection: this.filterConnectionValue,
limit: this.pageSize,
offset: (this.pageIndex * this.pageSize)
}).subscribe({
next: (data: Response) => {
this.users = data.body;
if (data.headers.has("x-total-count")) {
const totalCountHeader = data.headers.get("x-total-count");

if (totalCountHeader !== null) {
this.total = Number.parseInt(totalCountHeader, 10);
}
}
},
error: (erro) => {
console.error('Erro', erro);
},
});
}
}
12 changes: 10 additions & 2 deletions src/app/services/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { ActivatedRouteSnapshot, CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
Expand All @@ -9,8 +9,16 @@ import { AuthService } from './auth.service';
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(): boolean {
canActivate(route:ActivatedRouteSnapshot): boolean {
const roles: string[]= route.data?.roles;
console.log(roles)
const role = localStorage.getItem("role") || ""
console.log(role)
if (this.authService.isAuthenticated()) {
if (roles) {

return roles.includes(role)
}
return true;
} else {
this.router.navigate(['/login']);
Expand Down
29 changes: 27 additions & 2 deletions src/app/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ import { environment } from '../environment/environment';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

interface IGetAllUsers {
name?: string;
email?: string;
nameEmail?: string;
connection?: string;
offset?: number;
limit?: number;
}

@Injectable({
providedIn: 'root'
})
Expand All @@ -15,8 +24,20 @@ export class UserService {
return this.http.get(`${this.apiURL}/users/${id}`);
}

getAllUsers(): Observable<any> {
return this.http.get(`${this.apiURL}/users`);
getAllUsers({ name, email, nameEmail, connection, offset, limit }: IGetAllUsers): Observable<any> {
const params = {
...(name && { name__like: name }),
...(email && { email__like: email }),
...(nameEmail && { name_or_email: nameEmail }),
...(connection && { connection }),
...(offset && { offset: offset.toString() }),
...(limit && { limit: limit.toString() }),
};

const searchParams = new URLSearchParams(params);
const queryString = searchParams.toString();

return this.http.get(`${this.apiURL}/users${queryString && '?' + queryString}`, {observe: 'response'});
}

updateUser(id: any, body: any): Observable<any> {
Expand All @@ -26,4 +47,8 @@ export class UserService {
deleteUser(id: any): Observable<any> {
return this.http.delete(`${this.apiURL}/users/${id}`);
}

updateUserRole(id: any): Observable<any> {
return this.http.patch(`${this.apiURL}/users/role/${id}`, {});
}
}
3 changes: 3 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<app-root></app-root>
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noPropertyAccessFromIndexSignature": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
Expand Down