From 7c2bc6a3dcb0d0f719f4e313edf84dafaf533229 Mon Sep 17 00:00:00 2001 From: Eneko Nieto Date: Wed, 20 Jan 2021 12:53:46 +0100 Subject: [PATCH] =?UTF-8?q?Limpieza=20de=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- angular.json | 14 +++--- src/app/app.component.spec.ts | 8 ++-- src/app/app.component.ts | 68 +--------------------------- src/app/app.module.ts | 6 +-- src/app/app.tokens.ts | 2 +- src/app/auth-no-discovery.config.ts | 69 ----------------------------- src/app/home/home.component.ts | 40 ++++++++--------- src/app/shared/auth/auth.guard.ts | 2 +- tsconfig.json | 12 +++-- 9 files changed, 48 insertions(+), 173 deletions(-) delete mode 100644 src/app/auth-no-discovery.config.ts diff --git a/angular.json b/angular.json index 4aff041..1f3c173 100644 --- a/angular.json +++ b/angular.json @@ -5,7 +5,11 @@ "projects": { "sample-oauth": { "projectType": "application", - "schematics": {}, + "schematics": { + "@schematics/angular:application": { + "strict": true + } + }, "root": "", "sourceRoot": "src", "prefix": "app", @@ -47,13 +51,13 @@ "budgets": [ { "type": "initial", - "maximumWarning": "2mb", - "maximumError": "5mb" + "maximumWarning": "1mb", + "maximumError": "2mb" }, { "type": "anyComponentStyle", - "maximumWarning": "6kb", - "maximumError": "10kb" + "maximumWarning": "2kb", + "maximumError": "4kb" } ] } diff --git a/src/app/app.component.spec.ts b/src/app/app.component.spec.ts index eca3de3..43515a4 100644 --- a/src/app/app.component.spec.ts +++ b/src/app/app.component.spec.ts @@ -1,22 +1,22 @@ -import { TestBed, async } from '@angular/core/testing'; +import { TestBed, async, waitForAsync } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { AppModule } from './app.module'; describe('AppComponent', () => { - beforeEach(async(() => { + beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [AppModule] }).compileComponents(); })); - it('should create the app', async(() => { + it('should create the app', waitForAsync(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); - it('should render link to flight in a a tag', async(() => { + it('should render link to flight in a a tag', waitForAsync(() => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 75cbb4c..451dc24 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -1,4 +1,3 @@ -import { noDiscoveryAuthConfig } from './auth-no-discovery.config'; import { Component } from '@angular/core'; import { OAuthService, NullValidationHandler } from 'angular-oauth2-oidc'; import { Router } from '@angular/router'; @@ -19,12 +18,12 @@ export class AppComponent { this.oauthService.events .pipe(filter((e) => e.type === 'token_received')) .subscribe((_) => { - console.debug('state', this.oauthService.state); + console.log('state', this.oauthService.state); this.oauthService.loadUserProfile(); }); } - private configureCodeFlow() { + private configureCodeFlow(): void { this.oauthService.configure(authCodeFlowConfig); this.oauthService.loadDiscoveryDocumentAndTryLogin().then((_) => { if (useHash) { @@ -35,67 +34,4 @@ export class AppComponent { // Optional this.oauthService.setupAutomaticSilentRefresh(); } - - // - // Below you find further examples for configuration functions - // - - private configureWithoutDiscovery() { - this.oauthService.configure(noDiscoveryAuthConfig); - this.oauthService.tokenValidationHandler = new NullValidationHandler(); - this.oauthService.tryLogin(); - } - - private configureAuth() { - // - // This method demonstrated the old API; see configureWithNewConfigApi for new one - // - - // URL of the SPA to redirect the user to after login - this.oauthService.redirectUri = window.location.origin + '/index.html'; - - // URL of the SPA to redirect the user after silent refresh - this.oauthService.silentRefreshRedirectUri = - window.location.origin + '/silent-refresh.html'; - - // The SPA's id. The SPA is registerd with this id at the auth-server - this.oauthService.clientId = 'spa-demo'; - - // set the scope for the permissions the client should request - // The first three are defined by OIDC. The 4th is a usecase-specific one - this.oauthService.scope = 'openid profile email voucher'; - - // Url of the Identity Provider - this.oauthService.issuer = - 'https://steyer-identity-server.azurewebsites.net/identity'; - - this.oauthService.tokenValidationHandler = new NullValidationHandler(); - - this.oauthService.events.subscribe((e) => { - // tslint:disable-next-line:no-console - console.debug('oauth/oidc event', e); - }); - - // Load Discovery Document and then try to login the user - this.oauthService.loadDiscoveryDocument().then((doc) => { - this.oauthService.tryLogin(); - }); - - this.oauthService.events - .pipe(filter((e) => e.type === 'token_expires')) - .subscribe((e) => { - // tslint:disable-next-line:no-console - console.debug('received token_expires event', e); - this.oauthService.silentRefresh(); - }); - } - - private configurePasswordFlow() { - // Set a dummy secret - // Please note that the auth-server used here demand the client to transmit a client secret, although - // the standard explicitly cites that the password flow can also be used without it. Using a client secret - // does not make sense for a SPA that runs in the browser. That's why the property is called dummyClientSecret - // Using such a dummy secreat is as safe as using no secret. - this.oauthService.dummyClientSecret = 'geheim'; - } } diff --git a/src/app/app.module.ts b/src/app/app.module.ts index a0c4c38..d92cb77 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -15,7 +15,7 @@ import { useHash } from '../flags'; const ROUTING_OPTIONS: ExtraOptions = { // preloadingStrategy: CustomPreloadingStrategy, - useHash: useHash, + useHash, initialNavigation: !useHash }; @@ -29,7 +29,7 @@ const ROUTING_OPTIONS: ExtraOptions = { SharedModule.forRoot(), OAuthModule.forRoot({ resourceServer: { - allowedUrls: ['http://www.angular.at/api'], + allowedUrls: ['http://localhost:8080/api'], sendAccessToken: true } }) @@ -44,7 +44,7 @@ const ROUTING_OPTIONS: ExtraOptions = { // {provide: AuthConfig, useValue: authConfig }, // { provide: OAuthStorage, useValue: localStorage }, // { provide: ValidationHandler, useClass: JwksValidationHandler }, - { provide: BASE_URL, useValue: 'http://www.angular.at' } + { provide: BASE_URL, useValue: 'http://localhost:8080' } ], bootstrap: [AppComponent] }) diff --git a/src/app/app.tokens.ts b/src/app/app.tokens.ts index d704d0d..8ca1a03 100644 --- a/src/app/app.tokens.ts +++ b/src/app/app.tokens.ts @@ -1,3 +1,3 @@ import { InjectionToken } from '@angular/core'; -export const BASE_URL = new InjectionToken('BASE_URL'); +export const BASE_URL = new InjectionToken('http://localhost:8080'); diff --git a/src/app/auth-no-discovery.config.ts b/src/app/auth-no-discovery.config.ts deleted file mode 100644 index 52d5acd..0000000 --- a/src/app/auth-no-discovery.config.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { AuthConfig } from 'angular-oauth2-oidc'; - -export const noDiscoveryAuthConfig: AuthConfig = { - clientId: - '1004270452653-m396kcs7jc3970turlp7ffh6bv4t1b86.apps.googleusercontent.com', - redirectUri: 'http://localhost:4200/index.html', - postLogoutRedirectUri: '', - loginUrl: 'https://accounts.google.com/o/oauth2/v2/auth', - scope: 'openid profile email', - resource: '', - rngUrl: '', - oidc: true, - requestAccessToken: true, - options: null, - issuer: 'https://accounts.google.com', - clearHashAfterLogin: true, - tokenEndpoint: 'https://www.googleapis.com/oauth2/v4/token', - userinfoEndpoint: 'https://www.googleapis.com/oauth2/v3/userinfo', - responseType: 'token', - showDebugInformation: true, - silentRefreshRedirectUri: 'http://localhost:4200/silent-refresh.html', - silentRefreshMessagePrefix: '', - silentRefreshShowIFrame: false, - silentRefreshTimeout: 20000, - dummyClientSecret: null, - requireHttps: 'remoteOnly', - strictDiscoveryDocumentValidation: false, - jwks: { - keys: [ - { - kty: 'RSA', - alg: 'RS256', - use: 'sig', - kid: '7540561fdb04b89d824a1b7b9e8849873e7cb50e', - n: - // tslint:disable-next-line: max-line-length - 'sSFZrLIrXzvXBCehdPR10T-mfHWFU5ZtGzW9buI7wT_tJzZ1SRUc2l1NH92kGV9bmWRtDLjWcWFwMG7rbjX25-R-62lD1k15gQiO4bhx7gbV05e36os2vXTs0ypj9GS9y8X_2fYAnxxulMLwz4m24Ejo2tQI43-V-3Tec6cSXe0FjhRaPbGdS8GHPDKkhpJ1NHMZ38vhddIImOfvtVuz3lt_zwjBsAC6Q7PHs2GOm3KtC22DCwXMYSri4QOQcasuvTlZxIQSIksTyuH0T02IH5SJvQZSx46Vfq8BM4JP-zEEjzadoyxQPouRM6TrUeaqNv5B1f1lbH6G0G_r_ddYWQ', - e: 'AQAB' - }, - { - kty: 'RSA', - alg: 'RS256', - use: 'sig', - kid: '778233e8f6f342ea09e867aad25f543adeebf372', - n: - // tslint:disable-next-line: max-line-length - '8MMxQ9F7R1zJ57QvLX-HqUlTVLLofCzZ3-lxohJr8ivJDGZoCqll7ZTNO0nGMgnPpIO-3BQLkaNGQDCpnID1vNIjClFFl0E3cN5bDX15uxCQeQDsm25fTlphpy5FkdoHCviswtrsl2KKUPeRlKqCqMjlDO27KuxIwzIPdNSqv4tseZmI-biFt2JlO9htgODrVqaawdm27t9HcWfOK_a5czRFDHWck2-ZwjbCOF9CtF1ggYm11aV0TElExXr5fgjAQdZ1yGmJvir127BRUgyIy5cpyf7VRRf2Cv7whSMoVJr4W3OK0H9vkuFLnlBiBNYQmH_eWy5U4jBfZjBqvA7Oww', - e: 'AQAB' - }, - { - kty: 'RSA', - alg: 'RS256', - use: 'sig', - kid: '8ec17994394464d95b0b3d906326f1cdde8aee64', - n: - // tslint:disable-next-line: max-line-length - 'w49KfvzGWVXH4vyUxvP29_QTmJfvLp4RPT1WlI6Wo2aNvn6j9vRSLDrK2CnOvvrrlUKvR-8FTcyNi9pRKXDwDhEJcyVFBJVi4PqDh0KIX_dOGYCulr5FUvU0HXQxlMWSHIsJjfGbMMUwM0p09y8KHL-kipiipzn80EpBmrI4Q3t6XOAZJSmbIPaGZJDjyoWWV0TDdVDBMfkqII6tOOB7Ha189AZjz7FHYXR9CIc0Jm6rFy0tVpdHFEG3ptcNQEDQ5ghyMM4PDM4ZmQ5uk3WgHVqnpdmGEfKekLwmYFWgnI-ux_MabltIxr9TE1qubEmebM64rOusHBF0mSbEwggbyw', - e: 'AQAB' - } - ] - }, - customQueryParams: null, - silentRefreshIFrameName: 'angular-oauth-oidc-silent-refresh-iframe', - timeoutFactor: 0.75, - sessionCheckIntervall: 3000, - sessionCheckIFrameName: 'angular-oauth-oidc-check-session-iframe', - disableAtHashCheck: false, - skipSubjectCheck: false -}; diff --git a/src/app/home/home.component.ts b/src/app/home/home.component.ts index 38ce3ae..3e5b50c 100644 --- a/src/app/home/home.component.ts +++ b/src/app/home/home.component.ts @@ -7,7 +7,7 @@ import { ActivatedRoute } from '@angular/router'; templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { - loginFailed: boolean = false; + loginFailed = false; userProfile: object; usePopup: boolean; login: false; @@ -17,7 +17,7 @@ export class HomeComponent implements OnInit { private oauthService: OAuthService ) {} - ngOnInit() { + ngOnInit(): void { this.route.params.subscribe(p => { this.login = p['login']; }); @@ -33,7 +33,7 @@ export class HomeComponent implements OnInit { */ } - async loginCode() { + async loginCode(): Promise { // Tweak config for code flow this.oauthService.configure(authCodeFlowConfig); await this.oauthService.loadDiscoveryDocument(); @@ -43,7 +43,7 @@ export class HomeComponent implements OnInit { // the parameter here is optional. It's passed around and can be used after logging in } - async loginCodeInPopup() { + async loginCodeInPopup(): Promise { // Tweak config for code flow this.oauthService.configure(authCodeFlowConfig); await this.oauthService.loadDiscoveryDocument(); @@ -54,7 +54,7 @@ export class HomeComponent implements OnInit { }); } - logout() { + logout(): void { // this.oauthService.logOut(); this.oauthService.revokeTokenAndLogout(); } @@ -63,19 +63,19 @@ export class HomeComponent implements OnInit { this.oauthService.loadUserProfile().then(up => (this.userProfile = up)); } - get givenName() { - var claims = this.oauthService.getIdentityClaims(); - if (!claims) return null; + get givenName(): any { + const claims = this.oauthService.getIdentityClaims(); + if (!claims) { return null; } return claims['given_name']; } - get familyName() { - var claims = this.oauthService.getIdentityClaims(); - if (!claims) return null; + get familyName(): any { + const claims = this.oauthService.getIdentityClaims(); + if (!claims) { return null; } return claims['family_name']; } - refresh() { + refresh(): void { this.oauthService.oidc = true; if ( @@ -84,12 +84,12 @@ export class HomeComponent implements OnInit { ) { this.oauthService .refreshToken() - .then(info => console.debug('refresh ok', info)) + .then(info => console.log('refresh ok', info)) .catch(err => console.error('refresh error', err)); } else { this.oauthService .silentRefresh() - .then(info => console.debug('silent refresh ok', info)) + .then(info => console.log('silent refresh ok', info)) .catch(err => console.error('silent refresh error', err)); } } @@ -99,7 +99,7 @@ export class HomeComponent implements OnInit { localStorage.setItem('requestAccessToken', '' + value); } - get requestAccessToken() { + get requestAccessToken(): boolean { return this.oauthService.requestAccessToken; } @@ -111,23 +111,23 @@ export class HomeComponent implements OnInit { } } - get useHashLocationStrategy() { + get useHashLocationStrategy(): boolean { return localStorage.getItem('useHashLocationStrategy') === 'true'; } - get id_token() { + get id_token(): string { return this.oauthService.getIdToken(); } - get access_token() { + get access_token(): string { return this.oauthService.getAccessToken(); } - get id_token_expiration() { + get id_token_expiration(): number { return this.oauthService.getIdTokenExpiration(); } - get access_token_expiration() { + get access_token_expiration(): number { return this.oauthService.getAccessTokenExpiration(); } } diff --git a/src/app/shared/auth/auth.guard.ts b/src/app/shared/auth/auth.guard.ts index b137ab4..8d01c3c 100644 --- a/src/app/shared/auth/auth.guard.ts +++ b/src/app/shared/auth/auth.guard.ts @@ -6,7 +6,7 @@ import { OAuthService } from 'angular-oauth2-oidc'; export class AuthGuard implements CanActivate { constructor(private router: Router, private oauthService: OAuthService) {} - canActivate() { + canActivate(): boolean { if ( this.oauthService.hasValidAccessToken() && this.oauthService.hasValidIdToken() diff --git a/tsconfig.json b/tsconfig.json index f69f654..1d4dd1e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,9 +12,13 @@ "importHelpers": true, "target": "es2015", "module": "es2020", - "lib": [ - "es2018", - "dom" - ] + "lib": ["es2018", "dom"], + "strict": false, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true + }, + "angularCompilerOptions": { + "strictInjectionParameters": true, + "strictTemplates": true } }