Compare commits

..

No commits in common. "dba0d3cd62c9345e89597b4e7a22293c97e6af3b" and "28715055918fea3a846ba1c7f9bffd42dee33976" have entirely different histories.

19 changed files with 239 additions and 291 deletions

35
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "frontend",
"version": "1.0.0-b3",
"version": "1.0.0-b2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frontend",
"version": "1.0.0-b3",
"version": "1.0.0-b2",
"dependencies": {
"@angular/animations": "^18.2.1",
"@angular/cdk": "~18.2.1",
@ -19,10 +19,9 @@
"@angular/platform-browser": "^18.2.1",
"@angular/platform-browser-dynamic": "^18.2.1",
"@angular/router": "^18.2.1",
"@dhutaryan/ngx-mat-timepicker": "^18.0.1",
"@progress/kendo-date-math": "^1.5.13",
"rxjs": "~7.8.1",
"tslib": "^2.7.0",
"tslib": "^2.6.3",
"zone.js": "^0.14.10"
},
"devDependencies": {
@ -36,6 +35,7 @@
"karma-coverage": "~2.2.1",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"terser-webpack-plugin": "^5.3.10",
"typescript": "^5.5.4"
}
},
@ -232,13 +232,6 @@
"node": ">=14.0.0"
}
},
"node_modules/@angular-devkit/build-angular/node_modules/tslib": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz",
"integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==",
"dev": true,
"license": "0BSD"
},
"node_modules/@angular-devkit/build-webpack": {
"version": "0.1802.1",
"resolved": "https://registry.npmjs.org/@angular-devkit/build-webpack/-/build-webpack-0.1802.1.tgz",
@ -2535,20 +2528,6 @@
"node": ">=0.1.90"
}
},
"node_modules/@dhutaryan/ngx-mat-timepicker": {
"version": "18.0.1",
"resolved": "https://registry.npmjs.org/@dhutaryan/ngx-mat-timepicker/-/ngx-mat-timepicker-18.0.1.tgz",
"integrity": "sha512-7qOiDFGorfmJJ/f9In4jHRJq8sDZqtX0aBFQU/KEGkBywmm0In7C+Z7To1DWM5hbR/XAC4d6b+sOqq0Pcqqsmw==",
"license": "MIT",
"dependencies": {
"tslib": ">=2.0.0"
},
"peerDependencies": {
"@angular/common": ">=18.0.0",
"@angular/core": ">=18.0.0",
"@angular/material": ">=18.0.0"
}
},
"node_modules/@discoveryjs/json-ext": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.6.1.tgz",
@ -12565,9 +12544,9 @@
}
},
"node_modules/tslib": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz",
"integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==",
"license": "0BSD"
},
"node_modules/tuf-js": {

View File

@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "1.0.0-b3",
"version": "1.0.0-b2",
"scripts": {
"ng": "ng",
"start": "ng serve",
@ -21,10 +21,9 @@
"@angular/platform-browser": "^18.2.1",
"@angular/platform-browser-dynamic": "^18.2.1",
"@angular/router": "^18.2.1",
"@dhutaryan/ngx-mat-timepicker": "^18.0.1",
"@progress/kendo-date-math": "^1.5.13",
"rxjs": "~7.8.1",
"tslib": "^2.7.0",
"tslib": "^2.6.3",
"zone.js": "^0.14.10"
},
"devDependencies": {
@ -38,6 +37,7 @@
"karma-coverage": "~2.2.1",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"terser-webpack-plugin": "^5.3.10",
"typescript": "^5.5.4"
}
}

View File

@ -1,5 +1,9 @@
import {HttpHeaders} from "@angular/common/http";
export interface SetRequestBuilderAfterBuild {
setRequestBuilder(request: RequestData): void;
}
export interface RequestData {
endpoint: string;
queryParams: Record<string, string | number | boolean | Array<any> | null> | null;
@ -7,7 +11,6 @@ export interface RequestData {
data: any;
silenceMode: boolean;
withCredentials: boolean;
needAuth: boolean;
}
export class RequestBuilder {
@ -17,8 +20,10 @@ export class RequestBuilder {
private data: any = null;
private silenceMode: boolean = false;
private withCredentials: boolean = false;
private readonly object: any;
constructor() {
constructor(obj: any) {
this.object = obj;
}
public setEndpoint(endpoint: string): this {
@ -53,16 +58,16 @@ export class RequestBuilder {
return this;
}
public get build(): RequestData {
return {
public build<Type>(): Type {
(this.object as SetRequestBuilderAfterBuild).setRequestBuilder({
endpoint: this.endpoint,
queryParams: this.queryParams,
httpHeaders: this.httpHeaders,
data: this.data,
silenceMode: this.silenceMode,
withCredentials: this.withCredentials,
needAuth: false
};
withCredentials: this.withCredentials
});
return this.object as Type;
}
public getEndpoint(): string {
@ -92,8 +97,16 @@ export class RequestBuilder {
httpHeaders: new HttpHeaders(),
data: null,
silenceMode: false,
withCredentials: false,
needAuth: false
withCredentials: false
};
}
public reset(): void {
this.endpoint = '';
this.queryParams = null;
this.httpHeaders = new HttpHeaders();
this.data = null;
this.silenceMode = false;
this.withCredentials = false;
}
}

View File

@ -1,10 +1,10 @@
import {catchError, distinctUntilChanged, filter, first, mergeMap, Observable, retryWhen, switchMap, timer} from "rxjs";
import {catchError, filter, mergeMap, Observable, retryWhen, switchMap, tap, timer} from "rxjs";
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {NotifyColor, OpenNotifyService} from "@service/open-notify.service";
import {environment} from "@environment";
import {Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {RequestBuilder, RequestData} from "@api/RequestBuilder";
import {RequestBuilder, RequestData, SetRequestBuilderAfterBuild} from "@api/RequestBuilder";
import {TokenRefreshService} from "@service/token-refresh.service";
import {AuthToken} from "@service/auth.service";
@ -36,17 +36,20 @@ export enum AvailableVersion {
}
@Injectable()
export default abstract class ApiService {
export default abstract class ApiService implements SetRequestBuilderAfterBuild {
constructor(private http: HttpClient, private notify: OpenNotifyService, private router: Router, protected tokenRefreshService: TokenRefreshService) {
}
private apiUrl = environment.apiUrl;
protected abstract basePath: string;
protected abstract version: AvailableVersion;
private request: RequestData = RequestBuilder.getStandardRequestData();
public static readonly tokenKey = 'auth_token';
public setRequestBuilder(request: RequestData): void {
this.request = request;
}
private static addQuery(endpoint: string, queryParams?: Record<string, string | number | boolean | Array<any> | null> | null): string {
const url = new URL(endpoint);
@ -69,80 +72,73 @@ export default abstract class ApiService {
return parts.map(part => part.replace(/(^\/+|\/+$)/g, '')).join('/');
}
protected combinedUrl(request: RequestData) {
return ApiService.addQuery(ApiService.combineUrls(this.apiUrl, AvailableVersion[this.version], this.basePath, request.endpoint), request.queryParams);
protected get combinedUrl() {
return ApiService.addQuery(ApiService.combineUrls(this.apiUrl, AvailableVersion[this.version], this.basePath, this.request.endpoint), this.request.queryParams);
}
private sendHttpRequest<Type>(method: 'get' | 'post' | 'delete' | 'put', request: RequestData): Observable<Type> {
const doneEndpoint = this.combinedUrl(request);
private makeHttpRequest<Type>(method: 'get' | 'post' | 'delete' | 'put'): Observable<Type> {
const doneEndpoint = this.combinedUrl;
return this.http.request<Type>(method, doneEndpoint, {
withCredentials: request.withCredentials,
headers: request.httpHeaders,
body: request.data
}).pipe(
retryWithInterval<Type>(),
catchError(error => {
if (!request.silenceMode)
this.handleError(error);
return this.tokenRefreshService.getTokenRefreshing$().pipe(
filter(isRefreshing => !isRefreshing),
switchMap(() =>
this.http.request<Type>(method, doneEndpoint, {
withCredentials: this.request.withCredentials,
headers: this.request.httpHeaders,
body: this.request.data
}).pipe(
tap(_ => this.request = RequestBuilder.getStandardRequestData()),
retryWithInterval<Type>(),
catchError(error => {
if (!this.request.silenceMode)
this.handleError(error);
throw error;
})
this.request = RequestBuilder.getStandardRequestData();
throw error;
})
)
)
);
}
private makeHttpRequest<Type>(method: 'get' | 'post' | 'delete' | 'put', request: RequestData): Observable<Type> {
if (request.needAuth)
return this.tokenRefreshService.getTokenRefreshing$().pipe(
distinctUntilChanged(),
filter(isRefreshing => !isRefreshing),
first(),
switchMap(() => {
const token = localStorage.getItem(ApiService.tokenKey);
if (token) {
const authToken = AuthToken.httpHeader((JSON.parse(token) as AuthToken));
authToken.keys().forEach(key => request.httpHeaders = request.httpHeaders.append(key, authToken.get(key) ?? ''));
}
return this.sendHttpRequest<Type>(method, request);
})
);
return this.sendHttpRequest<Type>(method, request);
}
private getRequest(request: RequestData | string | null): RequestData {
if (request === null)
return this.createRequestBuilder().build;
if (typeof request === 'string')
return this.createRequestBuilder().setEndpoint(request as string).build;
return request as RequestData;
}
public createRequestBuilder() {
return new RequestBuilder();
this.request = RequestBuilder.getStandardRequestData();
return new RequestBuilder(this);
}
public get<Type>(request: RequestData | string | null = null): Observable<Type> {
return this.makeHttpRequest<Type>('get', this.getRequest(request));
public get<Type>(endpoint: string = ''): Observable<Type> {
if (endpoint)
this.request.endpoint = endpoint;
return this.makeHttpRequest<Type>('get');
}
public post<Type>(request: RequestData | string | null = null): Observable<Type> {
return this.makeHttpRequest<Type>('post', this.getRequest(request));
public post<Type>(endpoint: string = ''): Observable<Type> {
if (endpoint)
this.request.endpoint = endpoint;
return this.makeHttpRequest<Type>('post');
}
public put<Type>(request: RequestData | string | null = null): Observable<Type> {
return this.makeHttpRequest<Type>('put', this.getRequest(request));
public put<Type>(endpoint: string = ''): Observable<Type> {
if (endpoint)
this.request.endpoint = endpoint;
return this.makeHttpRequest<Type>('put');
}
public delete<Type>(request: RequestData | string | null = null): Observable<Type> {
return this.makeHttpRequest<Type>('delete', this.getRequest(request));
public delete<Type>(endpoint: string = ''): Observable<Type> {
if (endpoint)
this.request.endpoint = endpoint;
return this.makeHttpRequest<Type>('delete');
}
public addAuth(request: RequestData) {
request.needAuth = true;
public addAuth() {
const token = localStorage.getItem(ApiService.tokenKey);
if (!token)
return this;
const authToken = AuthToken.httpHeader((JSON.parse(token) as AuthToken));
authToken.keys().forEach(key => this.request.httpHeaders = this.request.httpHeaders.append(key, authToken.get(key) ?? ''));
return this;
}

View File

@ -12,29 +12,26 @@ export default class AuthApiService extends ApiService {
public readonly version = AvailableVersion.v1;
public login(login: LoginRequest) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('Login')
.setData(login)
.setWithCredentials()
.build;
return this.post<TokenResponse>(request)
.build<ApiService>()
.post<TokenResponse>()
.pipe(
tap(response => {
AuthService.setToken(response, AvailableAuthenticationProvider.Bearer, this.combinedUrl(this.createRequestBuilder().setEndpoint('ReLogin').build));
this.tokenRefreshService.setRefreshTokenExpireMs(response.expiresIn);
AuthService.setToken(response, AvailableAuthenticationProvider.Bearer, this.createRequestBuilder().setEndpoint('ReLogin').build<AuthApiService>().combinedUrl);
this.tokenRefreshService.startTokenRefresh(response.expiresIn);
})
);
}
public logout() {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setWithCredentials()
.setEndpoint('Logout')
.build;
return this.addAuth(request)
.get(request)
.build<ApiService>()
.addAuth()
.get()
.pipe(
tap(_ => {
localStorage.removeItem(ApiService.tokenKey);
@ -43,13 +40,11 @@ export default class AuthApiService extends ApiService {
}
public getRole(isSilence: boolean = true) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setSilenceMode(isSilence)
.setEndpoint('GetRole')
.build;
return this.addAuth(request)
.get<AuthRoles>(request)
.build<ApiService>()
.addAuth()
.get<AuthRoles>('GetRole')
.pipe(
catchError(_ => {
return of(null);

View File

@ -8,11 +8,10 @@ export class DisciplineService extends ApiService {
public readonly version = AvailableVersion.v1;
public getDisciplines(page: number | null = null, pageSize: number | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setQueryParams({page: page, pageSize: pageSize})
.build;
return this.get<DisciplineResponse[]>(request);
.build<ApiService>()
.get<DisciplineResponse[]>();
}
public getById(id: number) {

View File

@ -9,11 +9,10 @@ export class FacultyService extends ApiService {
public readonly version = AvailableVersion.v1;
public getFaculties(page: number | null = null, pageSize: number | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setQueryParams({page: page, pageSize: pageSize})
.build;
return this.get<FacultyResponse[]>(request);
.build<ApiService>()
.get<FacultyResponse[]>();
}
public getById(id: number) {

View File

@ -9,11 +9,10 @@ export class GroupService extends ApiService {
public readonly version = AvailableVersion.v1;
public getGroups(page: number | null = null, pageSize: number | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setQueryParams({page: page, pageSize: pageSize})
.build;
return this.get<GroupResponse[]>(request);
.build<ApiService>()
.get<GroupResponse[]>();
}
public getById(id: number) {

View File

@ -8,11 +8,10 @@ export class ProfessorService extends ApiService {
public readonly version = AvailableVersion.v1;
public getProfessors(page: number | null = null, pageSize: number | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setQueryParams({page: page, pageSize: pageSize})
.build;
return this.get<ProfessorResponse[]>(request);
.build<ApiService>()
.get<ProfessorResponse[]>();
}
public getById(id: number) {

View File

@ -20,46 +20,41 @@ export class ScheduleService extends ApiService {
}
public postSchedule(data: ScheduleRequest) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setData(data)
.build;
return this.post<ScheduleResponse[]>(request);
.build<ApiService>()
.post<ScheduleResponse[]>();
}
public getByGroup(id: number, isEven: boolean | null = null, disciplines: Array<number> | null = null, professors: Array<number> | null = null, lectureHalls: Array<number> | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('GetByGroup/' + id.toString())
.setQueryParams({isEven: isEven, disciplines: disciplines, professors: professors, lectureHalls: lectureHalls})
.build;
return this.get<ScheduleResponse[]>(request);
.build<ApiService>()
.get<ScheduleResponse[]>();
}
public getByProfessor(id: number, isEven: boolean | null = null, disciplines: Array<number> | null = null, groups: Array<number> | null = null, lectureHalls: Array<number> | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('GetByProfessor/' + id.toString())
.setQueryParams({isEven: isEven, disciplines: disciplines, groups: groups, lectureHalls: lectureHalls})
.build;
return this.get<ScheduleResponse[]>(request);
.build<ApiService>()
.get<ScheduleResponse[]>();
}
public getByLectureHall(id: number, isEven: boolean | null = null, disciplines: Array<number> | null = null, groups: Array<number> | null = null, professors: Array<number> | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('GetByLectureHall/' + id.toString())
.setQueryParams({isEven: isEven, disciplines: disciplines, groups: groups, professors: professors})
.build;
return this.get<ScheduleResponse[]>(request);
.build<ApiService>()
.get<ScheduleResponse[]>();
}
public getByDiscipline(id: number, isEven: boolean | null = null, groups: Array<number> | null = null, professors: Array<number> | null = null, lectureHalls: Array<number> | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('GetByDiscipline/' + id.toString())
.setQueryParams({isEven: isEven, groups: groups, professors: professors, lectureHalls: lectureHalls})
.build;
return this.get<ScheduleResponse[]>(request);
.build<ApiService>()
.get<ScheduleResponse[]>();
}
}

View File

@ -14,112 +14,101 @@ export default class SetupService extends ApiService {
public readonly version = AvailableVersion.v1;
public checkToken(token: string) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('CheckToken')
.setQueryParams({token: token})
.build;
return this.get<boolean>(request);
.build<ApiService>()
.get<boolean>();
}
public setPsql(data: DatabaseRequest) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetPsql')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public setMysql(data: DatabaseRequest) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetMysql')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public setSqlite(path: string | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetSqlite')
.setQueryParams({path: path})
.setWithCredentials()
.build;
return this.get<boolean>(request);
.build<ApiService>()
.get<boolean>();
}
public setRedis(data: CacheRequest) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetRedis')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public setMemcached() {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetMemcached')
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public createAdmin(data: CreateUserRequest) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('CreateAdmin')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public setLogging(data: LoggingRequest | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetLogging')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public setEmail(data: EmailRequest | null = null) {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetEmail')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public setSchedule(data: ScheduleConfigurationRequest) {
data.startTerm = new DateOnly(data.startTerm).toString();
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('SetSchedule')
.setData(data)
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public submit() {
let request = this.createRequestBuilder()
return this.createRequestBuilder()
.setEndpoint('Submit')
.setWithCredentials()
.build;
return this.post<boolean>(request);
.build<ApiService>()
.post<boolean>();
}
public isConfigured() {

View File

@ -4,6 +4,7 @@ import {FooterComponent} from "@component/common/footer/footer.component";
import localeRu from '@angular/common/locales/ru';
import {registerLocaleData} from '@angular/common';
import {FocusNextDirective} from "@/directives/focus-next.directive";
import {TokenRefreshService} from "@service/token-refresh.service";
import {HeaderComponent} from "@component/common/header/header.component";
@Component({
@ -16,7 +17,8 @@ import {HeaderComponent} from "@component/common/header/header.component";
<app-footer/>`
})
export class AppComponent {
constructor() {
constructor(tokenRefreshService: TokenRefreshService) {
registerLocaleData(localeRu);
tokenRefreshService.startTokenRefresh();
}
}

View File

@ -1,24 +1,24 @@
<!--suppress CssInvalidPropertyValue -->
<button mat-button [matMenuTriggerFor]="menu" #menuTrigger="matMenuTrigger" [id]="idButton" style="margin-bottom: 10px;">{{ textButton }}</button>
<button mat-button [matMenuTriggerFor]="menu" #menuTrigger="matMenuTrigger" [id]="idButton">{{ textButton }}</button>
<mat-menu #menu="matMenu" [hasBackdrop]="false" class="menu-options">
<div (click)="$event.stopPropagation()" (keydown)="$event.stopPropagation()" style="padding: 0 15px 15px">
<div class="header-menu">
<mat-form-field appearance="outline" color="accent" style="display:flex;">
<input matInput placeholder="Поиск..." [(ngModel)]="searchQuery" [disabled]="data === null || data.length === 0">
<button mat-icon-button matSuffix (click)="clearSearchQuery()" [disabled]="data === null || data.length === 0">
<input matInput placeholder="Поиск..." [(ngModel)]="searchQuery" [disabled]="data.length === 0">
<button mat-icon-button matSuffix (click)="clearSearchQuery()" [disabled]="data.length === 0">
<mat-icon style="color: var(--mdc-filled-button-label-text-color);">close</mat-icon>
</button>
</mat-form-field>
<div class="button-group">
<mat-checkbox (click)="checkData()" [disabled]="data === null || data.length === 0" #chooseCheckbox/>
<button mat-button (click)="clearAll()" [disabled]="data === null || data.length === 0">Очистить</button>
<mat-checkbox (click)="checkData()" [disabled]="data.length === 0" #chooseCheckbox/>
<button mat-button (click)="clearAll()" [disabled]="data.length === 0">Очистить</button>
</div>
<hr/>
</div>
@if (data === null || data.length === 0) {
<app-loading-indicator style="display: flex; justify-content: center;" [loading]="data === null"
@if (data.length === 0) {
<app-loading-indicator style="display: flex; justify-content: center;" [loading]="dataLoaded !== null"
(retryFunction)="retryLoadData.emit()"/>
} @else {
<mat-selection-list>

View File

@ -47,19 +47,17 @@ export interface SelectData {
export class OtherComponent {
private _searchQuery: string = '';
protected filteredData: BehaviorSubject<SelectData[]> = new BehaviorSubject<SelectData[]>([]);
protected data: SelectData[] | null = null;
protected data: SelectData[] = [];
@Input() idButton!: string;
@Input() textButton!: string;
@ViewChild('menuTrigger') menuTrigger!: MatMenuTrigger;
@ViewChild('chooseCheckbox') chooseCheckbox!: MatCheckbox;
@Input() dataLoaded: boolean | null = false;
@Output() retryLoadData: EventEmitter<void> = new EventEmitter<void>();
get selectedIds(): number[] {
if (this.data === null)
return [];
return this.data.filter(x => x.selected).map(x => x.id);
}
@ -74,9 +72,6 @@ export class OtherComponent {
}
private updateCheckBox() {
if (this.data === null)
return;
this.chooseCheckbox.checked = this.data.every(x => x.selected);
this.chooseCheckbox.indeterminate = this.data.some(x => x.selected) && !this.chooseCheckbox.checked;
}
@ -87,9 +82,6 @@ export class OtherComponent {
}
protected updateFilteredData(): void {
if (this.data === null)
return;
this.filteredData.next(this.data.filter(x =>
x.name.toLowerCase().includes(this.searchQuery.toLowerCase())
));
@ -100,7 +92,7 @@ export class OtherComponent {
}
protected clearAll(): void {
this.data?.forEach(x => x.selected = false);
this.data.forEach(x => x.selected = false);
if (this.searchQuery !== '') {
const updatedData = this.filteredData.value.map(x => {
@ -117,7 +109,7 @@ export class OtherComponent {
const check: boolean = this.filteredData.value.some(x => !x.selected) && !this.filteredData.value.every(x => x.selected);
const updatedData = this.filteredData.value.map(data => {
this.data!.find(x => x.id === data.id)!.selected = check;
this.data.find(x => x.id === data.id)!.selected = check;
return {...data, selected: check};
});
@ -126,7 +118,7 @@ export class OtherComponent {
}
protected checkboxStateChange(item: number) {
const data = this.data!.find(x => x.id === item)!;
const data = this.data.find(x => x.id === item)!;
data.selected = !data.selected;
const updatedData = this.filteredData.value;
updatedData.find(x => x.id === item)!.selected = data.selected;

View File

@ -20,7 +20,7 @@ export class HasRoleDirective {
this.authService
.getRole()
.pipe(catchError(_ => {
.pipe(catchError(error => {
this.viewContainer.clear();
return of(null);
}))

View File

@ -40,11 +40,11 @@ export class LoginComponent {
protected loginButtonIsDisable: boolean = true;
protected errorText: string = '';
constructor(private formBuilder: FormBuilder, private auth: AuthApiService, private router: Router) {
constructor(private formBuilder: FormBuilder, private auth: AuthApiService, private route: Router) {
this.auth.getRole()
.subscribe(data => {
if (data !== null)
router.navigate(['admin']).then();
route.navigate(['admin']).then();
});
this.loginForm = this.formBuilder.group({
@ -89,7 +89,7 @@ export class LoginComponent {
.subscribe(_ => {
this.loaderActive = false;
this.errorText = '';
this.router.navigate(['admin']).then();
this.route.navigate(['admin']).then();
});
}
}

View File

@ -2,7 +2,7 @@ import {Component} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from "@angular/forms";
import {NavigationService} from "@service/navigation.service";
import SetupService from "@api/v1/setup.service";
import {MAT_DATE_LOCALE, MatNativeDateModule} from "@angular/material/core";
import {DateAdapter, MatNativeDateModule} from "@angular/material/core";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatSelectModule} from "@angular/material/select";
import {MatInput} from "@angular/material/input";
@ -25,16 +25,17 @@ import {MatDatepickerModule} from "@angular/material/datepicker";
MatDatepickerModule,
MatNativeDateModule
],
templateUrl: './schedule.component.html',
providers: [{provide: MAT_DATE_LOCALE, useValue: 'ru-RU'}]
templateUrl: './schedule.component.html'
})
export class ScheduleComponent {
protected scheduleSettings!: FormGroup;
constructor(private navigationService: NavigationService, formBuilder: FormBuilder, private api: SetupService) {
this.scheduleSettings = formBuilder.group({
cron: ['0 */6 * * *', Validators.pattern(/^(\S+\s){4}\S$/)],
constructor(
private navigationService: NavigationService, private formBuilder: FormBuilder, private api: SetupService, private _adapter: DateAdapter<any>) {
this._adapter.setLocale('ru');
this.scheduleSettings = this.formBuilder.group({
cron: ['0 */6 * * *', Validators.pattern(/^([^\s]+\s){4}[^\s]{1}$/)],
startTerm: ['', Validators.required]
}
);

View File

@ -1,6 +1,6 @@
import {Injectable} from '@angular/core';
import {EventEmitter, Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {map, Observable, throwError} from "rxjs";
import {Observable, tap} from "rxjs";
import {TokenResponse} from "@api/v1/tokenResponse";
import ApiService from "@api/api.service";
@ -21,7 +21,7 @@ export class AuthToken {
this.endpoint = refreshEndpoint;
}
public static httpHeader(token: AuthToken): HttpHeaders {
static httpHeader(token: AuthToken): HttpHeaders {
let header = new HttpHeaders();
if (token.authProvider === AvailableAuthenticationProvider.Bearer)
@ -35,6 +35,8 @@ export class AuthToken {
providedIn: 'root',
})
export class AuthService {
public expireTokenChange = new EventEmitter<Date>();
constructor(private http: HttpClient) {
}
@ -54,11 +56,12 @@ export class AuthService {
return result <= new Date() ? new Date() : result;
}
public refreshToken(): Observable<Date> {
public refreshToken(): Observable<TokenResponse> {
const token = localStorage.getItem(ApiService.tokenKey);
console.log(token);
if (!token)
return throwError(() => new Error("Token is not found"));
throw new Error("token is not found");
const authToken = JSON.parse(token) as AuthToken;
@ -66,16 +69,14 @@ export class AuthService {
case AvailableAuthenticationProvider.Bearer:
return this.http.get<TokenResponse>(authToken.endpoint, {withCredentials: true})
.pipe(
map(response => {
tap(response => {
const newExpireDate = new Date(response.expiresIn);
const oldExpireDate = new Date(authToken.expiresIn);
if (newExpireDate.getTime() !== oldExpireDate.getTime()) {
AuthService.setToken(response, AvailableAuthenticationProvider.Bearer, authToken.endpoint);
return newExpireDate;
this.expireTokenChange.emit(newExpireDate);
}
return newExpireDate;
})
);
}

View File

@ -1,4 +1,4 @@
import {BehaviorSubject, catchError, of, Subject} from "rxjs";
import {BehaviorSubject, filter, interval, Subscription, switchMap} from "rxjs";
import {Injectable} from "@angular/core";
import {AuthService} from "@service/auth.service";
import {environment} from "@environment";
@ -8,75 +8,64 @@ import ApiService from "@api/api.service";
providedIn: 'root',
})
export class TokenRefreshService {
private tokenRefreshSubscription: Subscription | undefined;
private tokenRefreshing$ = new BehaviorSubject<boolean>(false);
private refreshTokenTimeout: any;
private refreshTokenExpireMs: number = environment.retryDelay;
constructor(private authService: AuthService) {
this.setRefreshTokenExpireMs(AuthService.tokenExpiresIn);
this.setRefreshTokenExpireMs(AuthService.tokenExpiresIn.getTime() - 1000 - Date.now());
authService.expireTokenChange.subscribe(date => {
console.debug('Expire token change event received:', date);
this.setRefreshTokenExpireMs(date.getTime() - 1000 - Date.now());
});
}
private startTokenRefresh(): void {
this.refreshTokenTimeout = setTimeout(() => {
this.refreshToken();
}, this.refreshTokenExpireMs);
}
public startTokenRefresh(date: Date | null = null): void {
if (date)
this.refreshTokenExpireMs = new Date(date).getTime() - 1000 - Date.now();
private refreshToken(): void {
if (this.tokenRefreshing$.value)
console.debug(this.tokenRefreshSubscription);
if (this.tokenRefreshSubscription && !this.tokenRefreshSubscription.closed)
return;
this.tokenRefreshing$.next(true);
this.authService.refreshToken()
.pipe(
catchError(error => {
if (error.status === 403 || error.status === 401 || !localStorage.getItem(ApiService.tokenKey)) {
localStorage.removeItem(ApiService.tokenKey);
return of(undefined);
}
let retryTime = this.refreshTokenExpireMs;
if (retryTime < environment.retryDelay)
retryTime = environment.retryDelay;
// 15 minutes
if (retryTime * 2 <= 900_000)
retryTime *= 2;
else
retryTime = 900_000;
return of(retryTime);
}))
.subscribe(data => {
if (data)
this.setRefreshTokenExpireMs(data);
this.tokenRefreshSubscription = interval(this.refreshTokenExpireMs).pipe(
filter(isRefreshing => !isRefreshing),
switchMap(() => {
this.tokenRefreshing$.next(true);
console.debug('Send query to refresh token');
return this.authService.refreshToken();
})
).subscribe({
next: (_) => {
this.tokenRefreshing$.next(false);
});
},
error: error => {
this.tokenRefreshing$.next(false);
localStorage.removeItem(ApiService.tokenKey);
}
});
}
public getTokenRefreshing$(): Subject<boolean> {
public getTokenRefreshing$(): BehaviorSubject<boolean> {
return this.tokenRefreshing$;
}
public setRefreshTokenExpireMs(expireMs: number | string | Date | null = null): void {
let expireMsNumber: number;
if (expireMs === null)
expireMsNumber = -1;
else if (expireMs instanceof Date || typeof expireMs === 'string')
expireMsNumber = new Date(expireMs).getTime() - 1000 - Date.now();
else
expireMsNumber = expireMs;
public stopTokenRefresh(): void {
if (this.tokenRefreshSubscription && !this.tokenRefreshSubscription.closed) {
this.tokenRefreshSubscription.unsubscribe();
this.tokenRefreshSubscription = undefined;
}
}
if (expireMsNumber < environment.retryDelay)
expireMsNumber = environment.retryDelay;
public setRefreshTokenExpireMs(expireMs: number): void {
if (expireMs < environment.retryDelay)
expireMs = environment.retryDelay;
this.refreshTokenExpireMs = expireMsNumber;
console.log('New refresh token interval:', this.refreshTokenExpireMs);
this.refreshTokenExpireMs = expireMs;
clearTimeout(this.refreshTokenTimeout);
console.log(expireMs);
this.stopTokenRefresh();
this.startTokenRefresh();
}
}