Skip to content

Commit

Permalink
implements a task service
Browse files Browse the repository at this point in the history
  • Loading branch information
thalesbarbosab committed Jul 12, 2021
1 parent 5708b9e commit 57d2560
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 21 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@angular/platform-browser": "~8.2.13",
"@angular/platform-browser-dynamic": "~8.2.13",
"@angular/router": "~8.2.13",
"jwt-decode": "^3.1.2",
"rxjs": "~6.4.0",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
Expand Down
2 changes: 1 addition & 1 deletion src/app/account/login/login.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class LoginComponent implements OnInit {
console.log(`${result}`);
this.router.navigate(['']);
} catch (error) {
console.error(error);
alert(error);
}
}

Expand Down
35 changes: 34 additions & 1 deletion src/app/account/shared/account.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from './../../../environments/environment';
import { Injectable } from '@angular/core';
import * as jwt_decode from 'jwt-decode';

@Injectable({
providedIn: 'root'
Expand Down Expand Up @@ -33,7 +34,39 @@ export class AccountService {
return result;
}
getAuthorizationToken(){
const token = window.localStorage.getItem('token');
const token = window.localStorage.getItem('access_token');
return token;
}
getTokenExpirationDate(token: string): Date {
const decoded: any = jwt_decode.default(token);

if (decoded.exp === undefined) {
return null;
}

const date = new Date(0);
date.setUTCSeconds(decoded.exp);
return date;
}

isTokenExpired(token?: string): boolean {
if (!token) {
return true;
}
const date = this.getTokenExpirationDate(token);
if (date === undefined) {
return false;
}
return !(date.valueOf() > new Date().valueOf());
}

isUserLoggedIn() {
const token = this.getAuthorizationToken();
if (!token) {
return false;
} else if (this.isTokenExpired(token)) {
return false;
}
return true;
}
}
7 changes: 4 additions & 3 deletions src/app/account/shared/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AccountService } from './account.service';
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

Expand All @@ -6,13 +7,13 @@ import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from
})
export class AuthGuard implements CanActivate {

constructor(private router: Router){}
constructor(private router: Router,
private account_service : AccountService){}

canActivate( next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
const token = window.localStorage.getItem('access_token');
if(token){
if(this.account_service.isUserLoggedIn()){
return true;
} else {
this.router.navigate(['login']);
Expand Down
3 changes: 1 addition & 2 deletions src/app/http-interceptors/auth-interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ export class AuthInterceptor implements HttpInterceptor {
const token = this.accountService.getAuthorizationToken();
let request: HttpRequest<any> = req;

//if (token && !this.accountService.isTokenExpired(token)) {
if (token) {
if (token && !this.accountService.isTokenExpired(token)) {
// O request é imutavel, ou seja, não é possível mudar nada
// Faço o clone para conseguir mudar as propriedades
// Passo o token de autenticação no header
Expand Down
14 changes: 7 additions & 7 deletions src/app/tasks/shared/task.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import { HttpClient } from '@angular/common/http';
providedIn: 'root'
})
export class TaskService {

constructor(private http: HttpClient) { }

getAll() {
return this.http.get<Task[]>(`${environment.api}/tasks`);
return this.http.get<Task[]>(`${environment.api}/api/tasks`);
}

getById(id: string) {
return this.http.get<Task>(`${environment.api}/tasks/${id}`);
return this.http.get<Task>(`${environment.api}/api/tasks/${id}`);
}

save(task: Task) {
Expand All @@ -24,14 +24,14 @@ export class TaskService {
completed: task.completed
};

if (task._id) {
return this.http.put<Task>(`${environment.api}/tasks/${task._id}`, taskBody);
if (task.id) {
return this.http.put<Task>(`${environment.api}/api/tasks/${task.id}`, taskBody);
} else {
return this.http.post<Task>(`${environment.api}/tasks`, taskBody);
return this.http.post<Task>(`${environment.api}/api/tasks`, taskBody);
}
}

delete(id: string) {
return this.http.delete(`${environment.api}/tasks/${id}`);
return this.http.delete(`${environment.api}/api/tasks/${id}`);
}
}
2 changes: 1 addition & 1 deletion src/app/tasks/shared/task.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export class Task {
_id: string;
id: string;
description: string;
completed: boolean;
}
4 changes: 2 additions & 2 deletions src/app/tasks/task-list-item/task-list-item.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
<div [innerHTML]="task.description" class="task-item-description" [ngClass]="task.completed ? 'task-completed' : ''">
</div>
<div>
<button type="button" [routerLink]="['/edit', task._id]" class="btn btn-primary mr-1">
<button type="button" [routerLink]="['/edit', task.id]" class="btn btn-primary mr-1">
Alterar
</button>
</div>
<div>
<button type="button" class="btn btn-danger" (click)="remove(task)">
Excluir
</button>
</div>
</div>
4 changes: 2 additions & 2 deletions src/app/tasks/task-list-item/task-list-item.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ export class TaskListItemComponent implements OnInit {

@Output()
onDeleteTask = new EventEmitter()

constructor(private taskService: TaskService) { }

ngOnInit() {
}

remove(task: Task) {
this.taskService.delete(task._id).subscribe(() => {
this.taskService.delete(task.id).subscribe(() => {
this.onDeleteTask.emit(task);
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/app/tasks/task-list/task-list.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ export class TaskListComponent implements OnInit {
constructor(private taskService: TaskService) { }

ngOnInit() {
this.taskService.getAll().subscribe(tasks => {
this.taskService.getAll().subscribe(tasks => {
this.tasks = tasks;
});
}

onTaskDeleted(task: Task) {
if (task) {
const index = this.tasks.findIndex((taskItem) => taskItem._id == task._id);
const index = this.tasks.findIndex((taskItem) => taskItem.id == task.id);
this.tasks.splice(index, 1);
}
}
Expand Down

0 comments on commit 57d2560

Please sign in to comment.