Skip to content

Commit

Permalink
(feat-ng-ui): 优化登录逻辑,简化代码结构并移除未使用的代码
Browse files Browse the repository at this point in the history
  • Loading branch information
vnobo committed Jul 24, 2024
1 parent e004e52 commit 4f221d6
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class MenusService extends AbstractDatabase {

public Flux<Menu> search(MenuRequest request) {
var cacheKey = BeanUtils.cacheKey(request);
Query query = Query.query(request.toCriteria()).sort(Sort.by("sort"));
Query query = Query.query(request.toCriteria()).sort(Sort.by("sortNo"));
return this.queryWithCache(cacheKey, query, Menu.class)
.flatMapSequential(ContextUtils::serializeUserAuditor);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
*/
@Data
public class CommandRequest implements Serializable {

private MessageType type;
private String command;
private String content;

}
2 changes: 1 addition & 1 deletion ng-ui/projects/web/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { NzLayoutModule } from 'ng-zorro-antd/layout';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NzBackTopModule, NzSpinModule, MatProgressBarModule, CommonModule, NzLayoutModule],
imports: [CommonModule, RouterOutlet, NzBackTopModule, NzSpinModule, MatProgressBarModule, NzLayoutModule],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
Expand Down
18 changes: 15 additions & 3 deletions ng-ui/projects/web/src/app/home/index/index.component.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Component, OnInit, signal } from '@angular/core';
import { Component, OnDestroy, OnInit, signal } from '@angular/core';
import { RouterModule } from '@angular/router';
import { PageHeaderComponent } from '../../../core/components/page-header/page-header.component';
import { MessageOut, RSocketCLientService } from '../../../core/rsocket.service';
import { NgFor } from '@angular/common';
import { Subject } from 'rxjs/internal/Subject';
import { debounceTime, distinctUntilChanged, takeUntil } from 'rxjs/operators';

@Component({
selector: 'home-index',
Expand All @@ -11,12 +13,22 @@ import { NgFor } from '@angular/common';
templateUrl: './index.component.html',
styleUrl: './index.component.scss',
})
export class IndexComponent implements OnInit {
export class IndexComponent implements OnInit, OnDestroy {
dataSet = signal([] as MessageOut[]);

private componentDestroyed$: Subject<void> = new Subject<void>();

constructor(private _rsocket: RSocketCLientService) {}

ngOnInit(): void {
this._rsocket.requestStream('request.stream').subscribe(res => this.dataSet.update(value => [...value, res]));
this._rsocket
.requestStream('request.stream')
.pipe(takeUntil(this.componentDestroyed$), debounceTime(100), distinctUntilChanged())
.subscribe(res => this.dataSet.update(value => [...value, res]));
}

ngOnDestroy(): void {
this.componentDestroyed$.next();
this.componentDestroyed$.complete();
}
}
5 changes: 1 addition & 4 deletions ng-ui/projects/web/src/core/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { inject, Injectable, signal } from '@angular/core';
import { CanActivateChildFn, CanActivateFn, CanMatchFn, Router } from '@angular/router';
import dayjs from 'dayjs';
import { SessionStorageService } from '../shared/session-storage.service';
import { RSocketCLientService } from './rsocket.service';

export interface Authentication {
token: string;
Expand All @@ -23,10 +22,9 @@ export const authGuard: CanMatchFn | CanActivateFn | CanActivateChildFn = () =>

@Injectable({ providedIn: 'root' })
export class AuthService {
private _socket = inject(RSocketCLientService);
private _storage = inject(SessionStorageService);

readonly loginUrl = '/auth/login';
private _storage: SessionStorageService = inject(SessionStorageService);
private readonly authenticationKey = 'authentication';
private isLoggedIn = signal(false);
private authentication = signal({} as Authentication);
Expand Down Expand Up @@ -74,7 +72,6 @@ export class AuthService {
this.isLoggedIn.set(true);
this.authentication.set(authentication);
this._storage.set(this.authenticationKey, JSON.stringify(authentication));
this._socket.connect(authentication.token);
}

logout(): void {
Expand Down
16 changes: 11 additions & 5 deletions ng-ui/projects/web/src/core/components/login/login.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Observable, tap } from 'rxjs';
import { Authentication, AuthService } from '../../auth.service';
import { BrowserStorageService } from '../../../shared/browser-storage.service';
import dayjs from 'dayjs';
import { RSocketCLientService } from '../../rsocket.service';

export interface Credentials {
password: string | null | undefined;
Expand All @@ -15,8 +16,9 @@ export interface Credentials {
})
export class LoginService {
_auth = inject(AuthService);
_http = inject(HttpClient);
_storage = inject(BrowserStorageService);
private _http = inject(HttpClient);
private _storage = inject(BrowserStorageService);
private _socket = inject(RSocketCLientService);

private readonly storageKey = 'credentials';
private credentials = signal({} as Credentials);
Expand All @@ -26,6 +28,7 @@ export class LoginService {
if (authentication) {
authentication.lastAccessTime = dayjs().unix();
this._auth.login(authentication);
this._socket.connect(authentication.token);
return authentication;
}
return null;
Expand All @@ -35,9 +38,12 @@ export class LoginService {
const headers: HttpHeaders = new HttpHeaders({
authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password),
});
return this._http
.get<Authentication>('/oauth2/token', { headers: headers })
.pipe(tap(authentication => this._auth.login(authentication)));
return this._http.get<Authentication>('/oauth2/token', { headers: headers }).pipe(
tap(authentication => {
this._auth.login(authentication);
this._socket.connect(authentication.token);
})
);
}

setRememberMe(credentials: Credentials) {
Expand Down
6 changes: 4 additions & 2 deletions ng-ui/projects/web/src/core/http.Interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ export function authTokenInterceptor(req: HttpRequest<unknown>, next: HttpHandle

return next(authReq).pipe(
catchError(errorResponse => {
_auth.logout();
_route.navigate([_auth.loginUrl]).then();
if (errorResponse.status === 401) {
_auth.logout();
_route.navigate([_auth.loginUrl]).then();
}
return throwError(() => errorResponse);
})
);
Expand Down
82 changes: 43 additions & 39 deletions ng-ui/projects/web/src/core/rsocket.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
MESSAGE_RSOCKET_ROUTING,
RSocketClient,
} from 'rsocket-core';
import { Single } from 'rsocket-flowable';
import { ReactiveSocket } from 'rsocket-types';
import RSocketWebSocketClient from 'rsocket-websocket-client';
import { Observable } from 'rxjs';
Expand All @@ -35,11 +34,11 @@ export class RSocketCLientService {
BufferEncoders
);

private socketClient: Single<ReactiveSocket<Buffer, Buffer>> | null = null;
private socketClient: ReactiveSocket<Buffer, Buffer> | null = null;
private token: string | null = null;

connect(token: string) {
const socketClient = new RSocketClient({
const client = new RSocketClient({
setup: {
// ms btw sending keepalive to server
keepAlive: 6000,
Expand All @@ -58,18 +57,30 @@ export class RSocketCLientService {
transport: this.transport,
});
this.token = token;
this.socketClient = socketClient.connect();
client.connect().subscribe({
onComplete: socket => (this.socketClient = socket),
onError: error => console.error(error),
});
}

connectionStatus() {
if (this.socketClient === null) {
throw new Error('socketClient is null');
}
this.socketClient.then(socket => {
socket.connectionStatus().subscribe(event => console.log(`connectionStatus :${event.kind}`));
this.socketClient.connectionStatus().subscribe(event => {
console.log(`connectionStatus :${event.kind}`);
if (event.kind !== 'CONNECTED') {
if (this.token === null) {
console.error('token 不能为空!,请先调用 connect 方法设置!');
return;
}
this.connect(this.token);
}
});
}

requestStream(route?: string): Observable<MessageOut> {
console.log('requestStream');
route = route || 'request.stream';
const observable = new Observable<MessageOut>(subscriber => {
if (this.socketClient === null) {
Expand All @@ -81,39 +92,32 @@ export class RSocketCLientService {
return;
}
const token = this.token;
this.socketClient.subscribe({
onComplete: socket =>
socket
.requestStream({
data: Buffer.from(token),
metadata: encodeCompositeMetadata([[MESSAGE_RSOCKET_ROUTING, encodeRoute(route)]]),
})
.subscribe({
onComplete: () => {
console.log('complete');
subscriber.complete();
},
onError: error => {
console.log('Connection has been closed due to:: ' + error);
subscriber.error(error);
},
onNext: value => {
const jsonStr = value.data?.toString();
if (jsonStr !== undefined && jsonStr !== null) {
console.log('onNext: %s,%s', value.data, value.metadata);
subscriber.next(JSON.parse(jsonStr));
}
},
onSubscribe: subscription => {
console.log('onNext: %s,%s', subscription);
subscription.request(2147483647);
},
}),
onError: error => {
console.log('error:', error);
subscriber.error(error);
},
});
this.socketClient
.requestStream({
data: Buffer.from(token),
metadata: encodeCompositeMetadata([[MESSAGE_RSOCKET_ROUTING, encodeRoute(route)]]),
})
.subscribe({
onComplete: () => {
console.log('complete');
subscriber.complete();
},
onError: error => {
console.log('Connection has been closed due to:: ' + error);
subscriber.error(error);
},
onNext: value => {
const jsonStr = value.data?.toString();
if (jsonStr !== undefined && jsonStr !== null) {
console.log('onNext: %s,%s', value.data, value.metadata);
subscriber.next(JSON.parse(jsonStr));
}
},
onSubscribe: subscription => {
console.log('onNext: %s,%s', subscription);
subscription.request(2147483647);
},
});
});
return observable;
}
Expand Down

0 comments on commit 4f221d6

Please sign in to comment.