Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

feat(auth): implement OIDC authentication support and refactor auth providers

johaven28bbf1df2f2a
diff --git a/backend/package.json b/backend/package.json
index af87f11f..22e68977 100755
--- a/backend/package.json
+++ b/backend/package.json
@@ -69,6 +69,7 @@
"mysql2": "^3.11.4",
"nestjs-pino": "^4.3.0",
"nodemailer": "^7.0.0",
+ "openid-client": "^6.8.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
diff --git a/backend/src/applications/links/services/links-manager.service.spec.ts b/backend/src/applications/links/services/links-manager.service.spec.ts
index 3c824c3b..9073f8a5 100644
--- a/backend/src/applications/links/services/links-manager.service.spec.ts
+++ b/backend/src/applications/links/services/links-manager.service.spec.ts
@@ -8,7 +8,7 @@ import { HttpService } from '@nestjs/axios'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { Test, TestingModule } from '@nestjs/testing'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
+import { AuthManager } from '../../../authentication/auth.service'
import { Cache } from '../../../infrastructure/cache/services/cache.service'
import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
diff --git a/backend/src/applications/links/services/links-manager.service.ts b/backend/src/applications/links/services/links-manager.service.ts
index 30092543..4538af48 100644
--- a/backend/src/applications/links/services/links-manager.service.ts
+++ b/backend/src/applications/links/services/links-manager.service.ts
@@ -6,9 +6,9 @@
import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@nestjs/common'
import { FastifyReply, FastifyRequest } from 'fastify'
+import { AuthManager } from '../../../authentication/auth.service'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto'
import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
import { serverConfig } from '../../../configuration/config.environment'
import { FilesManager } from '../../files/services/files-manager.service'
import { SendFile } from '../../files/utils/send-file'
diff --git a/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts b/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts
index e9f3dd10..33bf2597 100644
--- a/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts
+++ b/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts
@@ -10,9 +10,9 @@ import { Test, TestingModule } from '@nestjs/testing'
import { FastifyReply } from 'fastify'
import crypto from 'node:crypto'
import fs from 'node:fs/promises'
-import { AuthMethod } from '../../../authentication/models/auth-method'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
-import { AuthMethod2FA } from '../../../authentication/services/auth-methods/auth-method-two-fa.service'
+import { AuthManager } from '../../../authentication/auth.service'
+import { AuthProvider } from '../../../authentication/providers/auth-providers.models'
+import { AuthProvider2FA } from '../../../authentication/providers/two-fa/auth-provider-two-fa.service'
import * as commonFunctions from '../../../common/functions'
import * as commonShared from '../../../common/shared'
import { configuration } from '../../../configuration/config.environment'
@@ -119,8 +119,8 @@ describe(SyncClientsManager.name, () => {
{ provide: SyncQueries, useValue: syncQueries },
{ provide: UsersManager, useValue: usersManager },
{ provide: AuthManager, useValue: authManager },
- { provide: AuthMethod, useValue: authMethod },
- { provide: AuthMethod2FA, useValue: {} }
+ { provide: AuthProvider, useValue: authMethod },
+ { provide: AuthProvider2FA, useValue: {} }
]
}).compile()
diff --git a/backend/src/applications/sync/services/sync-clients-manager.service.ts b/backend/src/applications/sync/services/sync-clients-manager.service.ts
index 6281a53c..7045eb25 100644
--- a/backend/src/applications/sync/services/sync-clients-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-clients-manager.service.ts
@@ -11,9 +11,9 @@ import { FastifyReply } from 'fastify'
import crypto from 'node:crypto'
import fs from 'node:fs/promises'
import path from 'node:path'
-import { AuthMethod } from '../../../authentication/models/auth-method'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
-import { AuthMethod2FA } from '../../../authentication/services/auth-methods/auth-method-two-fa.service'
+import { AuthManager } from '../../../authentication/auth.service'
+import { AuthProvider } from '../../../authentication/providers/auth-providers.models'
+import { AuthProvider2FA } from '../../../authentication/providers/two-fa/auth-provider-two-fa.service'
import { convertHumanTimeToSeconds } from '../../../common/functions'
import { currentTimeStamp } from '../../../common/shared'
import { STATIC_PATH } from '../../../configuration/config.constants'
@@ -42,8 +42,8 @@ export class SyncClientsManager {
constructor(
private readonly http: HttpService,
private readonly authManager: AuthManager,
- private readonly authMethod: AuthMethod,
- private readonly authMethod2Fa: AuthMethod2FA,
+ private readonly authMethod: AuthProvider,
+ private readonly authMethod2Fa: AuthProvider2FA,
private readonly usersManager: UsersManager,
private readonly syncQueries: SyncQueries
) {}
diff --git a/backend/src/applications/users/admin-users.controller.spec.ts b/backend/src/applications/users/admin-users.controller.spec.ts
index ac982296..91c3af91 100644
--- a/backend/src/applications/users/admin-users.controller.spec.ts
+++ b/backend/src/applications/users/admin-users.controller.spec.ts
@@ -7,9 +7,9 @@
import { ConfigModule } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { Test, TestingModule } from '@nestjs/testing'
-import { AuthTwoFaGuard } from '../../authentication/guards/auth-two-fa-guard'
-import { AuthManager } from '../../authentication/services/auth-manager.service'
-import { AuthMethod2FA } from '../../authentication/services/auth-methods/auth-method-two-fa.service'
+import { AuthManager } from '../../authentication/auth.service'
+import { AuthProvider2FA } from '../../authentication/providers/two-fa/auth-provider-two-fa.service'
+import { AuthTwoFaGuard } from '../../authentication/providers/two-fa/auth-two-fa-guard'
import { exportConfiguration } from '../../configuration/config.environment'
import { Cache } from '../../infrastructure/cache/services/cache.service'
import { DB_TOKEN_PROVIDER } from '../../infrastructure/database/constants'
@@ -33,7 +33,7 @@ describe(AdminUsersController.name, () => {
provide: Cache,
useValue: {}
},
- { provide: AuthMethod2FA, useValue: {} },
+ { provide: AuthProvider2FA, useValue: {} },
{ provide: AuthTwoFaGuard, useValue: {} },
{ provide: NotificationsManager, useValue: {} },
JwtService,
diff --git a/backend/src/applications/users/admin-users.controller.ts b/backend/src/applications/users/admin-users.controller.ts
index b38afa76..90c196dd 100644
--- a/backend/src/applications/users/admin-users.controller.ts
+++ b/backend/src/applications/users/admin-users.controller.ts
@@ -7,7 +7,7 @@
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, Put, Res, Search, UseGuards } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import { LoginResponseDto } from '../../authentication/dto/login-response.dto'
-import { AuthTwoFaGuard, AuthTwoFaGuardWithoutPassword } from '../../authentication/guards/auth-two-fa-guard'
+import { AuthTwoFaGuard, AuthTwoFaGuardWithoutPassword } from '../../authentication/providers/two-fa/auth-two-fa-guard'
import { GROUP_TYPE } from './constants/group'
import { ADMIN_USERS_ROUTE } from './constants/routes'
import { USER_ROLE } from './constants/user'
diff --git a/backend/src/applications/users/services/admin-users-manager.service.spec.ts b/backend/src/applications/users/services/admin-users-manager.service.spec.ts
index 5cdc1e8b..d2e39219 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.spec.ts
@@ -6,7 +6,7 @@
import { HttpException } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
+import { AuthManager } from '../../../authentication/auth.service'
import { GROUP_TYPE } from '../constants/group'
import { USER_GROUP_ROLE, USER_ROLE } from '../constants/user'
import type { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'
diff --git a/backend/src/applications/users/services/admin-users-manager.service.ts b/backend/src/applications/users/services/admin-users-manager.service.ts
index ef04eed9..70ef7ddf 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.ts
@@ -6,8 +6,8 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { FastifyReply } from 'fastify'
+import { AuthManager } from '../../../authentication/auth.service'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
import { anonymizePassword, hashPassword } from '../../../common/functions'
import { isPathExists, moveFiles, removeFiles } from '../../files/utils/files'
import { GROUP_TYPE } from '../constants/group'
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.ts
index b8232a6e..49409318 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -8,7 +8,7 @@ import { Test, TestingModule } from '@nestjs/testing'
import bcrypt from 'bcryptjs'
import path from 'node:path'
import { Readable } from 'node:stream'
-import { AuthManager } from '../../../authentication/services/auth-manager.service'
+import { AuthManager } from '../../../authentication/auth.service'
import { comparePassword } from '../../../common/functions'
import * as imageModule from '../../../common/image'
import { pngMimeType, svgMimeType } from '../../../common/image'
diff --git a/backend/src/applications/users/users.controller.spec.ts b/backend/src/applications/users/users.controller.spec.ts
index 44efc52d..62a3e78a 100755
--- a/backend/src/applications/users/users.controller.spec.ts
+++ b/backend/src/applications/users/users.controller.spec.ts
@@ -7,8 +7,8 @@
import { ConfigModule } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { Test, TestingModule } from '@nestjs/testing'
-import { AuthManager } from '../../authentication/services/auth-manager.service'
-import { AuthMethod2FA } from '../../authentication/services/auth-methods/auth-method-two-fa.service'
+import { AuthManager } from '../../authentication/auth.service'
+import { AuthProvider2FA } from '../../authentication/providers/two-fa/auth-provider-two-fa.service'
import { exportConfiguration } from '../../configuration/config.environment'
import { Cache } from '../../infrastructure/cache/services/cache.service'
import { DB_TOKEN_PROVIDER } from '../../infrastructure/database/constants'
@@ -44,7 +44,7 @@ describe(UsersController.name, () => {
AdminUsersQueries,
AuthManager,
JwtService,
- AuthMethod2FA,
+ AuthProvider2FA,
{ provide: NotificationsManager, useValue: {} }
]
}).compile()
diff --git a/backend/src/applications/users/users.controller.ts b/backend/src/applications/users/users.controller.ts
index 50e9c0fb..59b90d12 100755
--- a/backend/src/applications/users/users.controller.ts
+++ b/backend/src/applications/users/users.controller.ts
@@ -7,8 +7,8 @@
import { Body, Controller, Delete, Get, Header, Param, ParseIntPipe, Patch, Post, Put, Req, Search, StreamableFile, UseGuards } from '@nestjs/common'
import { createReadStream } from 'fs'
import { LoginResponseDto } from '../../authentication/dto/login-response.dto'
-import { AuthTwoFaGuardWithoutPassword } from '../../authentication/guards/auth-two-fa-guard'
import { FastifyAuthenticatedRequest } from '../../authentication/interfaces/auth-request.interface'
+import { AuthTwoFaGuardWithoutPassword } from '../../authentication/providers/two-fa/auth-two-fa-guard'
import { makeContentDispositionAttachment } from '../files/utils/send-file'
import { USERS_ROUTE } from './constants/routes'
import { USER_PERMISSION, USER_ROLE } from './constants/user'
diff --git a/backend/src/applications/users/users.e2e-spec.ts b/backend/src/applications/users/users.e2e-spec.ts
index 5c4b8fd4..fd62d6ac 100644
--- a/backend/src/applications/users/users.e2e-spec.ts
+++ b/backend/src/applications/users/users.e2e-spec.ts
@@ -6,8 +6,8 @@
import { NestFastifyApplication } from '@nestjs/platform-fastify'
import { appBootstrap } from '../../app.bootstrap'
+import { AuthManager } from '../../authentication/auth.service'
import { TokenResponseDto } from '../../authentication/dto/token-response.dto'
-import { AuthManager } from '../../authentication/services/auth-manager.service'
import { dbCheckConnection } from '../../infrastructure/database/utils'
import { API_USERS_AVATAR, API_USERS_ME } from './constants/routes'
import { USER_ROLE } from './constants/user'
diff --git a/backend/src/authentication/auth.config.ts b/backend/src/authentication/auth.config.ts
index e1eb9402..8a7f0c3b 100644
--- a/backend/src/authentication/auth.config.ts
+++ b/backend/src/authentication/auth.config.ts
@@ -4,42 +4,13 @@
* See the LICENSE file for licensing details
*/
-import { Exclude, Transform, Type } from 'class-transformer'
-import {
- ArrayNotEmpty,
- IsArray,
- IsBoolean,
- IsDefined,
- IsEnum,
- IsIn,
- IsNotEmpty,
- IsNotEmptyObject,
- IsObject,
- IsOptional,
- IsString,
- ValidateIf,
- ValidateNested
-} from 'class-validator'
-import { SERVER_NAME } from '../common/shared'
+import { Exclude, Type } from 'class-transformer'
+import { IsDefined, IsEnum, IsIn, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'
import { ACCESS_KEY, CSRF_KEY, REFRESH_KEY, WS_KEY } from './constants/auth'
-import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './constants/auth-ldap'
-
-export class AuthMfaTotpConfig {
- @IsBoolean()
- enabled = true
-
- @IsString()
- issuer = SERVER_NAME
-}
-
-export class AuthMfaConfig {
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthMfaTotpConfig)
- totp: AuthMfaTotpConfig = new AuthMfaTotpConfig()
-}
+import { AUTH_PROVIDER } from './providers/auth-providers.constants'
+import { AuthMethodLDAPConfig } from './providers/ldap/auth-ldap.config'
+import { AuthMethodOIDCConfig } from './providers/oidc/auth-oidc.config'
+import { AuthMFAConfig } from './providers/two-fa/auth-two-fa.config'
export class AuthTokenAccessConfig {
@Exclude({ toClassOnly: true })
@@ -111,58 +82,10 @@ export class AuthTokenConfig {
ws: AuthTokenWSConfig
}
-export class AuthMethodLdapAttributesConfig {
- @IsOptional()
- @IsString()
- @Transform(({ value }) => value || LDAP_LOGIN_ATTR.UID)
- @IsEnum(LDAP_LOGIN_ATTR)
- login: LDAP_LOGIN_ATTR = LDAP_LOGIN_ATTR.UID
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => value || LDAP_COMMON_ATTR.MAIL)
- email: string = LDAP_COMMON_ATTR.MAIL
-}
-
-export class AuthMethodLdapConfig {
- @Transform(({ value }) => (Array.isArray(value) ? value.filter((v: string) => Boolean(v)) : value))
- @ArrayNotEmpty()
- @IsArray()
- @IsString({ each: true })
- servers: string[]
-
- @IsString()
- @IsNotEmpty()
- baseDN: string
-
- @IsOptional()
- @IsString()
- filter?: string
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthMethodLdapAttributesConfig)
- attributes: AuthMethodLdapAttributesConfig = new AuthMethodLdapAttributesConfig()
-
- @IsOptional()
- @IsString()
- adminGroup?: string
-
- @IsOptional()
- @IsString()
- upnSuffix?: string
-
- @IsOptional()
- @IsString()
- netbiosName?: string
-}
-
export class AuthConfig {
@IsString()
- @IsIn(['mysql', 'ldap'])
- method: 'mysql' | 'ldap' = 'mysql'
+ @IsEnum(AUTH_PROVIDER)
+ method: AUTH_PROVIDER = AUTH_PROVIDER.MYSQL
@IsOptional()
@IsString()
@@ -172,8 +95,8 @@ export class AuthConfig {
@IsNotEmptyObject()
@IsObject()
@ValidateNested()
- @Type(() => AuthMfaConfig)
- mfa: AuthMfaConfig = new AuthMfaConfig()
+ @Type(() => AuthMFAConfig)
+ mfa: AuthMFAConfig = new AuthMFAConfig()
@IsString()
@IsIn(['lax', 'strict'])
@@ -190,6 +113,13 @@ export class AuthConfig {
@IsDefined()
@IsObject()
@ValidateNested()
- @Type(() => AuthMethodLdapConfig)
- ldap: AuthMethodLdapConfig
+ @Type(() => AuthMethodLDAPConfig)
+ ldap: AuthMethodLDAPConfig
+
+ @ValidateIf((o: AuthConfig) => o.method === 'oidc')
+ @IsDefined()
+ @IsObject()
+ @ValidateNested()
+ @Type(() => AuthMethodOIDCConfig)
+ oidc: AuthMethodOIDCConfig = new AuthMethodOIDCConfig()
}
diff --git a/backend/src/authentication/auth.controller.spec.ts b/backend/src/authentication/auth.controller.spec.ts
index d6a679a7..6764edfb 100755
--- a/backend/src/authentication/auth.controller.spec.ts
+++ b/backend/src/authentication/auth.controller.spec.ts
@@ -19,12 +19,12 @@ import { Cache } from '../infrastructure/cache/services/cache.service'
import { DB_TOKEN_PROVIDER } from '../infrastructure/database/constants'
import { AuthConfig } from './auth.config'
import { AuthController } from './auth.controller'
+import { AuthManager } from './auth.service'
import { TOKEN_PATHS } from './constants/auth'
import { LoginResponseDto } from './dto/login-response.dto'
-import { AuthTwoFaGuard } from './guards/auth-two-fa-guard'
import { TOKEN_TYPE } from './interfaces/token.interface'
-import { AuthManager } from './services/auth-manager.service'
-import { AuthMethod2FA } from './services/auth-methods/auth-method-two-fa.service'
+import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'
+import { AuthTwoFaGuard } from './providers/two-fa/auth-two-fa-guard'
describe(AuthController.name, () => {
let module: TestingModule
@@ -40,7 +40,7 @@ describe(AuthController.name, () => {
ConfigService,
AuthManager,
JwtService,
- AuthMethod2FA,
+ AuthProvider2FA,
AuthTwoFaGuard,
{ provide: DB_TOKEN_PROVIDER, useValue: {} },
{ provide: Cache, useValue: {} },
diff --git a/backend/src/authentication/auth.controller.ts b/backend/src/authentication/auth.controller.ts
index 98d8e8e7..7a6fa152 100755
--- a/backend/src/authentication/auth.controller.ts
+++ b/backend/src/authentication/auth.controller.ts
@@ -11,26 +11,26 @@ import { UserHaveRole } from '../applications/users/decorators/roles.decorator'
import { GetUser } from '../applications/users/decorators/user.decorator'
import { UserRolesGuard } from '../applications/users/guards/roles.guard'
import { UserModel } from '../applications/users/models/user.model'
+import { AuthManager } from './auth.service'
import { ACCESS_KEY, TOKEN_PATHS } from './constants/auth'
import { AUTH_ROUTE } from './constants/routes'
import { AuthTokenSkip } from './decorators/auth-token-skip.decorator'
-import { LoginResponseDto, LoginVerify2FaDto, TwoFaResponseDto } from './dto/login-response.dto'
+import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto'
import { TokenResponseDto } from './dto/token-response.dto'
-import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './dto/two-fa-verify.dto'
import { AuthLocalGuard } from './guards/auth-local.guard'
import { AuthTokenRefreshGuard } from './guards/auth-token-refresh.guard'
-import { AuthTwoFaGuard } from './guards/auth-two-fa-guard'
import { FastifyAuthenticatedRequest } from './interfaces/auth-request.interface'
import { TOKEN_TYPE } from './interfaces/token.interface'
-import { TwoFaSetup, TwoFaVerifyResult } from './interfaces/two-fa-setup.interface'
-import { AuthManager } from './services/auth-manager.service'
-import { AuthMethod2FA } from './services/auth-methods/auth-method-two-fa.service'
+import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'
+import { AuthTwoFaGuard } from './providers/two-fa/auth-two-fa-guard'
+import { TwoFaResponseDto, TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './providers/two-fa/auth-two-fa.dtos'
+import { TwoFaSetup, TwoFaVerifyResult } from './providers/two-fa/auth-two-fa.interfaces'
@Controller(AUTH_ROUTE.BASE)
export class AuthController {
constructor(
private readonly authManager: AuthManager,
- private readonly authMethod2FA: AuthMethod2FA
+ private readonly authMethod2FA: AuthProvider2FA
) {}
@Post(AUTH_ROUTE.LOGIN)
diff --git a/backend/src/authentication/auth.module.ts b/backend/src/authentication/auth.module.ts
index d1afc9a7..89ed19fd 100755
--- a/backend/src/authentication/auth.module.ts
+++ b/backend/src/authentication/auth.module.ts
@@ -11,6 +11,7 @@ import { PassportModule } from '@nestjs/passport'
import { UsersModule } from '../applications/users/users.module'
import { configuration } from '../configuration/config.environment'
import { AuthController } from './auth.controller'
+import { AuthManager } from './auth.service'
import { AuthAnonymousGuard } from './guards/auth-anonymous.guard'
import { AuthAnonymousStrategy } from './guards/auth-anonymous.strategy'
import { AuthBasicGuard } from './guards/auth-basic.guard'
@@ -21,15 +22,20 @@ import { AuthTokenAccessGuard } from './guards/auth-token-access.guard'
import { AuthTokenAccessStrategy } from './guards/auth-token-access.strategy'
import { AuthTokenRefreshGuard } from './guards/auth-token-refresh.guard'
import { AuthTokenRefreshStrategy } from './guards/auth-token-refresh.strategy'
-import { AuthMethod } from './models/auth-method'
-import { AuthManager } from './services/auth-manager.service'
-import { AuthMethodDatabase } from './services/auth-methods/auth-method-database.service'
-import { AuthMethodLdapService } from './services/auth-methods/auth-method-ldap.service'
-import { AuthMethod2FA } from './services/auth-methods/auth-method-two-fa.service'
+import { AUTH_PROVIDER } from './providers/auth-providers.constants'
+import { AuthProvider } from './providers/auth-providers.models'
+import { selectAuthProvider } from './providers/auth-providers.utils'
+import { AuthMethodOIDCModule } from './providers/oidc/auth-method-oidc.module'
+import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'
@Global()
@Module({
- imports: [JwtModule.register({ global: true }), UsersModule, PassportModule],
+ imports: [
+ JwtModule.register({ global: true }),
+ UsersModule,
+ PassportModule,
+ ...(configuration.auth.method === AUTH_PROVIDER.OIDC ? [AuthMethodOIDCModule] : [])
+ ],
controllers: [AuthController],
providers: [
{
@@ -46,9 +52,9 @@ import { AuthMethod2FA } from './services/auth-methods/auth-method-two-fa.servic
AuthBasicStrategy,
AuthAnonymousStrategy,
AuthManager,
- AuthMethod2FA,
- { provide: AuthMethod, useClass: configuration.auth.method === 'ldap' ? AuthMethodLdapService : AuthMethodDatabase }
+ AuthProvider2FA,
+ selectAuthProvider(configuration.auth.method)
],
- exports: [AuthManager, AuthMethod, AuthMethod2FA]
+ exports: [AuthManager, AuthProvider, AuthProvider2FA]
})
export class AuthModule {}
diff --git a/backend/src/authentication/services/auth-manager.service.spec.ts b/backend/src/authentication/auth.service.spec.ts
similarity index 93%
rename from backend/src/authentication/services/auth-manager.service.spec.ts
rename to backend/src/authentication/auth.service.spec.ts
index 9a717e86..aa7d301b 100755
--- a/backend/src/authentication/services/auth-manager.service.spec.ts
+++ b/backend/src/authentication/auth.service.spec.ts
@@ -7,7 +7,7 @@
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { Test, TestingModule } from '@nestjs/testing'
-import { AuthManager } from './auth-manager.service'
+import { AuthManager } from './auth.service'
describe(AuthManager.name, () => {
let authManager: AuthManager
diff --git a/backend/src/authentication/services/auth-manager.service.ts b/backend/src/authentication/auth.service.ts
similarity index 92%
rename from backend/src/authentication/services/auth-manager.service.ts
rename to backend/src/authentication/auth.service.ts
index 558b2dee..e1273e2a 100755
--- a/backend/src/authentication/services/auth-manager.service.ts
+++ b/backend/src/authentication/auth.service.ts
@@ -8,16 +8,16 @@ import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { FastifyReply, FastifyRequest } from 'fastify'
import crypto from 'node:crypto'
-import { HTTP_CSRF_IGNORED_METHODS } from '../../applications/applications.constants'
-import { UserModel } from '../../applications/users/models/user.model'
-import { convertHumanTimeToSeconds } from '../../common/functions'
-import { currentTimeStamp } from '../../common/shared'
-import { configuration, serverConfig } from '../../configuration/config.environment'
-import { CSRF_ERROR, CSRF_KEY, TOKEN_2FA_TYPES, TOKEN_PATHS, TOKEN_TYPES } from '../constants/auth'
-import { LoginResponseDto, LoginVerify2FaDto } from '../dto/login-response.dto'
-import { TokenResponseDto } from '../dto/token-response.dto'
-import { JwtIdentity2FaPayload, JwtIdentityPayload, JwtPayload } from '../interfaces/jwt-payload.interface'
-import { TOKEN_TYPE } from '../interfaces/token.interface'
+import { HTTP_CSRF_IGNORED_METHODS } from '../applications/applications.constants'
+import { UserModel } from '../applications/users/models/user.model'
+import { convertHumanTimeToSeconds } from '../common/functions'
+import { currentTimeStamp } from '../common/shared'
+import { configuration, serverConfig } from '../configuration/config.environment'
+import { CSRF_ERROR, CSRF_KEY, TOKEN_2FA_TYPES, TOKEN_PATHS, TOKEN_TYPES } from './constants/auth'
+import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto'
+import { TokenResponseDto } from './dto/token-response.dto'
+import { JwtIdentity2FaPayload, JwtIdentityPayload, JwtPayload } from './interfaces/jwt-payload.interface'
+import { TOKEN_TYPE } from './interfaces/token.interface'
@Injectable()
export class AuthManager {
diff --git a/backend/src/authentication/constants/routes.ts b/backend/src/authentication/constants/routes.ts
index f5e6efe2..375e0806 100644
--- a/backend/src/authentication/constants/routes.ts
+++ b/backend/src/authentication/constants/routes.ts
@@ -4,19 +4,22 @@
* See the LICENSE file for licensing details
*/
-export enum AUTH_ROUTE {
- BASE = '/api/auth',
- LOGIN = 'login',
- LOGOUT = 'logout',
- REFRESH = 'refresh',
- TOKEN = 'token',
- TOKEN_REFRESH = `${AUTH_ROUTE.TOKEN}/refresh`,
- WS = 'socket.io',
- TWO_FA_BASE = '2fa',
- TWO_FA_ENABLE = 'enable',
- TWO_FA_DISABLE = 'disable',
- TWO_FA_LOGIN_VERIFY = 'login/verify',
- TWO_FA_ADMIN_RESET_USER = 'reset/user'
+export const AUTH_ROUTE = {
+ BASE: '/api/auth',
+ LOGIN: 'login',
+ LOGOUT: 'logout',
+ REFRESH: 'refresh',
+ TOKEN: 'token',
+ TOKEN_REFRESH: 'token/refresh',
+ WS: 'socket.io',
+ TWO_FA_BASE: '2fa',
+ TWO_FA_ENABLE: 'enable',
+ TWO_FA_DISABLE: 'disable',
+ TWO_FA_LOGIN_VERIFY: 'login/verify',
+ TWO_FA_ADMIN_RESET_USER: 'reset/user',
+ OIDC_LOGIN: 'oidc/login',
+ OIDC_CALLBACK: 'oidc/callback',
+ OIDC_LOGOUT: 'oidc/logout'
}
export const API_AUTH_LOGIN = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.LOGIN}`
diff --git a/backend/src/authentication/dto/login-response.dto.ts b/backend/src/authentication/dto/login-response.dto.ts
index 631baa9d..29848550 100644
--- a/backend/src/authentication/dto/login-response.dto.ts
+++ b/backend/src/authentication/dto/login-response.dto.ts
@@ -22,7 +22,7 @@ export class LoginResponseDto {
export class LoginVerify2FaDto {
server: ServerConfig
- user = { twoFaEnabled: true }
+ user: { twoFaEnabled: boolean } = { twoFaEnabled: true }
token: TokenResponseDto
constructor(serverConfig: ServerConfig) {
@@ -30,8 +30,3 @@ export class LoginVerify2FaDto {
this.token = new TokenResponseDto()
}
}
-
-export class TwoFaResponseDto extends LoginResponseDto {
- success: boolean
- message: string
-}
diff --git a/backend/src/authentication/guards/auth-basic.guard.spec.ts b/backend/src/authentication/guards/auth-basic.guard.spec.ts
index 6a3192b9..28d7d5a9 100644
--- a/backend/src/authentication/guards/auth-basic.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-basic.guard.spec.ts
@@ -12,14 +12,14 @@ import { UserModel } from '../../applications/users/models/user.model'
import { generateUserTest } from '../../applications/users/utils/test'
import { WEBDAV_BASE_PATH } from '../../applications/webdav/constants/routes'
import { Cache } from '../../infrastructure/cache/services/cache.service'
-import { AuthMethod } from '../models/auth-method'
+import { AuthProvider } from '../providers/auth-providers.models'
import { AuthBasicGuard } from './auth-basic.guard'
import { AuthBasicStrategy } from './auth-basic.strategy'
describe(AuthBasicGuard.name, () => {
let authBasicGuard: AuthBasicGuard
let authBasicStrategy: AuthBasicStrategy
- let authMethod: AuthMethod
+ let authMethod: AuthProvider
let cache: Cache
let userTest: UserModel
let encodedAuth: string
@@ -31,7 +31,7 @@ describe(AuthBasicGuard.name, () => {
AuthBasicGuard,
AuthBasicStrategy,
{
- provide: AuthMethod,
+ provide: AuthProvider,
useValue: {
validateUser: async () => null
}
@@ -56,7 +56,7 @@ describe(AuthBasicGuard.name, () => {
authBasicGuard = module.get<AuthBasicGuard>(AuthBasicGuard)
authBasicStrategy = module.get<AuthBasicStrategy>(AuthBasicStrategy)
- authMethod = module.get<AuthMethod>(AuthMethod)
+ authMethod = module.get<AuthProvider>(AuthProvider)
cache = module.get<Cache>(Cache)
userTest = new UserModel(generateUserTest(), false)
encodedAuth = Buffer.from(`${userTest.login}:${userTest.password}`).toString('base64')
diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.ts
index 98813ccb..3367ae7a 100644
--- a/backend/src/authentication/guards/auth-basic.strategy.ts
+++ b/backend/src/authentication/guards/auth-basic.strategy.ts
@@ -13,7 +13,7 @@ import { UserModel } from '../../applications/users/models/user.model'
import { SERVER_NAME } from '../../common/shared'
import { Cache } from '../../infrastructure/cache/services/cache.service'
import { AUTH_SCOPE } from '../constants/scope'
-import { AuthMethod } from '../models/auth-method'
+import { AuthProvider } from '../providers/auth-providers.models'
import { HttpBasicStrategy } from './implementations/http-basic.strategy'
@Injectable()
@@ -22,7 +22,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
private readonly CACHE_KEY_PREFIX = 'auth-webdav'
constructor(
- private readonly authMethod: AuthMethod,
+ private readonly authProvider: AuthProvider,
private readonly cache: Cache,
private readonly logger: PinoLogger
) {
@@ -44,7 +44,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
// warning: plainToInstance do not use constructor to instantiate the class
return plainToInstance(UserModel, userFromCache)
}
- const userFromDB: UserModel = await this.authMethod.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)
+ const userFromDB: UserModel = await this.authProvider.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)
if (userFromDB !== null) {
userFromDB.removePassword()
}
diff --git a/backend/src/authentication/guards/auth-local.guard.spec.ts b/backend/src/authentication/guards/auth-local.guard.spec.ts
index d126182c..443267a9 100644
--- a/backend/src/authentication/guards/auth-local.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-local.guard.spec.ts
@@ -10,13 +10,13 @@ import { Test, TestingModule } from '@nestjs/testing'
import { PinoLogger } from 'nestjs-pino'
import { UserModel } from '../../applications/users/models/user.model'
import { generateUserTest } from '../../applications/users/utils/test'
-import { AuthMethod } from '../models/auth-method'
+import { AuthProvider } from '../providers/auth-providers.models'
import { AuthLocalGuard } from './auth-local.guard'
import { AuthLocalStrategy } from './auth-local.strategy'
describe(AuthLocalGuard.name, () => {
let authLocalGuard: AuthLocalGuard
- let authMethod: AuthMethod
+ let authMethod: AuthProvider
let userTest: UserModel
let context: DeepMocked<ExecutionContext>
@@ -25,7 +25,7 @@ describe(AuthLocalGuard.name, () => {
providers: [
AuthLocalGuard,
AuthLocalStrategy,
- { provide: AuthMethod, useValue: {} },
+ { provide: AuthProvider, useValue: {} },
{
provide: PinoLogger,
useValue: {
@@ -36,7 +36,7 @@ describe(AuthLocalGuard.name, () => {
}).compile()
authLocalGuard = module.get<AuthLocalGuard>(AuthLocalGuard)
- authMethod = module.get<AuthMethod>(AuthMethod)
+ authMethod = module.get<AuthProvider>(AuthProvider)
userTest = new UserModel(generateUserTest(), false)
context = createMock<ExecutionContext>()
})
diff --git a/backend/src/authentication/guards/auth-local.strategy.ts b/backend/src/authentication/guards/auth-local.strategy.ts
index e555cb4f..b083e720 100755
--- a/backend/src/authentication/guards/auth-local.strategy.ts
+++ b/backend/src/authentication/guards/auth-local.strategy.ts
@@ -10,12 +10,12 @@ import type { FastifyRequest } from 'fastify'
import { PinoLogger } from 'nestjs-pino'
import { Strategy } from 'passport-local'
import type { UserModel } from '../../applications/users/models/user.model'
-import { AuthMethod } from '../models/auth-method'
+import { AuthProvider } from '../providers/auth-providers.models'
@Injectable()
export class AuthLocalStrategy extends PassportStrategy(Strategy, 'local') implements AbstractStrategy {
constructor(
- private readonly authMethod: AuthMethod,
+ private readonly authMethod: AuthProvider,
private readonly logger: PinoLogger
) {
super({ usernameField: 'login', passwordField: 'password', passReqToCallback: true })
diff --git a/backend/src/authentication/guards/auth-token-access.guard.spec.ts b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
index 7dc5df40..ce21d492 100644
--- a/backend/src/authentication/guards/auth-token-access.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
@@ -18,12 +18,12 @@ import { UsersManager } from '../../applications/users/services/users-manager.se
import { WEB_DAV_CONTEXT, WebDAVContext } from '../../applications/webdav/decorators/webdav-context.decorator'
import { exportConfiguration } from '../../configuration/config.environment'
import { AuthConfig } from '../auth.config'
+import { AuthManager } from '../auth.service'
import { CSRF_ERROR } from '../constants/auth'
import { AuthTokenOptional } from '../decorators/auth-token-optional.decorator'
import { AUTH_TOKEN_SKIP, AuthTokenSkip } from '../decorators/auth-token-skip.decorator'
import { JwtPayload } from '../interfaces/jwt-payload.interface'
import { TOKEN_TYPE } from '../interfaces/token.interface'
-import { AuthManager } from '../services/auth-manager.service'
import { AuthAnonymousGuard } from './auth-anonymous.guard'
import { AuthAnonymousStrategy } from './auth-anonymous.strategy'
import { AuthTokenAccessGuard } from './auth-token-access.guard'
diff --git a/backend/src/authentication/guards/auth-token-access.strategy.ts b/backend/src/authentication/guards/auth-token-access.strategy.ts
index 2fc5b3a3..3f1f56e6 100755
--- a/backend/src/authentication/guards/auth-token-access.strategy.ts
+++ b/backend/src/authentication/guards/auth-token-access.strategy.ts
@@ -11,9 +11,9 @@ import { PinoLogger } from 'nestjs-pino'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../applications/users/models/user.model'
import { configuration } from '../../configuration/config.environment'
+import { AuthManager } from '../auth.service'
import { JwtPayload } from '../interfaces/jwt-payload.interface'
import { TOKEN_TYPE } from '../interfaces/token.interface'
-import { AuthManager } from '../services/auth-manager.service'
@Injectable()
export class AuthTokenAccessStrategy extends PassportStrategy(Strategy, 'tokenAccess') implements AbstractStrategy {
diff --git a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
index 49b67f26..d93da5b0 100644
--- a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
@@ -16,10 +16,10 @@ import crypto from 'node:crypto'
import { UsersManager } from '../../applications/users/services/users-manager.service'
import { exportConfiguration } from '../../configuration/config.environment'
import { AuthConfig } from '../auth.config'
+import { AuthManager } from '../auth.service'
import { CSRF_ERROR } from '../constants/auth'
import { JwtPayload } from '../interfaces/jwt-payload.interface'
import { TOKEN_TYPE } from '../interfaces/token.interface'
-import { AuthManager } from '../services/auth-manager.service'
import { AuthTokenRefreshGuard } from './auth-token-refresh.guard'
import { AuthTokenRefreshStrategy } from './auth-token-refresh.strategy'
diff --git a/backend/src/authentication/guards/auth-token-refresh.strategy.ts b/backend/src/authentication/guards/auth-token-refresh.strategy.ts
index ad2a291e..48a523ba 100755
--- a/backend/src/authentication/guards/auth-token-refresh.strategy.ts
+++ b/backend/src/authentication/guards/auth-token-refresh.strategy.ts
@@ -11,9 +11,9 @@ import { PinoLogger } from 'nestjs-pino'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../applications/users/models/user.model'
import { configuration } from '../../configuration/config.environment'
+import { AuthManager } from '../auth.service'
import { JwtPayload } from '../interfaces/jwt-payload.interface'
import { TOKEN_TYPE } from '../interfaces/token.interface'
-import { AuthManager } from '../services/auth-manager.service'
@Injectable()
export class AuthTokenRefreshStrategy extends PassportStrategy(Strategy, 'tokenRefresh') implements AbstractStrategy {
diff --git a/backend/src/authentication/providers/auth-providers.constants.ts b/backend/src/authentication/providers/auth-providers.constants.ts
new file mode 100644
index 00000000..72d5a506
--- /dev/null
+++ b/backend/src/authentication/providers/auth-providers.constants.ts
@@ -0,0 +1,11 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+export enum AUTH_PROVIDER {
+ MYSQL = 'mysql',
+ LDAP = 'ldap',
+ OIDC = 'oidc'
+}
diff --git a/backend/src/authentication/models/auth-method.ts b/backend/src/authentication/providers/auth-providers.models.ts
similarity index 92%
rename from backend/src/authentication/models/auth-method.ts
rename to backend/src/authentication/providers/auth-providers.models.ts
index 1b6aed9f..c42479e3 100644
--- a/backend/src/authentication/models/auth-method.ts
+++ b/backend/src/authentication/providers/auth-providers.models.ts
@@ -7,6 +7,6 @@
import type { UserModel } from '../../applications/users/models/user.model'
import type { AUTH_SCOPE } from '../constants/scope'
-export abstract class AuthMethod {
+export abstract class AuthProvider {
abstract validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel>
}
diff --git a/backend/src/authentication/providers/auth-providers.utils.ts b/backend/src/authentication/providers/auth-providers.utils.ts
new file mode 100644
index 00000000..c52419bd
--- /dev/null
+++ b/backend/src/authentication/providers/auth-providers.utils.ts
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Provider } from '@nestjs/common'
+import { AUTH_PROVIDER } from './auth-providers.constants'
+
+import { AuthProvider } from './auth-providers.models'
+import { AuthProviderLDAP } from './ldap/auth-provider-ldap.service'
+import { AuthProviderMySQL } from './mysql/auth-provider-mysql.service'
+import { AuthProviderOIDC } from './oidc/auth-provider-oidc.service'
+
+export function selectAuthProvider(provider: AUTH_PROVIDER): Provider {
+ switch (provider) {
+ case AUTH_PROVIDER.OIDC:
+ // AuthMethodOIDC is already provided by AuthMethodOIDCModule
+ return { provide: AuthProvider, useExisting: AuthProviderOIDC }
+
+ case AUTH_PROVIDER.LDAP:
+ return { provide: AuthProvider, useClass: AuthProviderLDAP }
+
+ case AUTH_PROVIDER.MYSQL:
+ return { provide: AuthProvider, useClass: AuthProviderMySQL }
+
+ default:
+ return { provide: AuthProvider, useClass: AuthProviderMySQL }
+ }
+}
diff --git a/backend/src/authentication/providers/ldap/auth-ldap.config.ts b/backend/src/authentication/providers/ldap/auth-ldap.config.ts
new file mode 100644
index 00000000..8a88cadd
--- /dev/null
+++ b/backend/src/authentication/providers/ldap/auth-ldap.config.ts
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Transform, Type } from 'class-transformer'
+import {
+ ArrayNotEmpty,
+ IsArray,
+ IsDefined,
+ IsEnum,
+ IsNotEmpty,
+ IsNotEmptyObject,
+ IsObject,
+ IsOptional,
+ IsString,
+ ValidateNested
+} from 'class-validator'
+import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './auth-ldap.constants'
+
+export class AuthMethodLDAPAttributesConfig {
+ @IsOptional()
+ @Transform(({ value }) => value || LDAP_LOGIN_ATTR.UID)
+ @IsEnum(LDAP_LOGIN_ATTR)
+ login: LDAP_LOGIN_ATTR = LDAP_LOGIN_ATTR.UID
+
+ @IsOptional()
+ @IsString()
+ @Transform(({ value }) => value || LDAP_COMMON_ATTR.MAIL)
+ email: string = LDAP_COMMON_ATTR.MAIL
+}
+
+export class AuthMethodLDAPConfig {
+ @Transform(({ value }) => (Array.isArray(value) ? value.filter((v: string) => Boolean(v)) : value))
+ @ArrayNotEmpty()
+ @IsArray()
+ @IsString({ each: true })
+ servers: string[]
+
+ @IsString()
+ @IsNotEmpty()
+ baseDN: string
+
+ @IsOptional()
+ @IsString()
+ filter?: string
+
+ @IsDefined()
+ @IsNotEmptyObject()
+ @IsObject()
+ @ValidateNested()
+ @Type(() => AuthMethodLDAPAttributesConfig)
+ attributes: AuthMethodLDAPAttributesConfig = new AuthMethodLDAPAttributesConfig()
+
+ @IsOptional()
+ @IsString()
+ adminGroup?: string
+
+ @IsOptional()
+ @IsString()
+ upnSuffix?: string
+
+ @IsOptional()
+ @IsString()
+ netbiosName?: string
+}
diff --git a/backend/src/authentication/constants/auth-ldap.ts b/backend/src/authentication/providers/ldap/auth-ldap.constants.ts
similarity index 100%
rename from backend/src/authentication/constants/auth-ldap.ts
rename to backend/src/authentication/providers/ldap/auth-ldap.constants.ts
diff --git a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts
similarity index 98%
rename from backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
rename to backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts
index f452c87f..64ad037c 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts
@@ -13,8 +13,8 @@ import { AdminUsersManager } from '../../../applications/users/services/admin-us
import { UsersManager } from '../../../applications/users/services/users-manager.service'
import * as commonFunctions from '../../../common/functions'
import { configuration } from '../../../configuration/config.environment'
-import { LDAP_LOGIN_ATTR } from '../../constants/auth-ldap'
-import { AuthMethodLdapService } from './auth-method-ldap.service'
+import { LDAP_LOGIN_ATTR } from './auth-ldap.constants'
+import { AuthProviderLDAP } from './auth-provider-ldap.service'
// Mock ldapts Client to simulate LDAP behaviors
jest.mock('ldapts', () => {
@@ -61,8 +61,8 @@ const buildUser = (overrides: Partial<UserModel> = {}) =>
// --------------------------
-describe(AuthMethodLdapService.name, () => {
- let authMethodLdapService: AuthMethodLdapService
+describe(AuthProviderLDAP.name, () => {
+ let authMethodLdapService: AuthProviderLDAP
let usersManager: Mocked<UsersManager>
let adminUsersManager: Mocked<AdminUsersManager>
const ldapClient = {
@@ -89,7 +89,7 @@ describe(AuthMethodLdapService.name, () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
- AuthMethodLdapService,
+ AuthProviderLDAP,
{
provide: UsersManager,
useValue: {
@@ -111,7 +111,7 @@ describe(AuthMethodLdapService.name, () => {
}).compile()
module.useLogger(['fatal'])
- authMethodLdapService = module.get<AuthMethodLdapService>(AuthMethodLdapService)
+ authMethodLdapService = module.get<AuthProviderLDAP>(AuthProviderLDAP)
adminUsersManager = module.get<Mocked<AdminUsersManager>>(AdminUsersManager)
usersManager = module.get<Mocked<UsersManager>>(UsersManager)
})
diff --git a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
similarity index 98%
rename from backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts
rename to backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
index 2dc85bb9..3623fd85 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts
+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
@@ -14,15 +14,15 @@ import { AdminUsersManager } from '../../../applications/users/services/admin-us
import { UsersManager } from '../../../applications/users/services/users-manager.service'
import { comparePassword, splitFullName } from '../../../common/functions'
import { configuration } from '../../../configuration/config.environment'
-import { ALL_LDAP_ATTRIBUTES, LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from '../../constants/auth-ldap'
import type { AUTH_SCOPE } from '../../constants/scope'
-import { AuthMethod } from '../../models/auth-method'
+import { AuthProvider } from '../auth-providers.models'
+import { ALL_LDAP_ATTRIBUTES, LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './auth-ldap.constants'
type LdapUserEntry = Entry & Record<LDAP_LOGIN_ATTR | (typeof LDAP_COMMON_ATTR)[keyof typeof LDAP_COMMON_ATTR], string>
@Injectable()
-export class AuthMethodLdapService implements AuthMethod {
- private readonly logger = new Logger(AuthMethodLdapService.name)
+export class AuthProviderLDAP implements AuthProvider {
+ private readonly logger = new Logger(AuthProviderLDAP.name)
private readonly ldapConfig = configuration.auth.ldap
private readonly isAD = this.ldapConfig.attributes.login === LDAP_LOGIN_ATTR.SAM || this.ldapConfig.attributes.login === LDAP_LOGIN_ATTR.UPN
private clientOptions: ClientOptions = { timeout: 6000, connectTimeout: 6000, url: '' }
@@ -148,10 +148,12 @@ export class AuthMethodLdapService implements AuthMethod {
}
return freshUser
}
+
if (identity.login !== user.login) {
this.logger.error(`${this.updateOrCreateUser.name} - user login mismatch : ${identity.login} !== ${user.login}`)
throw new HttpException('Account matching error', HttpStatus.FORBIDDEN)
}
+
// Update: check if user information has changed
const identityHasChanged: UpdateUserDto = Object.fromEntries(
(
@@ -166,6 +168,7 @@ export class AuthMethodLdapService implements AuthMethod {
)
).filter(Boolean)
)
+
if (Object.keys(identityHasChanged).length > 0) {
try {
if (identityHasChanged?.role != null) {
@@ -174,13 +177,17 @@ export class AuthMethodLdapService implements AuthMethod {
delete identityHasChanged.role
}
}
+
// Update user properties
await this.adminUsersManager.updateUserOrGuest(user.id, identityHasChanged)
+
// Extra stuff
if (identityHasChanged?.password) {
delete identityHasChanged.password
}
+
Object.assign(user, identityHasChanged)
+
if ('lastName' in identityHasChanged || 'firstName' in identityHasChanged) {
// Force fullName update in the current user model
user.setFullName(true)
diff --git a/backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts
similarity index 75%
rename from backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts
rename to backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts
index 4778964d..e222f931 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts
+++ b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts
@@ -16,18 +16,18 @@ import { generateUserTest } from '../../../applications/users/utils/test'
import { hashPassword } from '../../../common/functions'
import { Cache } from '../../../infrastructure/cache/services/cache.service'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
-import { AuthManager } from '../auth-manager.service'
-import { AuthMethodDatabase } from './auth-method-database.service'
+import { AuthManager } from '../../auth.service'
+import { AuthProviderMySQL } from './auth-provider-mysql.service'
-describe(AuthMethodDatabase.name, () => {
- let authMethodDatabase: AuthMethodDatabase
+describe(AuthProviderMySQL.name, () => {
+ let authProviderMySQL: AuthProviderMySQL
let usersManager: UsersManager
let userTest: UserModel
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
- AuthMethodDatabase,
+ AuthProviderMySQL,
UsersManager,
UsersQueries,
AdminUsersManager,
@@ -39,7 +39,7 @@ describe(AuthMethodDatabase.name, () => {
]
}).compile()
- authMethodDatabase = module.get<AuthMethodDatabase>(AuthMethodDatabase)
+ authProviderMySQL = module.get<AuthProviderMySQL>(AuthProviderMySQL)
usersManager = module.get<UsersManager>(UsersManager)
module.useLogger(['fatal'])
// mocks
@@ -48,7 +48,7 @@ describe(AuthMethodDatabase.name, () => {
})
it('should be defined', () => {
- expect(authMethodDatabase).toBeDefined()
+ expect(authProviderMySQL).toBeDefined()
expect(usersManager).toBeDefined()
expect(userTest).toBeDefined()
})
@@ -56,7 +56,7 @@ describe(AuthMethodDatabase.name, () => {
it('should validate the user', async () => {
userTest.makePaths = jest.fn()
usersManager.findUser = jest.fn().mockReturnValue({ ...userTest, password: await hashPassword(userTest.password) })
- expect(await authMethodDatabase.validateUser(userTest.login, userTest.password)).toBeDefined()
+ expect(await authProviderMySQL.validateUser(userTest.login, userTest.password)).toBeDefined()
expect(userTest.makePaths).toHaveBeenCalled()
})
@@ -71,9 +71,9 @@ describe(AuthMethodDatabase.name, () => {
cause: { code: Array.from(CONNECT_ERROR_CODE)[0] }
})
)
- expect(await authMethodDatabase.validateUser(userTest.login, userTest.password)).toBeNull()
- expect(await authMethodDatabase.validateUser(userTest.login, userTest.password)).toBeNull()
- await expect(authMethodDatabase.validateUser(userTest.login, userTest.password)).rejects.toThrow(/db error/i)
- await expect(authMethodDatabase.validateUser(userTest.login, userTest.password)).rejects.toThrow(/authentication service/i)
+ expect(await authProviderMySQL.validateUser(userTest.login, userTest.password)).toBeNull()
+ expect(await authProviderMySQL.validateUser(userTest.login, userTest.password)).toBeNull()
+ await expect(authProviderMySQL.validateUser(userTest.login, userTest.password)).rejects.toThrow(/db error/i)
+ await expect(authProviderMySQL.validateUser(userTest.login, userTest.password)).rejects.toThrow(/authentication service/i)
})
})
diff --git a/backend/src/authentication/services/auth-methods/auth-method-database.service.ts b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
similarity index 88%
rename from backend/src/authentication/services/auth-methods/auth-method-database.service.ts
rename to backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
index 0c374338..c993062d 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-database.service.ts
+++ b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
@@ -9,11 +9,11 @@ import { CONNECT_ERROR_CODE } from '../../../app.constants'
import { UserModel } from '../../../applications/users/models/user.model'
import { UsersManager } from '../../../applications/users/services/users-manager.service'
import { AUTH_SCOPE } from '../../constants/scope'
-import { AuthMethod } from '../../models/auth-method'
+import { AuthProvider } from '../auth-providers.models'
@Injectable()
-export class AuthMethodDatabase implements AuthMethod {
- private readonly logger = new Logger(AuthMethodDatabase.name)
+export class AuthProviderMySQL implements AuthProvider {
+ private readonly logger = new Logger(AuthProviderMySQL.name)
constructor(private readonly usersManager: UsersManager) {}
diff --git a/backend/src/authentication/providers/oidc/auth-method-oidc.module.ts b/backend/src/authentication/providers/oidc/auth-method-oidc.module.ts
new file mode 100644
index 00000000..d08660bf
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-method-oidc.module.ts
@@ -0,0 +1,16 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Module } from '@nestjs/common'
+import { AuthOIDCController } from './auth-oidc.controller'
+import { AuthProviderOIDC } from './auth-provider-oidc.service'
+
+@Module({
+ controllers: [AuthOIDCController],
+ providers: [AuthProviderOIDC],
+ exports: [AuthProviderOIDC]
+})
+export class AuthMethodOIDCModule {}
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.config.ts b/backend/src/authentication/providers/oidc/auth-oidc.config.ts
new file mode 100644
index 00000000..0b228042
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-oidc.config.ts
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Transform } from 'class-transformer'
+import { IsBoolean, IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator'
+import { OAuthTokenEndpoint } from './auth-oidc.constants'
+
+export class AuthMethodOIDCConfig {
+ @IsString()
+ @IsNotEmpty()
+ issuerUrl: string
+
+ @IsString()
+ @IsNotEmpty()
+ clientId: string
+
+ @IsString()
+ @IsNotEmpty()
+ clientSecret: string
+
+ @IsOptional()
+ @Transform(({ value }) => value || OAuthTokenEndpoint.ClientSecretBasic)
+ @IsEnum(OAuthTokenEndpoint)
+ clientAuthMethod: OAuthTokenEndpoint = OAuthTokenEndpoint.ClientSecretBasic
+
+ @IsString()
+ @IsNotEmpty()
+ redirectUri: string
+
+ @IsOptional()
+ @IsString()
+ scope?: string
+
+ @IsOptional()
+ @IsBoolean()
+ autoCreateUser? = true
+
+ @IsOptional()
+ @IsBoolean()
+ skipSubjectCheck? = false
+
+ @IsOptional()
+ @IsString()
+ adminRoleOrGroup?: string
+}
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.constants.ts b/backend/src/authentication/providers/oidc/auth-oidc.constants.ts
new file mode 100644
index 00000000..05f95a63
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-oidc.constants.ts
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+export enum OAuthTokenEndpoint {
+ ClientSecretPost = 'client_secret_post',
+ ClientSecretBasic = 'client_secret_basic'
+}
+
+export const OAuthCookie = {
+ State: 'oidc_state',
+ Nonce: 'oidc_nonce',
+ CodeVerifier: 'oidc_code_verifier'
+} as const
+
+export const OAuthCookieSettings = { httpOnly: true, path: '/', maxAge: 600, sameSite: 'lax' } as const
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.controller.ts b/backend/src/authentication/providers/oidc/auth-oidc.controller.ts
new file mode 100644
index 00000000..feeb32b6
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-oidc.controller.ts
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Controller, Get, HttpStatus, Query, Req, Res } from '@nestjs/common'
+import { FastifyReply, FastifyRequest } from 'fastify'
+import type { UserModel } from '../../../applications/users/models/user.model'
+import { AuthManager } from '../../auth.service'
+import { AUTH_ROUTE } from '../../constants/routes'
+import { AuthTokenSkip } from '../../decorators/auth-token-skip.decorator'
+import type { LoginResponseDto } from '../../dto/login-response.dto'
+import { AuthProviderOIDC } from './auth-provider-oidc.service'
+
+@Controller(AUTH_ROUTE.BASE)
+export class AuthOIDCController {
+ constructor(
+ private readonly authManager: AuthManager,
+ private readonly authMethodOidc: AuthProviderOIDC
+ ) {}
+
+ @Get(AUTH_ROUTE.OIDC_LOGIN)
+ @AuthTokenSkip()
+ async oidcLogin(@Res() res: FastifyReply): Promise<void> {
+ const url = await this.authMethodOidc.getAuthorizationUrl(res)
+ // Redirect to OIDC provider
+ return res.redirect(url, HttpStatus.FOUND)
+ }
+
+ @Get(AUTH_ROUTE.OIDC_CALLBACK)
+ @AuthTokenSkip()
+ async oidcCallback(@Query() query: Record<string, string>, @Req() req: FastifyRequest, @Res() res: FastifyReply): Promise<void> {
+ const user: UserModel = await this.authMethodOidc.handleCallback(req, res, query)
+ const r: LoginResponseDto = await this.authManager.setCookies(user, res, false)
+ return res.redirect(this.authMethodOidc.getRedirectCallbackUrl(r.token.access_expiration, r.token.refresh_expiration), HttpStatus.FOUND)
+ }
+}
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
new file mode 100644
index 00000000..1c28b7be
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
@@ -0,0 +1,376 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
+import { FastifyReply, FastifyRequest } from 'fastify'
+import {
+ allowInsecureRequests,
+ authorizationCodeGrant,
+ calculatePKCECodeChallenge,
+ ClientSecretBasic,
+ ClientSecretPost,
+ Configuration,
+ discovery,
+ fetchUserInfo,
+ IDToken,
+ None,
+ randomNonce,
+ randomPKCECodeVerifier,
+ randomState,
+ skipSubjectCheck,
+ UserInfoResponse
+} from 'openid-client'
+import { USER_ROLE } from '../../../applications/users/constants/user'
+import type { CreateUserDto, UpdateUserDto } from '../../../applications/users/dto/create-or-update-user.dto'
+import { UserModel } from '../../../applications/users/models/user.model'
+import { AdminUsersManager } from '../../../applications/users/services/admin-users-manager.service'
+import { UsersManager } from '../../../applications/users/services/users-manager.service'
+import { generateShortUUID, splitFullName } from '../../../common/functions'
+import { configuration } from '../../../configuration/config.environment'
+import { AUTH_ROUTE } from '../../constants/routes'
+import type { AUTH_SCOPE } from '../../constants/scope'
+import { TOKEN_TYPE } from '../../interfaces/token.interface'
+import { AUTH_PROVIDER } from '../auth-providers.constants'
+import { AuthProvider } from '../auth-providers.models'
+import { AuthMethodOIDCConfig } from './auth-oidc.config'
+import { OAuthCookie, OAuthCookieSettings, OAuthTokenEndpoint } from './auth-oidc.constants'
+
+@Injectable()
+export class AuthProviderOIDC implements AuthProvider {
+ private readonly logger = new Logger(AuthProviderOIDC.name)
+ private readonly oidcConfig: AuthMethodOIDCConfig = configuration.auth.oidc
+ private frontendBaseUrl: string
+ private config: Configuration = null
+
+ constructor(
+ private readonly usersManager: UsersManager,
+ private readonly adminUsersManager: AdminUsersManager
+ ) {}
+
+ async getConfig(): Promise<Configuration> {
+ if (!this.config) {
+ this.config = await this.initializeOIDCClient()
+ if (!this.config) {
+ throw new HttpException('Failed to initialize OIDC client', HttpStatus.INTERNAL_SERVER_ERROR)
+ }
+ }
+ return this.config
+ }
+
+ async getAuthorizationUrl(res: FastifyReply): Promise<string> {
+ const config = await this.getConfig()
+
+ // Generate state and nonce for CSRF protection
+ const state = randomState()
+ const nonce = randomNonce()
+
+ const codeVerifier = randomPKCECodeVerifier()
+
+ const authUrl = new URL(config.serverMetadata().authorization_endpoint!)
+ authUrl.searchParams.set('client_id', this.oidcConfig.clientId!)
+ authUrl.searchParams.set('redirect_uri', this.oidcConfig.redirectUri)
+ authUrl.searchParams.set('response_type', 'code')
+ authUrl.searchParams.set('scope', this.oidcConfig.scope || 'openid email profile')
+ if (config.serverMetadata().supportsPKCE()) {
+ const codeChallenge = await calculatePKCECodeChallenge(codeVerifier)
+ authUrl.searchParams.set('code_challenge', codeChallenge)
+ authUrl.searchParams.set('code_challenge_method', 'S256')
+ }
+ authUrl.searchParams.set('state', state)
+ authUrl.searchParams.set('nonce', nonce)
+
+ // Avoid cache
+ res
+ .header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
+ .header('Pragma', 'no-cache')
+ .header('Expires', '0')
+ .header('X-Robots-Tag', 'noindex, nofollow')
+ .header('Referrer-Policy', 'no-referrer')
+
+ // Store state, nonce, and codeVerifier in httpOnly cookies (10 minutes expiration)
+ res.setCookie(OAuthCookie.State, state, OAuthCookieSettings)
+ res.setCookie(OAuthCookie.Nonce, nonce, OAuthCookieSettings)
+ res.setCookie(OAuthCookie.CodeVerifier, codeVerifier, OAuthCookieSettings)
+
+ return authUrl.toString()
+ }
+
+ async handleCallback(req: FastifyRequest, res: FastifyReply, query: Record<string, string>): Promise<UserModel> {
+ const config = await this.getConfig()
+
+ // Clear temporary OIDC cookies
+ Object.values(OAuthCookie).forEach((value) => {
+ res.clearCookie(value, { path: '/' })
+ })
+
+ const [expectedState, expectedNonce, codeVerifier] = [
+ req.cookies[OAuthCookie.State],
+ req.cookies[OAuthCookie.Nonce],
+ req.cookies[OAuthCookie.CodeVerifier]
+ ]
+
+ try {
+ if (!expectedState?.length) {
+ throw new HttpException('OAuth state is missing', HttpStatus.BAD_REQUEST)
+ }
+
+ if (!codeVerifier?.length) {
+ throw new HttpException('OAuth code verifier is missing', HttpStatus.BAD_REQUEST)
+ }
+
+ const pkceCodeVerifier = config.serverMetadata().supportsPKCE() ? codeVerifier : undefined
+ const callbackParams = new URLSearchParams(query)
+
+ // Exchange authorization code for tokens
+ const callbackUrl = new URL(this.oidcConfig.redirectUri)
+ callbackUrl.search = callbackParams.toString()
+ const tokens = await authorizationCodeGrant(config, callbackUrl, {
+ expectedState,
+ pkceCodeVerifier,
+ expectedNonce
+ })
+
+ // Get validated ID token claims
+ const claims: IDToken = tokens.claims()
+ if (!claims) {
+ throw new HttpException('No ID token claims found', HttpStatus.BAD_REQUEST)
+ }
+ if (!claims.sub) {
+ throw new HttpException('Unexpected profile response, no `sub`', HttpStatus.BAD_REQUEST)
+ }
+
+ // Get user info from the userinfo endpoint (requires access token and subject from ID token)
+ const subject = this.oidcConfig.skipSubjectCheck ? skipSubjectCheck : claims.sub
+ const userInfo: UserInfoResponse = await fetchUserInfo(config, tokens.access_token, subject)
+
+ if (!userInfo.sub) {
+ throw new Error('Unexpected profile response, no `sub`')
+ }
+
+ // Process the user info and create/update the user
+ return await this.processUserInfo(userInfo, req.ip)
+ } catch (error) {
+ const errorStatus = error?.getStatus() || HttpStatus.UNAUTHORIZED
+ this.logger.error(`${this.handleCallback.name} - OIDC callback error: ${error}`)
+ throw new HttpException('OIDC authentication failed', errorStatus)
+ }
+ }
+
+ async validateUser(login: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
+ // TODO: should not validate password for OIDC users
+ // Find user from login or email
+ const user: UserModel = await this.usersManager.findUser(login, false)
+
+ if (!user) {
+ return null
+ }
+
+ if (user.isGuest) {
+ // Allow guests to be authenticated from db
+ return this.usersManager.logUser(user, password, ip)
+ }
+
+ if (!user.isActive) {
+ this.logger.error(`${this.validateUser.name} - user *${user.login}* is locked`)
+ throw new HttpException('Account locked', HttpStatus.FORBIDDEN)
+ }
+
+ // For OIDC users, only allow app password authentication
+ let authSuccess = false
+ if (scope) {
+ authSuccess = await this.usersManager.validateAppPassword(user, password, ip, scope)
+ }
+
+ this.usersManager.updateAccesses(user, ip, authSuccess).catch((e: Error) => this.logger.error(`${this.validateUser.name} : ${e}`))
+
+ if (authSuccess) {
+ return user
+ }
+
+ return null
+ }
+
+ getRedirectCallbackUrl(accessExpiration: number, refreshExpiration: number) {
+ if (!this.frontendBaseUrl) {
+ const url = new URL(this.oidcConfig.redirectUri)
+ const apiIndex = url.pathname.indexOf(AUTH_ROUTE.BASE)
+ this.frontendBaseUrl = apiIndex >= 0 ? `${url.origin}${url.pathname.slice(0, apiIndex)}` : url.origin
+ }
+ const url = new URL('/#/', this.frontendBaseUrl)
+ const params = new URLSearchParams({
+ [AUTH_PROVIDER.OIDC]: 'true',
+ [`${TOKEN_TYPE.ACCESS}_expiration`]: `${accessExpiration}`,
+ [`${TOKEN_TYPE.REFRESH}_expiration`]: `${refreshExpiration}`
+ })
+ url.hash = `/?${params.toString()}`
+ return url.toString()
+ }
+
+ private async initializeOIDCClient(): Promise<Configuration> {
+ try {
+ const issuerUrl = new URL(this.oidcConfig.issuerUrl)
+ const config: Configuration = await discovery(
+ issuerUrl,
+ this.oidcConfig.clientId,
+ { client_secret: this.oidcConfig.clientSecret, response_types: ['code'] },
+ this.getTokenAuthMethod(this.oidcConfig.clientAuthMethod, this.oidcConfig.clientSecret),
+ {
+ execute: [allowInsecureRequests] // allow HTTP for development
+ }
+ )
+ this.logger.log(`${this.initializeOIDCClient.name} - OIDC client initialized successfully for issuer: ${this.oidcConfig.issuerUrl}`)
+ return config
+ } catch (error) {
+ this.logger.error(`${this.initializeOIDCClient.name} - Failed to initialize OIDC client: ${error}`)
+ return null
+ }
+ }
+
+ private getTokenAuthMethod(tokenEndpointAuthMethod: OAuthTokenEndpoint, clientSecret?: string) {
+ if (!clientSecret) {
+ return None()
+ }
+
+ switch (tokenEndpointAuthMethod) {
+ case OAuthTokenEndpoint.ClientSecretPost: {
+ return ClientSecretPost(clientSecret)
+ }
+
+ case OAuthTokenEndpoint.ClientSecretBasic: {
+ return ClientSecretBasic(clientSecret)
+ }
+
+ default: {
+ return None()
+ }
+ }
+ }
+
+ private async processUserInfo(userInfo: UserInfoResponse, ip?: string): Promise<UserModel> {
+ // Extract user information
+ const { login, email } = this.extractLoginAndEmail(userInfo)
+
+ // Check if user exists
+ let user: UserModel = await this.usersManager.findUser(email || login, false)
+
+ if (!user && !this.oidcConfig.autoCreateUser) {
+ throw new HttpException('User not found and autoCreateUser is disabled', HttpStatus.UNAUTHORIZED)
+ }
+
+ // Determine if user should be admin based on groups/roles
+ const isAdmin = this.checkAdminRole(userInfo)
+
+ // Create identity
+ const identity = this.createIdentity(login, email, userInfo, isAdmin)
+
+ // Create or update user
+ user = await this.updateOrCreateUser(identity, user)
+
+ // Update user access log
+ this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error(`${this.processUserInfo.name} : ${e}`))
+
+ return user
+ }
+
+ private checkAdminRole(userInfo: UserInfoResponse): boolean {
+ if (!this.oidcConfig.adminRoleOrGroup) {
+ return false
+ }
+
+ // Check claims
+ const claims = [...(Array.isArray(userInfo.groups) ? userInfo.groups : []), ...(Array.isArray(userInfo.roles) ? userInfo.roles : [])]
+
+ return claims.includes(this.oidcConfig.adminRoleOrGroup)
+ }
+
+ private createIdentity(
+ login: string,
+ email: string,
+ userInfo: UserInfoResponse,
+ isAdmin: boolean
+ ): Omit<CreateUserDto, 'password'> & { password?: string } {
+ // Get first name and last name
+ let firstName = userInfo.given_name || ''
+ let lastName = userInfo.family_name || ''
+
+ // If structured names not available, try to split the full name
+ if (!firstName && !lastName && userInfo.name) {
+ const names = splitFullName(userInfo.name)
+ firstName = names.firstName
+ lastName = names.lastName
+ }
+
+ return {
+ login,
+ email,
+ role: isAdmin ? USER_ROLE.ADMINISTRATOR : USER_ROLE.USER,
+ firstName,
+ lastName
+ }
+ }
+
+ private async updateOrCreateUser(identity: Omit<CreateUserDto, 'password'> & { password?: string }, user: UserModel | null): Promise<UserModel> {
+ if (user === null) {
+ // Create new user with a random password (required by the system but not used for OIDC login)
+ const userWithPassword = { ...identity, password: generateShortUUID(24) } as CreateUserDto
+ const createdUser = await this.adminUsersManager.createUserOrGuest(userWithPassword, identity.role)
+ const freshUser = await this.usersManager.fromUserId(createdUser.id)
+ if (!freshUser) {
+ this.logger.error(`${this.updateOrCreateUser.name} - user was not found : ${createdUser.login} (${createdUser.id})`)
+ throw new HttpException('User not found', HttpStatus.NOT_FOUND)
+ }
+ return freshUser
+ }
+
+ // Check if user information has changed (excluding password)
+ const identityHasChanged: UpdateUserDto = Object.fromEntries(
+ Object.keys(identity)
+ .filter((key) => key !== 'password')
+ .map((key: string) => (identity[key] !== user[key] ? [key, identity[key]] : null))
+ .filter(Boolean)
+ )
+
+ if (Object.keys(identityHasChanged).length > 0) {
+ try {
+ if (identityHasChanged?.role != null) {
+ if (user.role === USER_ROLE.ADMINISTRATOR && !this.oidcConfig.adminRoleOrGroup) {
+ // Prevent removing the admin role when adminGroup was removed or not defined
+ delete identityHasChanged.role
+ }
+ }
+
+ // Update user properties
+ await this.adminUsersManager.updateUserOrGuest(user.id, identityHasChanged)
+
+ // Update local user object
+ Object.assign(user, identityHasChanged)
+
+ if ('lastName' in identityHasChanged || 'firstName' in identityHasChanged) {
+ // Force fullName update in the current user model
+ user.setFullName(true)
+ }
+ } catch (e) {
+ this.logger.warn(`${this.updateOrCreateUser.name} - unable to update user *${user.login}* : ${e}`)
+ }
+ }
+
+ return user
+ }
+
+ private extractLoginAndEmail(userInfo: UserInfoResponse) {
+ const email = userInfo.email ? userInfo.email.trim() : undefined
+ if (!email) {
+ throw new HttpException('No email address found in the OIDC profile', HttpStatus.BAD_REQUEST)
+ }
+
+ const login = userInfo.preferred_username ?? (email ? email.split('@')[0] : undefined) ?? userInfo.sub
+ if (!login) {
+ throw new HttpException('Unable to determine the OIDC profile login', HttpStatus.BAD_REQUEST)
+ }
+
+ return { login: login.trim().toLowerCase(), email }
+ }
+}
diff --git a/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.spec.ts b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
similarity index 97%
rename from backend/src/authentication/services/auth-methods/auth-method-two-fa.service.spec.ts
rename to backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
index 484c680a..2c5c48f2 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.spec.ts
+++ b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
@@ -11,16 +11,16 @@ import { NotificationsManager } from '../../../applications/notifications/servic
import { UserModel } from '../../../applications/users/models/user.model'
import { UsersManager } from '../../../applications/users/services/users-manager.service'
import { Cache } from '../../../infrastructure/cache/services/cache.service'
-import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from '../../dto/two-fa-verify.dto'
import { FastifyAuthenticatedRequest } from '../../interfaces/auth-request.interface'
import { decryptSecret, encryptSecret } from '../../utils/crypt-secret'
-import { AuthMethod2FA } from './auth-method-two-fa.service'
+import { AuthProvider2FA } from './auth-provider-two-fa.service'
+import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './auth-two-fa.dtos'
jest.mock('../../utils/crypt-secret')
jest.mock('../../../common/qrcode')
-describe(AuthMethod2FA.name, () => {
- let service: AuthMethod2FA
+describe(AuthProvider2FA.name, () => {
+ let service: AuthProvider2FA
let cache: jest.Mocked<Cache>
let usersManager: jest.Mocked<UsersManager>
let notificationsManager: jest.Mocked<NotificationsManager>
@@ -44,7 +44,7 @@ describe(AuthMethod2FA.name, () => {
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
- AuthMethod2FA,
+ AuthProvider2FA,
{
provide: Cache,
useValue: {
@@ -72,7 +72,7 @@ describe(AuthMethod2FA.name, () => {
}).compile()
module.useLogger(['fatal'])
- service = module.get<AuthMethod2FA>(AuthMethod2FA)
+ service = module.get<AuthProvider2FA>(AuthProvider2FA)
cache = module.get(Cache)
usersManager = module.get(UsersManager)
notificationsManager = module.get(NotificationsManager)
diff --git a/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
similarity index 97%
rename from backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts
rename to backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
index 3a3a7657..b3568581 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts
+++ b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
@@ -17,14 +17,14 @@ import { qrcodeToDataURL } from '../../../common/qrcode'
import { configuration } from '../../../configuration/config.environment'
import { Cache } from '../../../infrastructure/cache/services/cache.service'
import { TWO_FA_CODE_LENGTH } from '../../constants/auth'
-import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from '../../dto/two-fa-verify.dto'
import { FastifyAuthenticatedRequest } from '../../interfaces/auth-request.interface'
-import { TwoFaEnableResult, TwoFaSetup, TwoFaVerifyResult } from '../../interfaces/two-fa-setup.interface'
import { decryptSecret, encryptSecret } from '../../utils/crypt-secret'
+import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './auth-two-fa.dtos'
+import { TwoFaEnableResult, TwoFaSetup, TwoFaVerifyResult } from './auth-two-fa.interfaces'
@Injectable()
-export class AuthMethod2FA {
- private readonly logger = new Logger(AuthMethod2FA.name)
+export class AuthProvider2FA {
+ private readonly logger = new Logger(AuthProvider2FA.name)
private readonly cacheKeyPrefix = 'auth-2fa-pending-user-'
constructor(
diff --git a/backend/src/authentication/guards/auth-two-fa-guard.ts b/backend/src/authentication/providers/two-fa/auth-two-fa-guard.ts
similarity index 67%
rename from backend/src/authentication/guards/auth-two-fa-guard.ts
rename to backend/src/authentication/providers/two-fa/auth-two-fa-guard.ts
index ca893759..c6ac2d05 100644
--- a/backend/src/authentication/guards/auth-two-fa-guard.ts
+++ b/backend/src/authentication/providers/two-fa/auth-two-fa-guard.ts
@@ -5,10 +5,10 @@
*/
import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, mixin, Type } from '@nestjs/common'
-import { configuration } from '../../configuration/config.environment'
-import { TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from '../constants/auth'
-import { FastifyAuthenticatedRequest } from '../interfaces/auth-request.interface'
-import { AuthMethod2FA } from '../services/auth-methods/auth-method-two-fa.service'
+import { configuration } from '../../../configuration/config.environment'
+import { TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from '../../constants/auth'
+import { FastifyAuthenticatedRequest } from '../../interfaces/auth-request.interface'
+import { AuthProvider2FA } from './auth-provider-two-fa.service'
export const AuthTwoFaGuard = AuthTwoFaGuardFactory()
export const AuthTwoFaGuardWithoutPassword = AuthTwoFaGuardFactory({ withPassword: false })
@@ -20,17 +20,17 @@ interface TwoFaGuardOptions {
function AuthTwoFaGuardFactory(options: TwoFaGuardOptions = { withPassword: true }): Type<CanActivate> {
@Injectable()
class MixinAuthTwoFaGuard implements CanActivate {
- constructor(private readonly authMethod2FA: AuthMethod2FA) {}
+ constructor(private readonly authProvider2FA: AuthProvider2FA) {}
async canActivate(ctx: ExecutionContext): Promise<boolean> {
const req: FastifyAuthenticatedRequest = ctx.switchToHttp().getRequest()
- const user = await this.authMethod2FA.loadUser(req.user.id, req.ip)
+ const user = await this.authProvider2FA.loadUser(req.user.id, req.ip)
if (options.withPassword) {
if (!req.headers[TWO_FA_HEADER_PASSWORD]) {
throw new HttpException('Missing TWO-FA password', HttpStatus.FORBIDDEN)
}
- await this.authMethod2FA.verifyUserPassword(user, req.headers[TWO_FA_HEADER_PASSWORD] as string, req.ip)
+ await this.authProvider2FA.verifyUserPassword(user, req.headers[TWO_FA_HEADER_PASSWORD] as string, req.ip)
}
if (!configuration.auth.mfa.totp.enabled || !user.twoFaEnabled) {
@@ -41,7 +41,7 @@ function AuthTwoFaGuardFactory(options: TwoFaGuardOptions = { withPassword: true
throw new HttpException('Missing TWO-FA code', HttpStatus.FORBIDDEN)
}
- const auth = await this.authMethod2FA.verify({ code: req.headers[TWO_FA_HEADER_CODE] as string }, req)
+ const auth = await this.authProvider2FA.verify({ code: req.headers[TWO_FA_HEADER_CODE] as string }, req)
if (!auth.success) {
throw new HttpException(auth.message, HttpStatus.FORBIDDEN)
diff --git a/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts b/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts
new file mode 100644
index 00000000..8491350f
--- /dev/null
+++ b/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Type } from 'class-transformer'
+import { IsBoolean, IsDefined, IsNotEmptyObject, IsObject, IsString, ValidateNested } from 'class-validator'
+import { SERVER_NAME } from '../../../common/shared'
+
+export class AuthMFATotpConfig {
+ @IsBoolean()
+ enabled = true
+
+ @IsString()
+ issuer = SERVER_NAME
+}
+
+export class AuthMFAConfig {
+ @IsDefined()
+ @IsNotEmptyObject()
+ @IsObject()
+ @ValidateNested()
+ @Type(() => AuthMFATotpConfig)
+ totp: AuthMFATotpConfig = new AuthMFATotpConfig()
+}
diff --git a/backend/src/authentication/dto/two-fa-verify.dto.ts b/backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts
similarity index 76%
rename from backend/src/authentication/dto/two-fa-verify.dto.ts
rename to backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts
index 2e65e45a..33beec39 100644
--- a/backend/src/authentication/dto/two-fa-verify.dto.ts
+++ b/backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts
@@ -5,6 +5,12 @@
*/
import { IsBoolean, IsNotEmpty, IsOptional, IsString } from 'class-validator'
+import { LoginResponseDto } from '../../dto/login-response.dto'
+
+export class TwoFaResponseDto extends LoginResponseDto {
+ success: boolean
+ message: string
+}
export class TwoFaVerifyDto {
@IsString()
diff --git a/backend/src/authentication/interfaces/two-fa-setup.interface.ts b/backend/src/authentication/providers/two-fa/auth-two-fa.interfaces.ts
similarity index 100%
rename from backend/src/authentication/interfaces/two-fa-setup.interface.ts
rename to backend/src/authentication/providers/two-fa/auth-two-fa.interfaces.ts
diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yaml
index 7cf20140..aeff6bac 100755
--- a/environment/environment.dist.yaml
+++ b/environment/environment.dist.yaml
@@ -77,7 +77,7 @@ mail:
# default: `false`
debug: false
auth:
- # adapter : `mysql` | `ldap`
+ # adapter : `mysql` | `ldap` | `oidc`
# default: `mysql`
method: mysql
# Key used to encrypt user secret keys in the database
@@ -135,6 +135,48 @@ auth:
upnSuffix:
# netbiosName: NetBIOS domain name used with `sAMAccountName` to build legacy logins (e.g., `SYNC_IN`\user)
netbiosName:
+ oidc:
+ # issuerUrl: The URL of the OIDC provider's discovery endpoint (e.g., https://accounts.google.com, https://login.microsoftonline.com/tenant-id/v2.0)
+ # The server will automatically discover the authorization, token, userinfo, and logout endpoints
+ # required
+ issuerUrl:
+ # clientId: OAuth 2.0 Client ID obtained from your OIDC provider
+ # required
+ clientId:
+ # clientSecret: OAuth 2.0 Client Secret obtained from your OIDC provider
+ # required
+ clientSecret:
+ # OAuth 2.0 / OIDC client authentication method used at the token endpoint.
+ # Possible values:
+ # - client_secret_basic (DEFAULT): HTTP Basic auth using client_id and client_secret.
+ # Recommended for backend (confidential) clients.
+ # - client_secret_post: client_id and client_secret sent in the request body.
+ # - none: no client authentication (public clients: mobile / SPA with PKCE).
+ # default: `client_secret_basic`
+ # optional
+ clientAuthMethod: client_secret_basic
+ # redirectUri: The callback URL where users are redirected after authentication
+ # This URL must be registered in your OIDC provider's allowed redirect URIs
+ # required
+ redirectUri: http://192.168.0.25:8080/api/auth/oidc/callback
+ # scope: OAuth 2.0 scopes to request (space-separated string)
+ # Common scopes: openid (required), email, profile, groups, roles
+ # default: `openid email profile`
+ scope: openid email profile
+ # autoCreateUser: Automatically create a local user account on first successful OIDC login.
+ # When disabled, only existing users are allowed to authenticate via OIDC.
+ # default: true
+ autoCreateUser: true
+ # skipSubjectCheck: Disable verification that the `sub` claim returned by the UserInfo endpoint
+ # matches the `sub` claim from the ID token.
+ # Set to true only for non-compliant or legacy OIDC providers.
+ # default: false
+ skipSubjectCheck: false
+ # adminRoleOrGroup: Name of the role or group that grants Sync-in administrator access
+ # Users with this value will be granted administrator privileges
+ # The value is matched against the `groups` or `roles` claims returned by the OIDC provider
+ # optional
+ adminRoleOrGroup:
applications:
files:
# required
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.ts b/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.ts
index b3c5e9a3..6b49d589 100644
--- a/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.ts
+++ b/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.ts
@@ -23,7 +23,7 @@ import {
import { USER_LOGIN_VALIDATION, USER_PERMISSION, USER_PERMS_SEP, USER_ROLE } from '@sync-in-server/backend/src/applications/users/constants/user'
import type { CreateUserDto, UpdateUserDto } from '@sync-in-server/backend/src/applications/users/dto/create-or-update-user.dto'
import type { SearchMembersDto } from '@sync-in-server/backend/src/applications/users/dto/search-members.dto'
-import type { TwoFaVerifyResult } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'
+import type { TwoFaVerifyResult } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.interfaces'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { BsModalRef } from 'ngx-bootstrap/modal'
import { TabDirective, TabHeadingDirective, TabsetComponent } from 'ngx-bootstrap/tabs'
diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.ts b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.ts
index 3cb00fb2..30a5198e 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.ts
+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.ts
@@ -9,7 +9,7 @@ import { FormGroup, ReactiveFormsModule, UntypedFormBuilder, Validators } from '
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { faCopy, faKey, faLock } from '@fortawesome/free-solid-svg-icons'
import { TWO_FA_CODE_LENGTH } from '@sync-in-server/backend/src/authentication/constants/auth'
-import { TwoFaEnableResult } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'
+import type { TwoFaEnableResult } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.interfaces'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective } from 'angular-l10n'
import { ClipboardService } from 'ngx-clipboard'
import { InputPasswordComponent } from '../../../../common/components/input-password.component'
diff --git a/frontend/src/app/applications/users/components/user-account.component.ts b/frontend/src/app/applications/users/components/user-account.component.ts
index 99eb6bb2..329a7896 100644
--- a/frontend/src/app/applications/users/components/user-account.component.ts
+++ b/frontend/src/app/applications/users/components/user-account.component.ts
@@ -16,7 +16,7 @@ import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applicatio
import { UserAppPassword } from '@sync-in-server/backend/src/applications/users/interfaces/user-secrets.interface'
import { WEBDAV_BASE_PATH } from '@sync-in-server/backend/src/applications/webdav/constants/routes'
import { TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from '@sync-in-server/backend/src/authentication/constants/auth'
-import { TwoFaSetup } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'
+import type { TwoFaSetup } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.interfaces'
import type { FileEditorProvider } from '@sync-in-server/backend/src/configuration/config.interfaces'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { BsModalRef } from 'ngx-bootstrap/modal'
diff --git a/frontend/src/app/applications/users/user.service.ts b/frontend/src/app/applications/users/user.service.ts
index b08616d2..66fc0d7c 100644
--- a/frontend/src/app/applications/users/user.service.ts
+++ b/frontend/src/app/applications/users/user.service.ts
@@ -50,8 +50,12 @@ import type {
UserOnline
} from '@sync-in-server/backend/src/applications/users/interfaces/websocket.interface'
import { API_TWO_FA_ADMIN_RESET_USER, API_TWO_FA_DISABLE, API_TWO_FA_ENABLE } from '@sync-in-server/backend/src/authentication/constants/routes'
-import type { TwoFaVerifyWithPasswordDto } from '@sync-in-server/backend/src/authentication/dto/two-fa-verify.dto'
-import type { TwoFaEnableResult, TwoFaSetup, TwoFaVerifyResult } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'
+import type { TwoFaVerifyWithPasswordDto } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.dtos'
+import type {
+ TwoFaEnableResult,
+ TwoFaSetup,
+ TwoFaVerifyResult
+} from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.interfaces'
import type { FileEditorProvider } from '@sync-in-server/backend/src/configuration/config.interfaces'
import { BsModalRef } from 'ngx-bootstrap/modal'
import { Socket } from 'ngx-socket-io'
diff --git a/frontend/src/app/auth/auth.component.ts b/frontend/src/app/auth/auth.component.ts
index 5e2dfde6..6ce5276c 100644
--- a/frontend/src/app/auth/auth.component.ts
+++ b/frontend/src/app/auth/auth.component.ts
@@ -11,8 +11,7 @@ import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { faKey, faLock, faQrcode, faUserAlt } from '@fortawesome/free-solid-svg-icons'
import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'
import { TWO_FA_CODE_LENGTH } from '@sync-in-server/backend/src/authentication/constants/auth'
-import { TwoFaResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'
-import { TwoFaVerifyDto } from '@sync-in-server/backend/src/authentication/dto/two-fa-verify.dto'
+import type { TwoFaResponseDto, TwoFaVerifyDto } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.dtos'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { finalize } from 'rxjs/operators'
import { logoDarkUrl } from '../applications/files/files.constants'
diff --git a/frontend/src/app/auth/auth.guards.ts b/frontend/src/app/auth/auth.guards.ts
index 38827d36..a1f07d5f 100644
--- a/frontend/src/app/auth/auth.guards.ts
+++ b/frontend/src/app/auth/auth.guards.ts
@@ -7,10 +7,13 @@
import { inject } from '@angular/core'
import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot } from '@angular/router'
import { Observable } from 'rxjs'
+import { AuthOIDCQueryParams } from './auth.interface'
import { AuthService } from './auth.service'
-export const authGuard: CanActivateFn = (_route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> => {
- return inject(AuthService).checkUserAuthAndLoad(state.url)
+export const authGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> => {
+ // Authentication initiated via OIDC callback
+ const authFromOIDC = route.queryParams?.oidc ? (route.queryParams as AuthOIDCQueryParams) : undefined
+ return inject(AuthService).checkUserAuthAndLoad(state.url, authFromOIDC)
}
export const noAuthGuard: CanActivateFn = (): boolean => {
diff --git a/frontend/src/app/auth/auth.interface.ts b/frontend/src/app/auth/auth.interface.ts
new file mode 100644
index 00000000..add99280
--- /dev/null
+++ b/frontend/src/app/auth/auth.interface.ts
@@ -0,0 +1,11 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+export interface AuthOIDCQueryParams {
+ oidc: string
+ access_expiration: string
+ refresh_expiration: string
+}
diff --git a/frontend/src/app/auth/auth.service.ts b/frontend/src/app/auth/auth.service.ts
index a60646e8..5c70a8d0 100644
--- a/frontend/src/app/auth/auth.service.ts
+++ b/frontend/src/app/auth/auth.service.ts
@@ -19,9 +19,9 @@ import {
API_AUTH_REFRESH,
API_TWO_FA_LOGIN_VERIFY
} from '@sync-in-server/backend/src/authentication/constants/routes'
-import { LoginResponseDto, TwoFaResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'
+import type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'
import type { TokenResponseDto } from '@sync-in-server/backend/src/authentication/dto/token-response.dto'
-import { TwoFaVerifyDto } from '@sync-in-server/backend/src/authentication/dto/two-fa-verify.dto'
+import type { TwoFaResponseDto, TwoFaVerifyDto } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.dtos'
import { currentTimeStamp } from '@sync-in-server/backend/src/common/shared'
import { catchError, finalize, map, Observable, of, throwError } from 'rxjs'
import { switchMap, tap } from 'rxjs/operators'
@@ -33,6 +33,7 @@ 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'
@Injectable({
providedIn: 'root'
@@ -187,7 +188,11 @@ export class AuthService {
)
}
- checkUserAuthAndLoad(returnUrl: string): Observable<boolean> {
+ checkUserAuthAndLoad(returnUrl: string, authFromOIDC?: AuthOIDCQueryParams): Observable<boolean> {
+ if (authFromOIDC) {
+ this.accessExpiration = parseInt(authFromOIDC.access_expiration)
+ this.refreshExpiration = parseInt(authFromOIDC.refresh_expiration)
+ }
if (this.refreshTokenHasExpired()) {
if (this.electron.enabled) {
return this.loginElectron()
@@ -197,7 +202,12 @@ export class AuthService {
return of(false)
} else if (!this.store.user.getValue()) {
return this.http.get<Omit<LoginResponseDto, 'token'>>(API_USERS_ME).pipe(
- tap((r: Omit<LoginResponseDto, 'token'>) => this.initUser(r)),
+ tap((r: Omit<LoginResponseDto, 'token'>) => {
+ this.initUser(r)
+ if (authFromOIDC) {
+ this.router.navigate([]).catch(console.error)
+ }
+ }),
map(() => true),
catchError((e: HttpErrorResponse) => {
if (e.status === 401) {