Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
feat(auth): refactor authentication services and add desktop client registration support
johaven08c6e0faf84d
diff --git a/frontend/src/app/auth/auth.component.ts b/frontend/src/app/auth/auth.component.tsindex 2a19e04c..3ff2f64e 100644--- a/frontend/src/app/auth/auth.component.ts+++ b/frontend/src/app/auth/auth.component.ts@@ -18,6 +18,7 @@ import { finalize } from 'rxjs/operators'import { logoDarkUrl } from '../applications/files/files.constants'import { RECENTS_PATH } from '../applications/recents/recents.constants'import { AutofocusDirective } from '../common/directives/auto-focus.directive'+import type { AuthResult } from './auth.interface'import { AuthService } from './auth.service'@Component({@@ -60,21 +61,26 @@ export class AuthComponent {.login(this.loginForm.value.username, this.loginForm.value.password).pipe(finalize(() => setTimeout(() => (this.submitted = false), 1500))).subscribe({- next: (res: { success: boolean; message: any; twoFaEnabled?: boolean }) => this.isLogged(res),+ next: (res: AuthResult) => this.isLogged(res),error: (e) => this.isLogged({ success: false, message: e.error ? e.error.message : e })})}- onSubmit2Fa() {+ async onSubmit2Fa() {this.submitted = true- const verifyCode: TwoFaVerifyDto = {- code: this.twoFaForm.value.isRecoveryCode ? this.twoFaForm.value.recoveryCode : this.twoFaForm.value.totpCode,- isRecoveryCode: this.twoFaForm.value.isRecoveryCode+ const code = this.twoFaForm.value.isRecoveryCode ? this.twoFaForm.value.recoveryCode : this.twoFaForm.value.totpCode++ if (this.auth.electron.enabled) {+ this.auth.electron.register(this.loginForm.value.username, this.loginForm.value.password, code).subscribe({+ next: (res: AuthResult) => this.is2FaVerified(res as TwoFaResponseDto),+ error: (e) => this.is2FaVerified({ success: false, message: e.error ? e.error.message : e } as TwoFaResponseDto)+ })+ } else {+ this.auth.loginWith2Fa({ code: code, isRecoveryCode: this.twoFaForm.value.isRecoveryCode } satisfies TwoFaVerifyDto).subscribe({+ next: (res: TwoFaResponseDto) => this.is2FaVerified(res),+ error: (e) => this.is2FaVerified({ success: false, message: e.error ? e.error.message : e } as TwoFaResponseDto)+ })}- this.auth.loginWith2Fa(verifyCode).subscribe({- next: (res: TwoFaResponseDto) => this.is2FaVerified(res),- error: (e) => this.is2FaVerified({ success: false, message: e.error ? e.error.message : e } as TwoFaResponseDto)- })}onCancel2Fa() {@@ -85,10 +91,18 @@ export class AuthComponent {this.hasError = null}- is2FaVerified(res: TwoFaResponseDto) {+ loginWithOIDC() {+ if (this.oidcSettings) {+ window.location.href = this.oidcSettings.loginUrl+ }+ }++ private is2FaVerified(res: TwoFaResponseDto) {if (res.success) {- // In this case, the user and tokens are provided- this.auth.initUserFromResponse(res)+ if (!this.auth.electron.enabled) {+ // Web: in this case, the user and tokens are provided+ this.auth.initUserFromResponse(res)+ }this.isLogged({ success: true, message: res.message })} else {this.hasError = res.message || 'Unable to verify code'@@ -97,11 +111,15 @@ export class AuthComponent {this.twoFaForm.patchValue({ totpCode: '', recoveryCode: '' })}- isLogged(res: { success: boolean; message: any; twoFaEnabled?: boolean }) {+ private isLogged(res: AuthResult) {if (res.success) {this.hasError = nullif (res.twoFaEnabled) {this.twoFaVerify = true+ if (this.auth.electron.enabled) {+ // Do not clear the password; it will be used to register the client.+ return+ }} else if (this.auth.returnUrl) {this.router.navigateByUrl(this.auth.returnUrl).then(() => {this.auth.returnUrl = null@@ -116,10 +134,4 @@ export class AuthComponent {}this.loginForm.patchValue({ password: '' })}-- loginWithOIDC() {- if (this.oidcSettings) {- window.location.href = this.oidcSettings.loginUrl- }- }}diff --git a/frontend/src/app/auth/auth.service.ts b/frontend/src/app/auth/auth.service.tsindex b14ff042..30e6d9e2 100644--- a/frontend/src/app/auth/auth.service.ts+++ b/frontend/src/app/auth/auth.service.ts@@ -35,20 +35,20 @@ import { Electron } from '../electron/electron.service'import { LayoutService } from '../layout/layout.service'import { StoreService } from '../store/store.service'import { AUTH_PATHS } from './auth.constants'-import type { AuthOIDCQueryParams } from './auth.interface'+import type { AuthOIDCQueryParams, AuthResult } from './auth.interface'@Injectable({providedIn: 'root'})export class AuthService {public returnUrl: string+ public electron = inject(Electron)private authSettings: AuthOIDCSettings | false = nullprivate readonly http = inject(HttpClient)private readonly router = inject(Router)private readonly store = inject(StoreService)private readonly userService = inject(UserService)private readonly layout = inject(LayoutService)- private readonly electron = inject(Electron)private _refreshExpiration = parseInt(localStorage.getItem('refresh_expiration') || '0', 10) || 0@@ -74,50 +74,26 @@ export class AuthService {localStorage.setItem('access_expiration', value.toString())}- login(login: string, password: string): Observable<{ success: boolean; message: any; twoFaEnabled?: boolean }> {+ login(login: string, password: string): Observable<AuthResult> {return this.http.post<LoginResponseDto>(API_AUTH_LOGIN, { login, password }).pipe(- map((r: LoginResponseDto) => {+ switchMap((r: LoginResponseDto) => {+ // 2FA - first step (code page)if (r.server.twoFaEnabled && r.user.twoFaEnabled) {- // check 2FA before logging in the userthis.accessExpiration = r.token.access_2fa_expirationthis.refreshExpiration = this.accessExpiration- return { success: true, twoFaEnabled: true, message: null }- } else {- this.initUserFromResponse(r)+ return of<AuthResult>({ success: true, twoFaEnabled: true, message: null })}- return { success: true, message: null }+ // Desktop Client Login+ if (this.electron.enabled) {+ return this.electron.register(login, password)+ }+ // Web Login+ this.initUserFromResponse(r)+ return of<AuthResult>({ success: true, message: null })}),catchError((e) => {- console.warn(e)- return of({ success: false, message: e.error.message || e.message })- })- )- }-- loginElectron(): Observable<boolean> {- return this.electron.authenticate().pipe(- switchMap((auth: SyncClientAuthDto) => {- return this.http.post<ClientAuthCookieDto>(API_SYNC_AUTH_COOKIE, auth).pipe(- map((r: ClientAuthCookieDto) => {- this.accessExpiration = r.token.access_expiration- this.refreshExpiration = r.token.refresh_expiration- this.initUser(r)- if (r?.client_token_update) {- // update client token- this.electron.send(EVENT.SERVER.AUTHENTICATION_TOKEN_UPDATE, r.client_token_update)- }- return true- }),- catchError((e: HttpErrorResponse) => {- console.warn(e)- if (e.error.message === CLIENT_TOKEN_EXPIRED_ERROR) {- this.electron.send(EVENT.SERVER.AUTHENTICATION_TOKEN_EXPIRED)- } else {- this.electron.send(EVENT.SERVER.AUTHENTICATION_FAILED)- }- return of(false)- })- )+ console.error(e)+ return of<AuthResult>({ success: false, message: e?.error?.message ?? e?.message })}))}@@ -146,20 +122,6 @@ export class AuthService {.subscribe()}- logoutImpersonateUser() {- this.http.post<LoginResponseDto>(API_ADMIN_IMPERSONATE_LOGOUT, null).subscribe({- next: (r: LoginResponseDto) => {- this.userService.disconnectWebSocket()- this.initUserFromResponse(r)- this.router.navigate([USER_PATH.BASE, USER_PATH.ACCOUNT]).catch(console.error)- },- error: (e: HttpErrorResponse) => {- console.error(e)- this.layout.sendNotification('error', 'Impersonate identity', 'logout', e)- }- })- }-initUserFromResponse(r: LoginResponseDto, impersonate = false) {if (r !== null) {this.accessExpiration = r.token.access_expiration@@ -183,7 +145,7 @@ export class AuthService {console.debug('token has expired')if (this.electron.enabled) {console.debug('login with app')- return this.loginElectron()+ return this.authenticateDesktopClient()}this.logout(true, true)return throwError(() => e)@@ -198,7 +160,7 @@ export class AuthService {}if (this.refreshTokenHasExpired()) {if (this.electron.enabled) {- return this.loginElectron()+ return this.authenticateDesktopClient()}this.returnUrl = returnUrl.length > 1 ? returnUrl : nullthis.logout()@@ -260,6 +222,54 @@ export class AuthService {)}+ private logoutImpersonateUser() {+ this.http.post<LoginResponseDto>(API_ADMIN_IMPERSONATE_LOGOUT, null).subscribe({+ next: (r: LoginResponseDto) => {+ this.userService.disconnectWebSocket()+ this.initUserFromResponse(r)+ this.router.navigate([USER_PATH.BASE, USER_PATH.ACCOUNT]).catch(console.error)+ },+ error: (e: HttpErrorResponse) => {+ console.error(e)+ this.layout.sendNotification('error', 'Impersonate identity', 'logout', e)+ }+ })+ }++ private authenticateDesktopClient(): Observable<boolean> {+ return this.electron.authenticate().pipe(+ switchMap((auth: SyncClientAuthDto) => {+ if (!auth.clientId) {+ // No auth was provided, the Sync-in desktop app must be registered+ this.logout(true)+ return of(false)+ }+ return this.http.post<ClientAuthCookieDto>(API_SYNC_AUTH_COOKIE, auth).pipe(+ map((r: ClientAuthCookieDto) => {+ this.accessExpiration = r.token.access_expiration+ this.refreshExpiration = r.token.refresh_expiration+ this.initUser(r)+ if (r?.client_token_update) {+ // Update the client token+ this.electron.send(EVENT.SERVER.AUTHENTICATION_TOKEN_UPDATE, r.client_token_update)+ }+ return true+ }),+ catchError((e: HttpErrorResponse) => {+ if (e.error.message === CLIENT_TOKEN_EXPIRED_ERROR) {+ this.electron.send(EVENT.SERVER.AUTHENTICATION_TOKEN_EXPIRED)+ } else {+ // In other cases, we consider the server unavailable+ this.electron.send(EVENT.SERVER.AUTHENTICATION_FAILED)+ }+ this.logout(true, e.error.message === CLIENT_TOKEN_EXPIRED_ERROR)+ return of(false)+ })+ )+ })+ )+ }+private refreshTokenHasExpired(): boolean {return this.refreshExpiration === 0 || currentTimeStamp() >= this.refreshExpiration}diff --git a/frontend/src/app/electron/constants/events.ts b/frontend/src/app/electron/constants/events.tsindex 5afe9710..5c0e3218 100644--- a/frontend/src/app/electron/constants/events.ts+++ b/frontend/src/app/electron/constants/events.ts@@ -5,8 +5,9 @@*/export const EVENT = {- // authentication+ // serverSERVER: {+ REGISTRATION: 'server-registration',AUTHENTICATION: 'server-authentication',AUTHENTICATION_FAILED: 'server-authentication-failed',AUTHENTICATION_TOKEN_UPDATE: 'server-authentication-token-update',diff --git a/frontend/src/app/electron/electron.service.ts b/frontend/src/app/electron/electron.service.tsindex 8aea3bcc..7c27c3cd 100644--- a/frontend/src/app/electron/electron.service.ts+++ b/frontend/src/app/electron/electron.service.ts@@ -8,12 +8,13 @@ import { effect, inject, Injectable, NgZone } from '@angular/core'import { toObservable } from '@angular/core/rxjs-interop'import { FileTask } from '@sync-in-server/backend/src/applications/files/models/file-task'import type { SyncClientAuthDto } from '@sync-in-server/backend/src/applications/sync/dtos/sync-client-auth.dto'-import { combineLatest, from, Observable } from 'rxjs'+import { combineLatest, from, map, Observable } from 'rxjs'import { NotificationModel } from '../applications/notifications/models/notification.model'import { CLIENT_APP_COUNTER, CLIENT_SCHEDULER_STATE } from '../applications/sync/constants/client'import { SyncStatus } from '../applications/sync/interfaces/sync-status.interface'import { SyncTask } from '../applications/sync/interfaces/sync-task.interface'import { SYNC_MENU } from '../applications/sync/sync.constants'+import type { AuthResult } from '../auth/auth.interface'import { StoreService } from '../store/store.service'import { EVENT } from './constants/events'import { ElectronIpcRenderer } from './interface'@@ -73,6 +74,12 @@ export class Electron {return from(this.invoke(EVENT.SERVER.AUTHENTICATION))}+ register(login: string, password: string, code?: string): Observable<AuthResult> {+ return from(this.invoke(EVENT.SERVER.REGISTRATION, { login, password, code })).pipe(+ map((e: { ok: boolean; msg?: string }) => ({ success: e.ok, message: e.msg ?? null }) satisfies AuthResult)+ )+ }+openPath(path: string) {this.send(EVENT.MISC.FILE_OPEN, path)}