Compare commits
3 Commits
3.0-beta11
...
3ef5387b8d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ef5387b8d | ||
|
|
086d27c9a4 | ||
|
|
eeee9d5154 |
1455
package-lock.json
generated
1455
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -36,8 +36,10 @@
|
||||
"@taiga-ui/icons": "^5.25.0",
|
||||
"@taiga-ui/kit": "^5.25.0",
|
||||
"@taiga-ui/layout": "^5.25.0",
|
||||
"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"
|
||||
@@ -46,6 +48,7 @@
|
||||
"@angular/build": "^21.2.6",
|
||||
"@angular/cli": "^21.2.6",
|
||||
"@angular/compiler-cli": "^21.2.0",
|
||||
"@types/google.accounts": "^0.0.18",
|
||||
"jsdom": "^28.0.0",
|
||||
"less": "^4.6.4",
|
||||
"prettier": "^3.8.1",
|
||||
|
||||
@@ -79,7 +79,9 @@
|
||||
"microsoftStoreDesc": "Start testing the application on your Windows computer via the Microsoft Store!"
|
||||
},
|
||||
"signIn": {
|
||||
"formTitle": "Sign in",
|
||||
"initial": {
|
||||
"formTitle": "Welcome back!",
|
||||
"formSubtitle": "Sign in with your Chatenium account.",
|
||||
"mainInput": {
|
||||
"label": "Username, email or phone number",
|
||||
"placeholder": "bob, bob@example.com, +36201234567"
|
||||
@@ -87,15 +89,59 @@
|
||||
"password": {
|
||||
"label": "Password"
|
||||
},
|
||||
"emailButton": "Sign in with email code",
|
||||
"smsButton": "Sign in with SMS code",
|
||||
"signInButton": "Sign in",
|
||||
"signInButton": "Sign in"
|
||||
},
|
||||
"methodChoose": {
|
||||
"formTitle": "Choose a verification method",
|
||||
"formSubtitle": "Based on your security settings, more than 1 verification method may be required.",
|
||||
"formTitleAlt": "Choose another verification method",
|
||||
"formSubtitleAlt": "Because of your security settings, multiple verification methods are required",
|
||||
"methods": {
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"desc": "Use your password to verify your identity"
|
||||
},
|
||||
"mail": {
|
||||
"title": "E-mail",
|
||||
"desc": "Use a one-time e-mail code to verify your identity"
|
||||
},
|
||||
"sms": {
|
||||
"title": "SMS",
|
||||
"desc": "Use a one-time SMS code to verify your identity"
|
||||
},
|
||||
"google": {
|
||||
"title": "Google",
|
||||
"desc": "Use your linked Google account to verify your identity"
|
||||
},
|
||||
"apple": {
|
||||
"title": "Apple",
|
||||
"desc": "Use your linked Apple account to verify your identity"
|
||||
}
|
||||
}
|
||||
},
|
||||
"anyAuth": {
|
||||
"verifyButton": "Verify identity"
|
||||
},
|
||||
"passwordAuth": {
|
||||
"formTitle": "Password authentication",
|
||||
"formSubtitle": "Enter your password below",
|
||||
"errors": {
|
||||
"unameMailPhoneRequired": "Username, email or phone number is required",
|
||||
"passwordRequired": "Password is required",
|
||||
"passwordIncorrect": "Password is incorrect"
|
||||
}
|
||||
},
|
||||
"emailAuth": {
|
||||
"formTitle": "E-mail authentication",
|
||||
"formSubtitle": "Enter your one-time e-mail code below",
|
||||
"errors": {
|
||||
"passwordRequired": "Code is required",
|
||||
"passwordIncorrect": "Code is incorrect"
|
||||
},
|
||||
"emailCode": {
|
||||
"label": "E-mail code"
|
||||
}
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"userSettingsDialog": {
|
||||
"label": "Settings",
|
||||
|
||||
@@ -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)
|
||||
|
||||
12
src/app/chatenium.token.ts
Normal file
12
src/app/chatenium.token.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
import { environment } from '../environments/environment';
|
||||
import { ChateniumClient } from 'chatenium-sdk-preview';
|
||||
|
||||
export const CHATENIUM_SDK = new InjectionToken<ChateniumClient>('CHATENIUM_SDK', {
|
||||
providedIn: 'root',
|
||||
factory: () => {
|
||||
return new ChateniumClient({
|
||||
baseUrl: environment.api_url,
|
||||
});
|
||||
},
|
||||
});
|
||||
16
src/app/google-oauth.spec.ts
Normal file
16
src/app/google-oauth.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { GoogleOAuth } from './google-oauth';
|
||||
|
||||
describe('GoogleOAuth', () => {
|
||||
let service: GoogleOAuth;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(GoogleOAuth);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
30
src/app/google-oauth.ts
Normal file
30
src/app/google-oauth.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { inject, Injectable, NgZone } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class GoogleOAuth {
|
||||
private ngZone = inject(NgZone);
|
||||
private codeClient?: google.accounts.oauth2.CodeClient;
|
||||
private codeSubject = new Subject<string>();
|
||||
|
||||
readonly code$ = this.codeSubject.asObservable();
|
||||
|
||||
init(clientId: string): void {
|
||||
this.codeClient = google.accounts.oauth2.initCodeClient({
|
||||
client_id: clientId,
|
||||
scope: 'openid email profile',
|
||||
ux_mode: 'popup',
|
||||
callback: (response) => {
|
||||
if (response.code) {
|
||||
this.ngZone.run(() => this.codeSubject.next(response.code));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openSignIn(): void {
|
||||
this.codeClient?.requestCode();
|
||||
}
|
||||
}
|
||||
@@ -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,44 +1,163 @@
|
||||
<main id="holder">
|
||||
<form [formGroup]="signInForm" tuiAppearance="floating">
|
||||
@switch (page()) {
|
||||
@case ('initial') {
|
||||
<form [formGroup]="signInForm" tuiAppearance="floating" id="initial" animate.enter="slide-in-right"
|
||||
animate.leave="slide-out-left">
|
||||
<header>
|
||||
<h1>{{"signIn.formTitle"|translate}}</h1>
|
||||
<h1>{{ "signIn.initial.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.initial.formSubtitle"|translate }}</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<tui-textfield iconStart="@tui.user">
|
||||
<label tuiLabel>{{"signIn.mainInput.label"|translate}}</label>
|
||||
<label tuiLabel>{{ "signIn.initial.mainInput.label"|translate }}</label>
|
||||
|
||||
<input (input)="checkAuthMethods(signInForm.controls['unameMailPhone'].value)" formControlName="unameMailPhone" tuiInput placeholder="{{'signIn.mainInput.placeholder'|translate}}">
|
||||
<input (input)="checkAuthMethods(signInForm.controls['unameMailPhone'].value)"
|
||||
formControlName="unameMailPhone" tuiInput
|
||||
placeholder="{{'signIn.initial.mainInput.placeholder'|translate}}">
|
||||
</tui-textfield>
|
||||
@if (signInForm.controls["unameMailPhone"].dirty) {
|
||||
@if (signInForm.controls["unameMailPhone"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.errors.unameMailPhoneRequired'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
|
||||
<tui-textfield iconStart="@tui.key">
|
||||
<label tuiLabel>{{"signIn.password.label"|translate}}</label>
|
||||
<input formControlName="password" [disabled]="!methods().password" type="password" tuiInput>
|
||||
<tui-icon tuiPassword></tui-icon>
|
||||
</tui-textfield>
|
||||
@if (signInForm.controls["password"].dirty) {
|
||||
@if (signInForm.controls["password"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.errors.passwordRequired'|translate"></tui-error>
|
||||
} @else if (signInForm.controls["password"].hasError("incorrect")) {
|
||||
<tui-error [error]="'signIn.errors.passwordIncorrect'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
|
||||
<div id="methods">
|
||||
<button [disabled]="!methods().email" iconStart="@tui.mail-open" appearance="secondary" tuiButton disabled>{{'signIn.emailButton'|translate}}</button>
|
||||
<button [disabled]="!methods().sms" iconStart="@tui.phone" appearance="secondary" tuiButton disabled>{{'signIn.smsButton'|translate}}</button>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<button (click)="passwordSignIn(signInForm.controls['unameMailPhone'].value, signInForm.controls['password'].value)" [disabled]="signInForm.invalid || !methods().password" tuiButton>
|
||||
{{'signIn.signInButton'|translate}}
|
||||
<button (click)="startChallenge(signInForm.controls['unameMailPhone'].value)"
|
||||
[disabled]="signInForm.invalid && false || pendingAction()" tuiButton>
|
||||
{{ 'signIn.initial.signInButton'|translate }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
}
|
||||
@case ('methodChoose') {
|
||||
<form id="methodChoose" animate.enter="slide-in-right" animate.leave="slide-out-left">
|
||||
<header>
|
||||
@if (isMultistep()) {
|
||||
<h1>{{ "signIn.methodChoose.formTitleAlt"|translate }}</h1>
|
||||
<span>{{ "signIn.methodChoose.formSubtitleAlt"|translate }}</span>
|
||||
} @else {
|
||||
<h1>{{ "signIn.methodChoose.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.methodChoose.formSubtitle"|translate }}</span>
|
||||
}
|
||||
</header>
|
||||
|
||||
<main tuiGroup orientation="vertical" style="gap: 0">
|
||||
@if (challenge != null) {
|
||||
@if (challenge()!.factorsTracker["PASSWORD"] != null) {
|
||||
<button [disabled]="challenge()!.factorsTracker['PASSWORD'].status == 'SUCCESS'" type="button" tuiButton
|
||||
appearance="secondary" class="method" (click)="this.page.set('passwordAuth')">
|
||||
<tui-icon icon="@tui.key"></tui-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.password.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.password.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
@if (challenge()!.factorsTracker["EMAIL"] != null) {
|
||||
<button type="button"
|
||||
[disabled]="challenge()!.factorsTracker['EMAIL'].status == 'SUCCESS' || pendingAction()" tuiButton
|
||||
appearance="secondary" class="method" (click)="this.requestCredential('EMAIL')">
|
||||
<tui-icon icon="@tui.mail"></tui-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.mail.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.mail.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
<button tuiButton appearance="secondary" class="method">
|
||||
<tui-icon icon="@tui.phone"></tui-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.sms.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.sms.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
@if (challenge()!.factorsTracker["GOOGLE"] != null) {
|
||||
<button type="button" tuiButton appearance="secondary" class="method"
|
||||
(click)="this.googleOAuth.openSignIn();" [disabled]="challenge()!.factorsTracker['GOOGLE'].status == 'SUCCESS' || pendingAction()">
|
||||
<fa-icon [icon]="faGoogle" style="font-size: 25px; margin-left: -5px"></fa-icon>
|
||||
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.google.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.google.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
<button tuiButton appearance="secondary" class="method">
|
||||
<fa-icon [icon]="faApple" style="font-size: 30px; margin-left: -7px"></fa-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.apple.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.apple.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
</main>
|
||||
</form>
|
||||
}
|
||||
@case ('passwordAuth') {
|
||||
<form [formGroup]="authForm" tuiAppearance="floating" id="passwordAuth" animate.enter="slide-in-right"
|
||||
animate.leave="slide-out-left">
|
||||
<header>
|
||||
<h1>{{ "signIn.passwordAuth.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.passwordAuth.formSubtitle"|translate }}</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<tui-textfield iconStart="@tui.key">
|
||||
<label tuiLabel>{{ "signIn.initial.password.label"|translate }}</label>
|
||||
<input formControlName="method" type="password" tuiInput>
|
||||
<tui-icon tuiPassword></tui-icon>
|
||||
</tui-textfield>
|
||||
@if (authForm.controls["method"].dirty) {
|
||||
@if (authForm.controls["method"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.passwordAuth.errors.passwordRequired'|translate"></tui-error>
|
||||
} @else if (authForm.controls["method"].hasError("incorrect")) {
|
||||
<tui-error [error]="'signIn.passwordAuth.errors.passwordIncorrect'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<button (click)="verifyMethod('PASSWORD', authForm.controls['method'].value)"
|
||||
[disabled]="authForm.invalid && false || pendingAction()" tuiButton>
|
||||
{{ 'signIn.anyAuth.verifyButton'|translate }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
}
|
||||
@case ('emailAuth') {
|
||||
<form [formGroup]="authForm" tuiAppearance="floating" id="emailAuth" animate.enter="slide-in-right"
|
||||
animate.leave="slide-out-left">
|
||||
<header>
|
||||
<h1>{{ "signIn.emailAuth.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.emailAuth.formSubtitle"|translate }}</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<tui-textfield iconStart="@tui.mail">
|
||||
<label tuiLabel>{{ "signIn.emailAuth.emailCode.label"|translate }}</label>
|
||||
<input formControlName="method" type="number" tuiInput>
|
||||
</tui-textfield>
|
||||
@if (authForm.controls["method"].dirty) {
|
||||
@if (authForm.controls["method"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.emailAuth.errors.passwordRequired'|translate"></tui-error>
|
||||
} @else if (authForm.controls["method"].hasError("incorrect")) {
|
||||
<tui-error [error]="'signIn.emailAuth.errors.passwordIncorrect'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<button (click)="verifyMethod('EMAIL', authForm.controls['method'].value)"
|
||||
[disabled]="authForm.invalid && false || pendingAction()" tuiButton>
|
||||
{{ 'signIn.anyAuth.verifyButton'|translate }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
}
|
||||
@case ('ok') {
|
||||
<h1>Received Chtn identity token, auth flow finished</h1>
|
||||
}
|
||||
}
|
||||
</main>
|
||||
|
||||
@@ -4,9 +4,28 @@
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
|
||||
.slide-in-right {
|
||||
animation: slideInRight 250ms ease-out forwards;
|
||||
}
|
||||
|
||||
.slide-out-left {
|
||||
animation: slideOutLeft 200ms ease-in forwards;
|
||||
}
|
||||
|
||||
@keyframes slideInRight {
|
||||
from { opacity: 0; transform: translateX(-8px); }
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
|
||||
@keyframes slideOutLeft {
|
||||
from { opacity: 1; transform: translateX(0); }
|
||||
to { opacity: 0; transform: translateX(8px); }
|
||||
}
|
||||
|
||||
form {
|
||||
width: 50%;
|
||||
height: 45%;
|
||||
position: absolute;
|
||||
width: 35%;
|
||||
max-height: 65%;
|
||||
border-radius: 35px;
|
||||
background: var(--tui-background-base-alt);
|
||||
padding: 20px;
|
||||
@@ -14,21 +33,51 @@
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
|
||||
main {
|
||||
header {
|
||||
align-self: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
margin-bottom: 35px;
|
||||
margin-top: 25px;
|
||||
|
||||
#methods {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 10px;
|
||||
h1 {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 30px;
|
||||
margin-top: 10px;
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#initial main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
#methodChoose main .method {
|
||||
width: 100%;
|
||||
height: 65px;
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
justify-content: start;
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-weight: normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,37 @@
|
||||
import {Component, inject, OnInit, signal} from '@angular/core';
|
||||
import {TuiAppearance, TuiButton, TuiError, TuiErrorDirective, TuiIcon, TuiInput, TuiTextfield} from '@taiga-ui/core';
|
||||
import { Component, computed, inject, OnInit, signal } from '@angular/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, 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';
|
||||
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',
|
||||
@@ -19,49 +41,77 @@ import {Router} from '@angular/router';
|
||||
TuiTextfield,
|
||||
TuiInput,
|
||||
TuiButton,
|
||||
TuiButtonGroup,
|
||||
TuiPassword,
|
||||
TuiIcon,
|
||||
ReactiveFormsModule,
|
||||
TuiErrorDirective,
|
||||
TuiError
|
||||
TuiError,
|
||||
TuiGroup,
|
||||
FaIconComponent,
|
||||
JsonPipe,
|
||||
],
|
||||
templateUrl: './signin.html',
|
||||
styleUrl: './signin.scss',
|
||||
})
|
||||
export class SignIn implements OnInit {
|
||||
indexedDb = inject(IndexedDB)
|
||||
router = inject(Router)
|
||||
SDK = inject(CHATENIUM_SDK);
|
||||
googleOAuth = inject(GoogleOAuth);
|
||||
sessionManager = inject(SessionManager);
|
||||
device = inject(DeviceDetectorService);
|
||||
notification = inject(TuiNotificationService);
|
||||
|
||||
service = new AuthService()
|
||||
serviceManager = new ServiceManager()
|
||||
methods = signal<AuthMethods>({sms: false, email: false, password: false})
|
||||
private googleSub?: Subscription;
|
||||
|
||||
private clickEvent = signal(0)
|
||||
challengeApi: AuthChallenge | null = null;
|
||||
challenge = signal<Challenge | null>(null);
|
||||
|
||||
indexedDb = inject(IndexedDB);
|
||||
router = inject(Router);
|
||||
|
||||
service = new AuthService();
|
||||
serviceManager = new ServiceManager();
|
||||
methods = signal<AuthMethods>({ sms: false, email: false, password: false });
|
||||
|
||||
pendingAction = signal(false);
|
||||
page = signal<'initial' | 'methodChoose' | 'passwordAuth' | 'emailAuth' | 'smsAuth' | 'ok'>(
|
||||
'initial',
|
||||
);
|
||||
isMultistep = signal(false);
|
||||
|
||||
signInForm = new FormGroup({
|
||||
unameMailPhone: new FormControl('', {
|
||||
validators: [Validators.required]
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
password: new FormControl('', {
|
||||
validators: [Validators.required]
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
authForm = new FormGroup({
|
||||
method: new FormControl('', {
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
});
|
||||
|
||||
timeoutId: any;
|
||||
|
||||
async checkAuthMethods(unameMailPhone: string | null) {
|
||||
console.log("Called")
|
||||
console.log('Called');
|
||||
clearTimeout(this.timeoutId);
|
||||
|
||||
this.timeoutId = setTimeout(async () => {
|
||||
this.methods.set({sms: false, password: false, email: false})
|
||||
this.methods.set(await this.service.getAuthMethods(unameMailPhone ?? ""))
|
||||
}, 500)
|
||||
this.methods.set({ sms: false, password: false, email: false });
|
||||
this.methods.set(await this.service.getAuthMethods(unameMailPhone ?? ''));
|
||||
}, 500);
|
||||
}
|
||||
|
||||
async passwordSignIn(unameMailPhone: string | null, password: string | null) {
|
||||
async startChallenge(identity: string | null) {
|
||||
this.pendingAction.set(true);
|
||||
try {
|
||||
const fetchResp = await this.SDK.auth.getIdFromIdentity(identity ?? '');
|
||||
const challenge = new AuthChallenge(this.SDK.auth);
|
||||
const resp = await challenge.start('AUTH:SIGNIN', fetchResp.data.userId);
|
||||
this.challenge.set(resp);
|
||||
this.challengeApi = challenge;
|
||||
this.pendingAction.set(false);
|
||||
this.page.set('methodChoose');
|
||||
/*
|
||||
const resp = await this.service.loginPasswordAuth(unameMailPhone ?? "", password ?? "")
|
||||
this.serviceManager.sessionManager.addSession(<PublicUserData>{
|
||||
pfp: resp.pfp,
|
||||
@@ -71,13 +121,101 @@ export class SignIn implements OnInit {
|
||||
}, resp.token)
|
||||
console.log("Logged in")
|
||||
this.router.navigate(["/chat"])
|
||||
*/
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
this.signInForm.controls['password'].setErrors({incorrect: true})
|
||||
console.error(e);
|
||||
this.signInForm.controls['unameMailPhone'].setErrors({ incorrect: true });
|
||||
this.pendingAction.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.indexedDb.openDatabase()
|
||||
async verifyMethod(methodName: string, credential: string | null) {
|
||||
this.pendingAction.set(true);
|
||||
if (this.challengeApi != null) {
|
||||
try {
|
||||
const resp = await this.challengeApi.verifyFactor(methodName, String(credential) ?? '');
|
||||
this.challenge.set(resp);
|
||||
this.pendingAction.set(false);
|
||||
if (resp.authIdentityToken == null) {
|
||||
this.isMultistep.set(true);
|
||||
this.page.set('methodChoose');
|
||||
this.authForm.reset();
|
||||
} else {
|
||||
await this.signIn(resp.authIdentityToken);
|
||||
this.page.set('ok');
|
||||
}
|
||||
} catch (e) {
|
||||
this.pendingAction.set(false);
|
||||
this.authForm.controls['method'].setErrors({ incorrect: true });
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
try {
|
||||
const resp = await this.challengeApi.requestCredential(methodName);
|
||||
this.challenge.set(resp);
|
||||
this.pendingAction.set(false);
|
||||
if (resp.authIdentityToken == null) {
|
||||
this.isMultistep.set(true);
|
||||
this.page.set(methodName == 'EMAIL' ? 'emailAuth' : 'smsAuth');
|
||||
}
|
||||
} catch (e) {
|
||||
this.pendingAction.set(false);
|
||||
this.authForm.controls['method'].setErrors({ incorrect: true });
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
this.indexedDb.openDatabase();
|
||||
|
||||
this.googleSub = this.googleOAuth.code$.subscribe((code) => {
|
||||
this.verifyMethod("GOOGLE", code);
|
||||
});
|
||||
|
||||
this.waitForGoogle().then(() => {
|
||||
this.googleOAuth.init(environment.google_client_id);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.googleSub?.unsubscribe();
|
||||
}
|
||||
|
||||
private waitForGoogle(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (typeof google !== 'undefined' && google.accounts?.oauth2) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
if (typeof google !== 'undefined' && google.accounts?.oauth2) {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
protected readonly faGoogle = faGoogle;
|
||||
protected readonly faApple = faApple;
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
export const environment = {
|
||||
version: "3.0-beta11",
|
||||
api_url: "http://localhost:3000",
|
||||
cdn_url: "http://localhost:4000",
|
||||
ws_url: "ws://localhost:3000",
|
||||
version: '3.0-beta11',
|
||||
api_url: 'http://localhost:3000',
|
||||
cdn_url: 'http://localhost:4000',
|
||||
ws_url: 'ws://localhost:3000',
|
||||
// Google OAuth
|
||||
google_client_id: '21430884719-vjmecc7ofnfp82hmb22hba323gr4r7p7.apps.googleusercontent.com',
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
export const environment = {
|
||||
version: "3.0-beta11",
|
||||
api_url: "https://api.chatenium.hu",
|
||||
cdn_url: "https://cdn.chatenium.hu",
|
||||
ws_url: "wss://api.chatenium.hu",
|
||||
version: '3.0-beta11',
|
||||
api_url: 'https://api.chatenium.hu',
|
||||
cdn_url: 'https://cdn.chatenium.hu',
|
||||
ws_url: 'wss://api.chatenium.hu',
|
||||
// Google OAuth
|
||||
google_client_id: '21430884719-vjmecc7ofnfp82hmb22hba323gr4r7p7.apps.googleusercontent.com',
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||
<link rel="manifest" href="manifest.webmanifest">
|
||||
<script src="https://accounts.google.com/gsi/client" async defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/app",
|
||||
"types": []
|
||||
"types": ["google.accounts"]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
|
||||
Reference in New Issue
Block a user