Finished implementing sign-in procedure for API/v3. Updated guards to V3 and started rewriting /chat too. UserData updating and multi-user support is TODO
This commit is contained in:
14
package-lock.json
generated
14
package-lock.json
generated
@@ -36,6 +36,7 @@
|
||||
"chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.4",
|
||||
"libphonenumber-js": "^1.12.41",
|
||||
"ngx-cookie-service": "^21.3.1",
|
||||
"ngx-device-detector": "^11.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"uuid": "^13.0.0"
|
||||
@@ -8954,6 +8955,19 @@
|
||||
"@angular/core": "^21.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ngx-device-detector": {
|
||||
"version": "11.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ngx-device-detector/-/ngx-device-detector-11.0.0.tgz",
|
||||
"integrity": "sha512-vQ07MpUvVKgxGMPmNvbZ9mUcgH4cH0KMVCj9skMOciPh4sBUKNsorWE/FUs2eSYiLbtu7oq1JcPMcRuEWZ1rug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@angular/common": "^21.0.0",
|
||||
"@angular/core": "^21.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ngx-highlightjs": {
|
||||
"version": "14.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ngx-highlightjs/-/ngx-highlightjs-14.0.1.tgz",
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.4",
|
||||
"libphonenumber-js": "^1.12.41",
|
||||
"ngx-cookie-service": "^21.3.1",
|
||||
"ngx-device-detector": "^11.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"uuid": "^13.0.0"
|
||||
|
||||
@@ -21,7 +21,7 @@ export const appConfig: ApplicationConfig = {
|
||||
provideTaiga(),
|
||||
provideTranslateService({
|
||||
fallbackLang: 'en',
|
||||
lang: 'hu',
|
||||
lang: 'en',
|
||||
loader: provideTranslateHttpLoader({
|
||||
prefix: '/i18n/',
|
||||
suffix: '.json',
|
||||
|
||||
@@ -4,6 +4,7 @@ import { RouterOutlet } from '@angular/router';
|
||||
import { environment as env } from '../environments/environment';
|
||||
import { environment, SDKConfig } from '@chatenium/chatenium-sdk/core/environment';
|
||||
import { IndexedDB } from './storage/indexed-db';
|
||||
import { SessionManager } from './session-manager';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -13,6 +14,7 @@ import { IndexedDB } from './storage/indexed-db';
|
||||
})
|
||||
export class App implements OnInit {
|
||||
indexedDb = inject(IndexedDB);
|
||||
sessionManager = inject(SessionManager);
|
||||
|
||||
protected readonly title = signal('Chatenium-On-Web');
|
||||
|
||||
@@ -22,5 +24,8 @@ export class App implements OnInit {
|
||||
apiUrl: env.api_url,
|
||||
wsUrl: env.ws_url,
|
||||
});
|
||||
this.indexedDb.openDatabase().then(() => {
|
||||
this.sessionManager.loadSessions();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
<user-settings (close)="userSettingsOpen.set(false)" />
|
||||
</ng-template>
|
||||
|
||||
@if (serviceManager.currentSession() == null) {
|
||||
@if (sessionManager.userData() == undefined) {
|
||||
<main style="width: 100%; height: 100svh; display: flex; justify-content: center; align-items: center;">
|
||||
<tui-loader size="xl" />
|
||||
</main>
|
||||
@@ -44,7 +44,7 @@
|
||||
</aside>
|
||||
|
||||
<main>
|
||||
@switch (navigationActiveIndex) {
|
||||
<!-- @switch (navigationActiveIndex) {
|
||||
@case (0) {
|
||||
<app-dm-list [token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-dm-list>
|
||||
@@ -59,7 +59,7 @@
|
||||
<app-picture-list [token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list>
|
||||
}
|
||||
}
|
||||
}-->
|
||||
</main>
|
||||
</aside>
|
||||
|
||||
@@ -85,6 +85,7 @@
|
||||
@if (!routerOutletActive()) {
|
||||
<div id="navigation">
|
||||
<div id="navigation_content">
|
||||
<!--
|
||||
@switch (navigationActiveIndex) {
|
||||
@case (0) {
|
||||
<app-dm-list [token]="serviceManager.currentSession()!.token"
|
||||
@@ -104,6 +105,7 @@
|
||||
<user-settings />
|
||||
}
|
||||
}
|
||||
-->
|
||||
</div>
|
||||
|
||||
<nav tuiTabBar [(activeItemIndex)]="navigationActiveIndex">
|
||||
|
||||
@@ -2,7 +2,6 @@ import {Component, computed, inject, OnInit, signal} from '@angular/core';
|
||||
import {isActive, IsActiveMatchOptions, Router, RouterOutlet} from '@angular/router';
|
||||
import {TuiSegmented} from '@taiga-ui/kit';
|
||||
import {TUI_BREAKPOINT, TuiAppearance, TuiButton, TuiDialog, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import {LoadStatus, ServiceManager} from '../service-manager';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {DmList} from './dm-list/dm-list';
|
||||
@@ -16,6 +15,7 @@ import {PictureList} from './picture-list/picture-list';
|
||||
import {UserSettings} from './user-settings/user-settings';
|
||||
import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
|
||||
import {UserService} from '@chatenium/chatenium-sdk/services/userService';
|
||||
import { SessionManager } from '../session-manager';
|
||||
|
||||
@Component({
|
||||
selector: 'app-chat',
|
||||
@@ -41,6 +41,7 @@ import {UserService} from '@chatenium/chatenium-sdk/services/userService';
|
||||
styleUrl: './chat.scss',
|
||||
})
|
||||
export class Chat implements OnInit {
|
||||
sessionManager = inject(SessionManager);
|
||||
serviceManager = inject(ServiceManager)
|
||||
indexedDb = inject(IndexedDB)
|
||||
breakpoint = inject(TUI_BREAKPOINT)
|
||||
|
||||
@@ -6,7 +6,7 @@ export const CHATENIUM_SDK = new InjectionToken<ChateniumClient>('CHATENIUM_SDK'
|
||||
providedIn: 'root',
|
||||
factory: () => {
|
||||
return new ChateniumClient({
|
||||
baseUrl: environment.api_url
|
||||
baseUrl: environment.api_url,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {inject} from '@angular/core';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {Keyring} from '../storage/keyring';
|
||||
import {KeyValue} from '../storage/key-value';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import { SessionManager } from '../session-manager';
|
||||
|
||||
export const authNeededGuard: CanActivateFn = (route, state) => {
|
||||
const indexedDb = inject(IndexedDB)
|
||||
const keyring = inject(Keyring)
|
||||
const keyValue = inject(KeyValue)
|
||||
const router = inject(Router)
|
||||
const sessionManager = inject(SessionManager);
|
||||
const idb = inject(IndexedDB);
|
||||
const router = inject(Router);
|
||||
|
||||
indexedDb.openDatabase().then(async () => {
|
||||
const sessionManager = new SessionManager(indexedDb.getApi(), keyring.getApi(), keyValue.getApi());
|
||||
const sessions = await sessionManager.loadSessions()
|
||||
|
||||
if (sessions.length == 0) {
|
||||
router.navigate(['/signin'])
|
||||
idb.openDatabase().then(async () => {
|
||||
if (!sessionManager.quickSignInCheck()) {
|
||||
await router.navigate(['/chat']);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import {inject} from '@angular/core';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {Keyring} from '../storage/keyring';
|
||||
import {KeyValue} from '../storage/key-value';
|
||||
import { SessionManager } from '../session-manager';
|
||||
|
||||
export const noAuthGuard: CanActivateFn = async (route, state) => {
|
||||
const indexedDb = inject(IndexedDB)
|
||||
const keyring = inject(Keyring)
|
||||
const keyValue = inject(KeyValue)
|
||||
const sessionManager = inject(SessionManager);
|
||||
const idb = inject(IndexedDB);
|
||||
const router = inject(Router)
|
||||
|
||||
indexedDb.openDatabase().then(async () => {
|
||||
const sessionManager = new SessionManager(indexedDb.getApi(), keyring.getApi(), keyValue.getApi());
|
||||
const sessions = await sessionManager.loadSessions()
|
||||
|
||||
if (sessions.length != 0) {
|
||||
router.navigate(['/chat'])
|
||||
idb.openDatabase().then(async () => {
|
||||
if (sessionManager.quickSignInCheck()) {
|
||||
await router.navigate(['/chat'])
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
16
src/app/session-manager.spec.ts
Normal file
16
src/app/session-manager.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { SessionManager } from './session-manager';
|
||||
|
||||
describe('SessionManager', () => {
|
||||
let service: SessionManager;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(SessionManager);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
100
src/app/session-manager.ts
Normal file
100
src/app/session-manager.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { inject, Injectable, signal } from '@angular/core';
|
||||
import { IndexedDB } from './storage/indexed-db';
|
||||
import { CookieService } from 'ngx-cookie-service';
|
||||
import { CHATENIUM_SDK } from './chatenium.token';
|
||||
import { PersonalUserData, SuccessfulAuthResp } from 'chatenium-sdk-preview';
|
||||
import { TuiNotificationService } from '@taiga-ui/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SessionManager {
|
||||
private SDK = inject(CHATENIUM_SDK);
|
||||
private idb = inject(IndexedDB);
|
||||
private cookie = inject(CookieService);
|
||||
private notification = inject(TuiNotificationService);
|
||||
|
||||
public userData = signal<PersonalUserData|undefined>(undefined);
|
||||
|
||||
async addSession(refreshToken: string, accessToken: string, userId: string) {
|
||||
const date = new Date();
|
||||
date.setFullYear(date.getFullYear() + 5);
|
||||
this.cookie.set(`token_${userId}`, refreshToken, {
|
||||
expires: date,
|
||||
path: '/',
|
||||
secure: true,
|
||||
sameSite: 'Strict',
|
||||
});
|
||||
|
||||
this.SDK.addHeader('Authorization', accessToken);
|
||||
try {
|
||||
const resp = await this.SDK.account.getPersonalUserData();
|
||||
const data = resp.data as PersonalUserData;
|
||||
this.idb.putObject('userData', data, data.userId);
|
||||
} catch (error) {
|
||||
this.notification
|
||||
.open('PersonalUserData fetch failed. Did header refresh fail?', { appearance: 'negative' })
|
||||
.subscribe();
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async loadSessions() {
|
||||
const cookies = this.cookie.getAll();
|
||||
for (const [key, value] of Object.entries(cookies)) {
|
||||
if (key.startsWith('token')) {
|
||||
const userId = key.split('_')[1];
|
||||
const userData = (await this.idb.get('userData', userId)) as PersonalUserData;
|
||||
console.log(`Found saved session for ID: ${userId} Username: ${userData.displayName}`);
|
||||
this.userData.set(userData);
|
||||
await this.rotateTokenPair();
|
||||
break; // For the moment, the client just loads the first session saved
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quickly checks saved cookies and determines if the user is signed-in or not
|
||||
*/
|
||||
quickSignInCheck(): boolean {
|
||||
const cookies = this.cookie.getAll();
|
||||
for (const [key, value] of Object.entries(cookies)) {
|
||||
if (key.startsWith('token')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async rotateTokenPair() {
|
||||
const userData = this.userData();
|
||||
|
||||
if (userData != undefined) {
|
||||
const refreshToken = this.cookie.get(`token_${userData.userId}`);
|
||||
|
||||
try {
|
||||
const resp = await this.SDK.auth.rotateTokenPair(refreshToken);
|
||||
const data = resp.data as SuccessfulAuthResp;
|
||||
|
||||
const date = new Date();
|
||||
date.setFullYear(date.getFullYear() + 5);
|
||||
this.cookie.set(`token_${data.userId}`, data.refreshToken, {
|
||||
expires: date,
|
||||
path: '/',
|
||||
secure: true,
|
||||
sameSite: 'Strict',
|
||||
});
|
||||
|
||||
this.SDK.addHeader('Authorization', data.accessToken);
|
||||
console.log(
|
||||
`Successfully rotated token pair for ID: ${userData.userId} Username: ${userData.username}. This session is now ready to be used.`,
|
||||
);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
} else {
|
||||
console.error('Token refresh failed - No user data loaded');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,27 @@
|
||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
||||
import {TuiAppearance, TuiButton, TuiError, TuiErrorDirective, TuiGroup, TuiIcon, TuiInput, TuiTextfield} from '@taiga-ui/core';
|
||||
import {
|
||||
TuiAlertService,
|
||||
TuiAppearance,
|
||||
TuiButton,
|
||||
TuiError,
|
||||
TuiErrorDirective,
|
||||
TuiGroup,
|
||||
TuiIcon,
|
||||
TuiInput,
|
||||
TuiNotificationService,
|
||||
TuiTextfield,
|
||||
} from '@taiga-ui/core';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import {TuiButtonGroup, TuiPassword} from '@taiga-ui/kit';
|
||||
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
|
||||
import {AuthMethods} from '@chatenium/chatenium-sdk/domain/authService.schema';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import {ServiceManager} from '../service-manager';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {PublicUserData} from '@chatenium/chatenium-sdk/domain/common.schema';
|
||||
import {Router} from '@angular/router';
|
||||
import { CHATENIUM_SDK } from '../chatenium.token';
|
||||
import { AuthChallenge, Challenge } from 'chatenium-sdk-preview';
|
||||
import { AuthChallenge, Challenge, SignInReq, SuccessfulAuthResp } from 'chatenium-sdk-preview';
|
||||
import { TuiItemGroup } from '@taiga-ui/layout';
|
||||
import { faApple, faGoogle } from '@fortawesome/free-brands-svg-icons';
|
||||
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
|
||||
@@ -19,6 +29,9 @@ import { JsonPipe } from '@angular/common';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { GoogleOAuth } from '../google-oauth';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { SessionManager } from '../session-manager';
|
||||
import { Platform } from '@angular/cdk/platform';
|
||||
import { DeviceDetectorService } from 'ngx-device-detector';
|
||||
|
||||
@Component({
|
||||
selector: 'app-signin',
|
||||
@@ -42,6 +55,9 @@ import { environment } from '../../environments/environment';
|
||||
export class SignIn implements OnInit {
|
||||
SDK = inject(CHATENIUM_SDK);
|
||||
googleOAuth = inject(GoogleOAuth);
|
||||
sessionManager = inject(SessionManager);
|
||||
device = inject(DeviceDetectorService);
|
||||
notification = inject(TuiNotificationService);
|
||||
|
||||
private googleSub?: Subscription;
|
||||
|
||||
@@ -125,6 +141,7 @@ export class SignIn implements OnInit {
|
||||
this.page.set('methodChoose');
|
||||
this.authForm.reset();
|
||||
} else {
|
||||
await this.signIn(resp.authIdentityToken);
|
||||
this.page.set('ok');
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -135,6 +152,20 @@ export class SignIn implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
private async signIn(authIdentityToken: string) {
|
||||
try {
|
||||
const resp = await this.SDK.auth.signIn(authIdentityToken, {
|
||||
os: this.device.deviceInfo().os,
|
||||
frontend: "nexum"
|
||||
})
|
||||
const data = resp.data as SuccessfulAuthResp;
|
||||
await this.sessionManager.addSession(data.refreshToken, data.accessToken, data.userId);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
this.notification.open('SignIn Failed', { appearance: "negative" }).subscribe();
|
||||
}
|
||||
}
|
||||
|
||||
async requestCredential(methodName: string) {
|
||||
this.pendingAction.set(true);
|
||||
if (this.challengeApi != null) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import {DatabaseAPI} from '@chatenium/chatenium-sdk/storage/database';
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class IndexedDB {
|
||||
private dbVersion = 3
|
||||
private dbVersion = 4
|
||||
private db: IDBDatabase | null = null
|
||||
|
||||
getApi(): DatabaseAPI {
|
||||
@@ -30,12 +30,12 @@ export class IndexedDB {
|
||||
|
||||
request.onupgradeneeded = (e: IDBVersionChangeEvent) => {
|
||||
const db = (e.target as IDBOpenDBRequest).result;
|
||||
db.createObjectStore('sessions', { keyPath: 'id' })
|
||||
db.createObjectStore('chats', { keyPath: 'id' })
|
||||
db.createObjectStore('networks', { keyPath: 'id' })
|
||||
db.createObjectStore('userData', { keyPath: 'id' })
|
||||
db.createObjectStore('contacts', { keyPath: 'id' })
|
||||
db.createObjectStore('cascades', { keyPath: 'id' })
|
||||
db.createObjectStore('files', { keyPath: 'id' })
|
||||
db.createObjectStore('messages', { keyPath: 'id' })
|
||||
db.createObjectStore('networkmessages', { keyPath: 'id' })
|
||||
db.createObjectStore('threadMessages', { keyPath: 'id' })
|
||||
db.createObjectStore('pictures', { keyPath: 'id' })
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ export class IndexedDB {
|
||||
});
|
||||
}
|
||||
|
||||
get(storeName: string, key: string): Promise<string> {
|
||||
get(storeName: string, key: string): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.db) {
|
||||
const transaction = this.db.transaction([storeName], "readonly");
|
||||
|
||||
Reference in New Issue
Block a user