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

15-02-2024 - Guardas de Rotas e validações. (authGuard e AuthService ) #23

Merged
merged 3 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
36 changes: 36 additions & 0 deletions modules/data-access/auth/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"extends": ["../../../.eslintrc.base.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "lib",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "lib",
"style": "kebab-case"
}
]
}
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions modules/data-access/auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# auth-data-access

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test auth-data-access` to execute the unit tests.
22 changes: 22 additions & 0 deletions modules/data-access/auth/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* eslint-disable */
export default {
displayName: 'auth-data-access',
preset: '../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../../coverage/modules/data-access/auth',
transform: {
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};
27 changes: 27 additions & 0 deletions modules/data-access/auth/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "auth-data-access",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "modules/data-access/auth/src",
"prefix": "lib",
"tags": ["type:data-access"],
"projectType": "library",
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "modules/data-access/auth/jest.config.ts"
}
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"modules/data-access/auth/**/*.ts",
"modules/data-access/auth/**/*.html"
]
}
}
}
}
3 changes: 3 additions & 0 deletions modules/data-access/auth/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//export * from './lib/auth-data-access/auth-data-access.component';
export * from './lib/auth/auth.service';
export * from './lib/guards/auth/auth.guard';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>auth-data-access works!</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthDataAccessComponent } from './auth-data-access.component';

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

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AuthDataAccessComponent],
}).compileComponents();

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

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
selector: 'lib-auth-data-access',
standalone: true,
imports: [CommonModule],
templateUrl: './auth-data-access.component.html',
styleUrl: './auth-data-access.component.css',
})
export class AuthDataAccessComponent {}
16 changes: 16 additions & 0 deletions modules/data-access/auth/src/lib/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { AuthService } from './auth.service';

describe('AuthService', () => {
let service: AuthService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
14 changes: 14 additions & 0 deletions modules/data-access/auth/src/lib/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class AuthService {
private emailSubject = new BehaviorSubject<string | null>(null);
email$ = this.emailSubject.asObservable();

setEmail(email: string): void {
this.emailSubject.next(email);
}
}
35 changes: 35 additions & 0 deletions modules/data-access/auth/src/lib/guards/auth/auth.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AuthService, authGuard } from 'auth-data-access';
import { of } from 'rxjs';

describe('authGuard', () => {
it('should return true when user is not truthy', () => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
});

TestBed.overrideProvider(AuthService, {
useValue: { email$: of(null) },
});

const guard = TestBed.runInInjectionContext(authGuard());
guard.subscribe((isActivated) => {
expect(isActivated).toBe(true);
});
});

it('should not return true when user is truthy', () => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
});

TestBed.overrideProvider(AuthService, {
useValue: { email$: of('[email protected]') },
});
const guard = TestBed.runInInjectionContext(authGuard());
guard.subscribe((isActivated) => {
expect(isActivated).not.toBe(true);
});
});
});
15 changes: 15 additions & 0 deletions modules/data-access/auth/src/lib/guards/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../auth/auth.service';
import { map } from 'rxjs';

export function authGuard() {
return () => {
const router = inject(Router);
const email$ = inject(AuthService).email$;

return email$.pipe(
map((email) => (!email ? true : router.createUrlTree(['/'])))
);
};
}
8 changes: 8 additions & 0 deletions modules/data-access/auth/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @ts-expect-error https://thymikee.github.io/jest-preset-angular/docs/getting-started/test-environment
globalThis.ngJest = {
testEnvironmentOptions: {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
},
};
import 'jest-preset-angular/setup-jest';
29 changes: 29 additions & 0 deletions modules/data-access/auth/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"extends": "../../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
17 changes: 17 additions & 0 deletions modules/data-access/auth/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": []
},
"exclude": [
"src/**/*.spec.ts",
"src/test-setup.ts",
"jest.config.ts",
"src/**/*.test.ts"
],
"include": ["src/**/*.ts"]
}
16 changes: 16 additions & 0 deletions modules/data-access/auth/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"target": "es2016",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
</mat-form-field>

<div class="container">
<button mat-button color="primary">Entrar</button>
<button mat-button color="primary" (click)="login()">Entrar</button>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { AuthFormComponent } from '../auth-form.component';
import { ReactiveFormsModule } from '@angular/forms';
import { AuthService } from 'modules/data-access/auth/src/lib/auth/auth.service';
import { Router } from '@angular/router';

@Component({
selector: 'lib-auth-form-password',
Expand All @@ -13,5 +15,13 @@ import { ReactiveFormsModule } from '@angular/forms';
styleUrl: './auth-form-password.component.scss',
})
export class AuthFormPasswordComponent {
email = inject(AuthFormComponent).form.controls.email.value;
control = inject(AuthFormComponent).form.controls.password;
authService = inject(AuthService);
router = inject(Router);

login(): void {
this.authService.setEmail(this.email);
this.router.navigate(['/']);
}
}
2 changes: 2 additions & 0 deletions modules/feature/auth/form/src/lib/lib.routes.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Route } from '@angular/router';
import { AuthFormComponent } from './auth-form/auth-form.component';
import { authGuard } from 'auth-data-access';

export const authFormRoutes: Route[] = [
{
path: '',
canActivate: [authGuard()],
component: AuthFormComponent,
children: [
{
Expand Down
9 changes: 6 additions & 3 deletions src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
<lib-header title="Ecommerce">
<lib-product-search></lib-product-search>
<lib-cart [quantity]="cartService.productQuantity$ | async"
>Fazer Login</lib-cart
>
<div>
<a routerLink="/auth">Fazer Login</a>
<lib-cart [quantity]="cartService.productQuantity$ | async"
>Carrinho de Compras</lib-cart
>
</div>
</lib-header>
<router-outlet></router-outlet>
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {
"auth-data-access": ["modules/data-access/auth/src/index.ts"],
"auth-form": ["modules/feature/auth/form/src/index.ts"],
"home": ["modules/feature/home/src/index.ts"],
"modules/layout": ["modules/feature/src/index.ts"],
Expand Down
Loading