Skip to content

Commit

Permalink
♻️ refactor: 移动core.module到http.Interceptor.ts并更新引用位置
Browse files Browse the repository at this point in the history
  • Loading branch information
vnobo committed Jun 7, 2024
1 parent 7df9569 commit f4ef7e2
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 46 deletions.
8 changes: 4 additions & 4 deletions ui-work/projects/web/local/source.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,31 @@
<file id="ngi18n" original="ng.template">
<unit id="errorMessage">
<notes>
<note category="location">projects/web/src/app/core/core.module.ts:39</note>
<note category="location">projects/web/src/app/core/http.Interceptor.ts:39</note>
</notes>
<segment>
<source>Backend returned code <ph id="0" equiv="PH" disp="errorResponse.status"/>, body was: </source>
</segment>
</unit>
<unit id="errorMessage401">
<notes>
<note category="location">projects/web/src/app/core/core.module.ts:60</note>
<note category="location">projects/web/src/app/core/http.Interceptor.ts:60</note>
</notes>
<segment>
<source>身份验证无效,请重新登录。</source>
</segment>
</unit>
<unit id="errorMessage407">
<notes>
<note category="location">projects/web/src/app/core/core.module.ts:64</note>
<note category="location">projects/web/src/app/core/http.Interceptor.ts:64</note>
</notes>
<segment>
<source>认证不正确,请重新登录。</source>
</segment>
</unit>
<unit id="errorMessage403">
<notes>
<note category="location">projects/web/src/app/core/core.module.ts:68</note>
<note category="location">projects/web/src/app/core/http.Interceptor.ts:68</note>
</notes>
<segment>
<source>验证码令牌错误,请重新登录。</source>
Expand Down
15 changes: 13 additions & 2 deletions ui-work/projects/web/src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,27 @@ import {provideNzConfig} from "ng-zorro-antd/core/config";
import {ngZorroConfig} from "../shared/shared-zorro.module";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {provideAnimationsAsync} from "@angular/platform-browser/animations/async";
import {provideHttpClient, withFetch} from "@angular/common/http";
import {
provideHttpClient,
withFetch,
withInterceptors,
withInterceptorsFromDi,
withXsrfConfiguration
} from "@angular/common/http";
import {authTokenInterceptor, defaultInterceptor} from "../core/http.Interceptor";

export const appConfig: ApplicationConfig = {
providers: [
importProvidersFrom(BrowserAnimationsModule),
provideAnimationsAsync(),
provideNzConfig(ngZorroConfig),
provideRouter(routes),
provideHttpClient(withFetch()),
provideExperimentalZonelessChangeDetection(),
{provide: TitleStrategy, useClass: PageTitleStrategy},
provideHttpClient(
withFetch(), withInterceptorsFromDi(),
withInterceptors([defaultInterceptor, authTokenInterceptor]),
withXsrfConfiguration({cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN'})
)
]
};
49 changes: 39 additions & 10 deletions ui-work/projects/web/src/core/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
import {inject, Injectable} from '@angular/core';
import {afterNextRender, Inject, inject, Injectable, InjectionToken} from '@angular/core';
import {Subject} from "rxjs";
import {HttpErrorResponse} from "@angular/common/http";
import {CanActivateChildFn, CanActivateFn, CanMatchFn, Router} from "@angular/router";

/**
* A function that acts as an authentication guard.
*
* @return {CanMatchFn | CanActivateFn | CanActivateChildFn} The authentication result.
*/
export const SESSION_STORAGE = new InjectionToken<Storage>('Session Storage', {
providedIn: 'root',
factory: () => sessionStorage
});

export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
providedIn: 'root',
factory: () => localStorage
});

@Injectable({providedIn: 'root'})
export class BrowserStorageService {

private storage: Storage = localStorage;

constructor(@Inject(BROWSER_STORAGE) private _storage: Storage) {
afterNextRender(() => {
this.storage = this._storage;
});
}

get(key: string) {
return this.storage.getItem(key);
}

delete(key: string) {
return this.storage.removeItem(key);
}

set(key: string, value: string) {
this.storage.setItem(key, value);
}
}

export const authGuard: CanMatchFn | CanActivateFn | CanActivateChildFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
Expand All @@ -27,7 +56,7 @@ export class AuthService {
private authenticatedSource = new Subject<boolean>();
authenticated$ = this.authenticatedSource.asObservable();

constructor() {
constructor(private storage: BrowserStorageService) {
this.autoLogin();
}

Expand All @@ -48,7 +77,7 @@ export class AuthService {
}

loadSessionByStorage(): string | null {
const authToken = '222222222222222222222222222';//sessionStorage.getItem(this.sessionKey);
const authToken = this.storage.get(this.sessionKey);
if (authToken != null) {
return authToken;
}
Expand All @@ -58,13 +87,13 @@ export class AuthService {
login(authentication: string) {
this.isLoggedIn = true;
this.authenticatedSource.next(true);
//sessionStorage.setItem(this.sessionKey, authentication);
this.storage.set(this.sessionKey, authentication);
}

logout(): void {
this.isLoggedIn = false;
this.authenticatedSource.next(false);
//sessionStorage.removeItem(this.sessionKey);
this.storage.delete(this.sessionKey);
}

}
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import {inject, NgModule, Optional, SkipSelf} from '@angular/core';
import {
HttpEvent,
HttpHandlerFn,
HttpRequest,
provideHttpClient,
withFetch,
withInterceptors,
withInterceptorsFromDi,
withXsrfConfiguration
} from "@angular/common/http";
import {inject} from '@angular/core';
import {HttpEvent, HttpHandlerFn, HttpRequest} from "@angular/common/http";
import {catchError, finalize, Observable, throwError, timeout} from "rxjs";
import {AuthService} from "./auth.service";
import {LoadingService} from "./loading.service";
Expand Down Expand Up @@ -73,22 +64,3 @@ export function authTokenInterceptor(req: HttpRequest<unknown>, next: HttpHandle
}
}));
}


@NgModule({
exports: [], imports: [], providers: [
provideHttpClient(withFetch(), withInterceptors([defaultInterceptor, authTokenInterceptor])),
provideHttpClient(withInterceptorsFromDi(), withXsrfConfiguration({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
}))
]
})
export class CoreModule {
constructor(@Optional() @SkipSelf() parentModule?: CoreModule) {
if (parentModule) {
throw new Error(
'CoreModule is already loaded. Import it in the AppModule only');
}
}
}
1 change: 1 addition & 0 deletions ui-work/projects/web/src/shared/shared.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ import {IconsProviderModule} from "./icons-provider.module";
})
export class SharedModule {
}

0 comments on commit f4ef7e2

Please sign in to comment.