Skip to content

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

refactor(mfa): unify password and TOTP verification flow with conditional guards

johavene4245c6b12b3
diff --git a/backend/src/applications/users/admin-users.controller.ts b/backend/src/applications/users/admin-users.controller.ts
index 5da60216..b38afa76 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 } from '../../authentication/guards/auth-two-fa-guard'
+import { AuthTwoFaGuard, AuthTwoFaGuardWithoutPassword } from '../../authentication/guards/auth-two-fa-guard'
import { GROUP_TYPE } from './constants/group'
import { ADMIN_USERS_ROUTE } from './constants/routes'
import { USER_ROLE } from './constants/user'
@@ -15,9 +15,8 @@ import { UserHaveRole } from './decorators/roles.decorator'
import { GetUser } from './decorators/user.decorator'
import { CreateOrUpdateGroupDto } from './dto/create-or-update-group.dto'
import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from './dto/create-or-update-user.dto'
-import { AdminDeleteUserDto } from './dto/delete-user.dto'
+import { DeleteUserDto } from './dto/delete-user.dto'
import { SearchMembersDto } from './dto/search-members.dto'
-import { UserPasswordDto } from './dto/user-properties.dto'
import { UserRolesGuard } from './guards/roles.guard'
import { AdminGroup } from './interfaces/admin-group.interface'
import { AdminUser } from './interfaces/admin-user.interface'
@@ -44,6 +43,7 @@ export class AdminUsersController {
}
@Post(ADMIN_USERS_ROUTE.USERS)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
createUser(@Body() createUserDto: CreateUserDto): Promise<AdminUser> {
return this.adminUsersManager.createUserOrGuest(
createUserDto,
@@ -53,14 +53,15 @@ export class AdminUsersController {
}
@Put(`${ADMIN_USERS_ROUTE.USERS}/:id`)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
updateUser(@Param('id', ParseIntPipe) userId: number, @Body() updateUserDto: UpdateUserDto): Promise<AdminUser> {
return this.adminUsersManager.updateUserOrGuest(userId, updateUserDto)
}
@Delete(`${ADMIN_USERS_ROUTE.USERS}/:id`)
@UseGuards(AuthTwoFaGuard)
- deleteUser(@GetUser() admin: UserModel, @Param('id', ParseIntPipe) userId: number, @Body() adminDeleteUserDto: AdminDeleteUserDto): Promise<void> {
- return this.adminUsersManager.deleteUserFromAdmin(admin, userId, adminDeleteUserDto)
+ deleteUser(@Param('id', ParseIntPipe) userId: number, @Body() deleteUserDto: DeleteUserDto): Promise<void> {
+ return this.adminUsersManager.deleteUserOrGuestFromAdmin(userId, { ...deleteUserDto, isGuest: false })
}
@Get(`${ADMIN_USERS_ROUTE.GUESTS}/${ADMIN_USERS_ROUTE.LIST}`)
@@ -74,18 +75,21 @@ export class AdminUsersController {
}
@Post(ADMIN_USERS_ROUTE.GUESTS)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
createGuest(@GetUser() user: UserModel, @Body() createGuestDto: CreateUserDto): Promise<GuestUser> {
return this.adminUsersManager.createGuest(user, createGuestDto)
}
@Put(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
updateGuest(@Param('id', ParseIntPipe) guestId: number, @Body() updateGuestDto: UpdateUserDto): Promise<GuestUser> {
return this.adminUsersManager.updateGuest(guestId, updateGuestDto)
}
@Delete(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)
- deleteGuest(@Param('id', ParseIntPipe) guestId: number): Promise<void> {
- return this.adminUsersManager.deleteGuest(guestId)
+ @UseGuards(AuthTwoFaGuard)
+ deleteGuest(@Param('id', ParseIntPipe) guestId: number, @Body() deleteUserDto: DeleteUserDto): Promise<void> {
+ return this.adminUsersManager.deleteUserOrGuestFromAdmin(guestId, { ...deleteUserDto, isGuest: true })
}
@Search(ADMIN_USERS_ROUTE.MEMBERS)
@@ -147,10 +151,9 @@ export class AdminUsersController {
impersonateUser(
@GetUser() admin: UserModel,
@Param('id', ParseIntPipe) userId: number,
- @Body() adminPasswordDto: UserPasswordDto,
@Res({ passthrough: true }) res: FastifyReply
): Promise<LoginResponseDto> {
- return this.adminUsersManager.impersonateUser(admin, userId, adminPasswordDto, res)
+ return this.adminUsersManager.impersonateUser(admin, userId, res)
}
@Post(`${ADMIN_USERS_ROUTE.IMPERSONATE}/${ADMIN_USERS_ROUTE.LOGOUT}`)
diff --git a/backend/src/applications/users/dto/delete-user.dto.ts b/backend/src/applications/users/dto/delete-user.dto.ts
index 126dea96..d8d87b7b 100644
--- a/backend/src/applications/users/dto/delete-user.dto.ts
+++ b/backend/src/applications/users/dto/delete-user.dto.ts
@@ -4,19 +4,12 @@
* See the LICENSE file for licensing details
*/
-import { IsBoolean, IsNotEmpty, IsOptional, IsString } from 'class-validator'
+import { IsBoolean } from 'class-validator'
export class DeleteUserDto {
@IsBoolean()
deleteSpace: boolean
- @IsOptional()
@IsBoolean()
- isGuest? = false
-}
-
-export class AdminDeleteUserDto extends DeleteUserDto {
- @IsNotEmpty()
- @IsString()
- adminPassword: string
+ isGuest: boolean
}
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 5686f279..bf24d464 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
@@ -10,10 +10,9 @@ import { AuthManager } from '../../../authentication/services/auth-manager.servi
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'
-import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'
-import type { AdminDeleteUserDto } from '../dto/delete-user.dto'
+import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'
+import type { DeleteUserDto } from '../dto/delete-user.dto'
import type { SearchMembersDto } from '../dto/search-members.dto'
-import type { UserPasswordDto } from '../dto/user-properties.dto'
import { UserModel } from '../models/user.model'
import { AdminUsersManager } from './admin-users-manager.service'
import { AdminUsersQueries } from './admin-users-queries.service'
@@ -324,26 +323,17 @@ describe(AdminUsersManager.name, () => {
adminQueriesMock.deleteUser.mockRejectedValueOnce(new Error('db crash'))
await expectHttp(service.deleteUserOrGuest(10, 'john', { deleteSpace: false } as any))
})
-
- it('deleteGuest -> getGuest then delete', async () => {
- setGuest({ id: 77, login: 'g77' } as any)
- adminQueriesMock.deleteUser.mockResolvedValueOnce(true)
- fs.isPathExists.mockResolvedValueOnce(false)
- await expect(service.deleteGuest(77)).resolves.toBeUndefined()
- expect(adminQueriesMock.deleteUser).toHaveBeenCalledWith(77, 'g77')
- })
})
describe('deleteUserFromAdmin', () => {
it('admin password incorrect / deletion ok', async () => {
- const admin = new UserModel({ id: 1 } as any, true)
adminQueriesMock.usersQueries.compareUserPassword.mockResolvedValueOnce(false)
- await expectHttp(service.deleteUserFromAdmin(admin, 10, { adminPassword: 'bad' } as AdminDeleteUserDto))
+ await expectHttp(service.deleteUserOrGuestFromAdmin(10, { isGuest: false } as DeleteUserDto))
adminQueriesMock.usersQueries.compareUserPassword.mockResolvedValueOnce(true)
adminQueriesMock.usersQueries.from.mockResolvedValueOnce({ id: 10, login: 'to-del' } as any)
adminQueriesMock.deleteUser.mockResolvedValueOnce(true)
- await service.deleteUserFromAdmin(admin, 10, { adminPassword: 'ok', deleteSpace: true } as any)
+ await service.deleteUserOrGuestFromAdmin(10, { isGuest: false, deleteSpace: true } as DeleteUserDto)
expect(adminQueriesMock.deleteUser).toHaveBeenCalledWith(10, 'to-del')
})
})
@@ -438,16 +428,16 @@ describe(AdminUsersManager.name, () => {
const res: any = {}
it('self / bad password / ok + logout (guard + non-admin + admin)', async () => {
const admin = new UserModel({ id: 5 } as any, true)
- await expectHttp(service.impersonateUser(admin, 5, { password: 'x' } as UserPasswordDto, res))
+ await expectHttp(service.impersonateUser(admin, 5, res))
adminQueriesMock.usersQueries.compareUserPassword.mockResolvedValueOnce(false)
- await expectHttp(service.impersonateUser(admin, 6, { password: 'bad' } as any, res))
+ await expectHttp(service.impersonateUser(admin, 6, res))
const admin2 = new UserModel({ id: 5, clientId: 'c1' } as any, true)
adminQueriesMock.usersQueries.compareUserPassword.mockResolvedValueOnce(true)
adminQueriesMock.usersQueries.from.mockResolvedValueOnce({ id: 6, login: 'user' } as any)
authManagerMock.setCookies.mockResolvedValueOnce({ accessToken: 't' })
- expect(await service.impersonateUser(admin2, 6, { password: 'ok' } as any, res)).toEqual({ accessToken: 't' })
+ expect(await service.impersonateUser(admin2, 6, res)).toEqual({ accessToken: 't' })
const notImpersonated = new UserModel({ id: 1 } as any, true)
await expectHttp(service.logoutImpersonateUser(notImpersonated, res))
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 c3239b0e..27a5dcec 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.ts
@@ -13,10 +13,9 @@ import { isPathExists, moveFiles, removeFiles } from '../../files/utils/files'
import { GROUP_TYPE } from '../constants/group'
import { USER_ROLE } from '../constants/user'
import type { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'
-import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'
-import type { AdminDeleteUserDto, DeleteUserDto } from '../dto/delete-user.dto'
+import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'
+import type { DeleteUserDto } from '../dto/delete-user.dto'
import type { SearchMembersDto } from '../dto/search-members.dto'
-import type { UserPasswordDto } from '../dto/user-properties.dto'
import type { AdminGroup } from '../interfaces/admin-group.interface'
import type { AdminUser } from '../interfaces/admin-user.interface'
import type { GroupBrowse } from '../interfaces/group-browse.interface'
@@ -185,14 +184,14 @@ export class AdminUsersManager {
}
}
- async deleteUserFromAdmin(admin: UserModel, userId: number, adminDeleteUserDto: AdminDeleteUserDto): Promise<void> {
- // check admin password
- if (!(await this.adminQueries.usersQueries.compareUserPassword(admin.id, adminDeleteUserDto.adminPassword))) {
- throw new HttpException('Bad password', HttpStatus.BAD_REQUEST)
- }
+ async deleteUserOrGuestFromAdmin(userId: number, deleteUserDto: DeleteUserDto): Promise<void> {
const userToDelete: UserModel = this.checkUser(await this.adminQueries.usersQueries.from(userId))
+ if (userToDelete.isGuest !== deleteUserDto.isGuest) {
+ throw new HttpException('User mismatch', HttpStatus.BAD_REQUEST)
+ }
await this.deleteUserOrGuest(userToDelete.id, userToDelete.login, {
- deleteSpace: adminDeleteUserDto.deleteSpace
+ deleteSpace: deleteUserDto.isGuest ? true : deleteUserDto.deleteSpace,
+ isGuest: deleteUserDto.isGuest
} satisfies DeleteUserDto)
}
@@ -217,12 +216,6 @@ export class AdminUsersManager {
return this.updateUserOrGuest(guestId, updateGuestDto, USER_ROLE.GUEST)
}
- async deleteGuest(guestId: number): Promise<void> {
- // guest has no space but a temporary directory
- const guest: GuestUser = await this.getGuest(guestId)
- return this.deleteUserOrGuest(guest.id, guest.login, { deleteSpace: true, isGuest: true })
- }
-
async browseGroups(name?: string, type: GROUP_TYPE = GROUP_TYPE.USER): Promise<GroupBrowse> {
if (name) {
const group: Pick<Group, 'id' | 'name' | 'type'> = await this.adminQueries.groupFromName(name)
@@ -309,14 +302,10 @@ export class AdminUsersManager {
return this.adminQueries.usersQueries.searchUsersOrGroups(searchMembersDto)
}
- async impersonateUser(admin: UserModel, userId: number, adminPassword: UserPasswordDto, res: FastifyReply): Promise<LoginResponseDto> {
- // check admin password
+ async impersonateUser(admin: UserModel, userId: number, res: FastifyReply): Promise<LoginResponseDto> {
if (admin.id === userId) {
throw new HttpException('You are already logged in', HttpStatus.BAD_REQUEST)
}
- if (!(await this.adminQueries.usersQueries.compareUserPassword(admin.id, adminPassword.password))) {
- throw new HttpException('Bad password', HttpStatus.BAD_REQUEST)
- }
const user: UserModel = this.checkUser(await this.adminQueries.usersQueries.from(userId))
user.impersonatedFromId = admin.id
user.impersonatedClientId = admin.clientId
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 a1129fc4..856f114f 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -93,7 +93,7 @@ describe(UsersManager.name, () => {
adminUsersQueries = module.get(AdminUsersQueries)
usersQueriesService = module.get(UsersQueries)
userTest = new UserModel(generateUserTest(), false)
- deleteUserDto = { deleteSpace: true } satisfies DeleteUserDto
+ deleteUserDto = { deleteSpace: true, isGuest: false } satisfies DeleteUserDto
})
afterEach(() => jest.restoreAllMocks())
diff --git a/backend/src/applications/users/users.controller.ts b/backend/src/applications/users/users.controller.ts
index d4019c9b..19c60f49 100755
--- a/backend/src/applications/users/users.controller.ts
+++ b/backend/src/applications/users/users.controller.ts
@@ -7,7 +7,7 @@
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 { AuthTwoFaGuard } from '../../authentication/guards/auth-two-fa-guard'
+import { AuthTwoFaGuardWithoutPassword } from '../../authentication/guards/auth-two-fa-guard'
import { FastifyAuthenticatedRequest } from '../../authentication/interfaces/auth-request.interface'
import { USERS_ROUTE } from './constants/routes'
import { USER_PERMISSION, USER_ROLE } from './constants/user'
@@ -42,12 +42,14 @@ export class UsersController {
@Get(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)
@UserHaveRole(USER_ROLE.USER)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
listAppPasswords(@GetUser() user: UserModel): Promise<Omit<UserAppPassword, 'password'>[]> {
return this.usersManager.listAppPasswords(user)
}
@Post(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)
@UserHaveRole(USER_ROLE.USER)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
generateAppPassword(@GetUser() user: UserModel, @Body() userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {
return this.usersManager.generateAppPassword(user, userAppPasswordDto)
}
@@ -65,7 +67,7 @@ export class UsersController {
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.PASSWORD}`)
- @UseGuards(AuthTwoFaGuard)
+ @UseGuards(AuthTwoFaGuardWithoutPassword)
updatePassword(@GetUser() user: UserModel, @Body() userPasswordDto: UserUpdatePasswordDto) {
return this.usersManager.updatePassword(user, userPasswordDto)
}
diff --git a/backend/src/applications/users/users.e2e-spec.ts b/backend/src/applications/users/users.e2e-spec.ts
index 792d5994..dde16ca2 100644
--- a/backend/src/applications/users/users.e2e-spec.ts
+++ b/backend/src/applications/users/users.e2e-spec.ts
@@ -34,7 +34,7 @@ describe('Users (e2e)', () => {
afterAll(async () => {
await expect(
- adminUsersManager.deleteUserOrGuest(userTest.id, userTest.login, { deleteSpace: true } satisfies DeleteUserDto)
+ adminUsersManager.deleteUserOrGuest(userTest.id, userTest.login, { deleteSpace: true, isGuest: false } satisfies DeleteUserDto)
).resolves.not.toThrow()
await dbCloseConnection(app)
await app.close()
diff --git a/backend/src/authentication/auth.controller.ts b/backend/src/authentication/auth.controller.ts
index ec0b0447..98d8e8e7 100755
--- a/backend/src/authentication/auth.controller.ts
+++ b/backend/src/authentication/auth.controller.ts
@@ -9,8 +9,6 @@ import { FastifyReply } from 'fastify'
import { USER_ROLE } from '../applications/users/constants/user'
import { UserHaveRole } from '../applications/users/decorators/roles.decorator'
import { GetUser } from '../applications/users/decorators/user.decorator'
-
-import { UserPasswordDto } from '../applications/users/dto/user-properties.dto'
import { UserRolesGuard } from '../applications/users/guards/roles.guard'
import { UserModel } from '../applications/users/models/user.model'
import { ACCESS_KEY, TOKEN_PATHS } from './constants/auth'
@@ -110,21 +108,10 @@ export class AuthController {
return authStatus
}
- @Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_VERIFY}`)
- @UseGuards(UserRolesGuard)
- @UserHaveRole(USER_ROLE.USER)
- twoFaVerify(@Body() body: TwoFaVerifyDto, @Req() req: FastifyAuthenticatedRequest): Promise<TwoFaVerifyResult> {
- return this.authMethod2FA.verify(body, req)
- }
-
@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ADMIN_RESET_USER}/:id`)
@UseGuards(UserRolesGuard, AuthTwoFaGuard)
@UserHaveRole(USER_ROLE.ADMINISTRATOR)
- twoFaReset(
- @GetUser() admin: UserModel,
- @Param('id', ParseIntPipe) userId: number,
- @Body() adminPassword: UserPasswordDto
- ): Promise<TwoFaVerifyResult> {
- return this.authMethod2FA.adminResetUserTwoFa(admin.id, userId, adminPassword)
+ twoFaReset(@Param('id', ParseIntPipe) userId: number): Promise<TwoFaVerifyResult> {
+ return this.authMethod2FA.adminResetUserTwoFa(userId)
}
}
diff --git a/backend/src/authentication/auth.e2e-spec.ts b/backend/src/authentication/auth.e2e-spec.ts
index 72eb01b2..5163d523 100644
--- a/backend/src/authentication/auth.e2e-spec.ts
+++ b/backend/src/authentication/auth.e2e-spec.ts
@@ -44,7 +44,7 @@ describe('Auth (e2e)', () => {
afterAll(async () => {
await expect(
- adminUsersManager.deleteUserOrGuest(userTest.id, userTest.login, { deleteSpace: true } satisfies DeleteUserDto)
+ adminUsersManager.deleteUserOrGuest(userTest.id, userTest.login, { deleteSpace: true, isGuest: false } satisfies DeleteUserDto)
).resolves.not.toThrow()
await dbCloseConnection(app)
await app.close()
diff --git a/backend/src/authentication/auth.module.ts b/backend/src/authentication/auth.module.ts
index 25adae1f..d1afc9a7 100755
--- a/backend/src/authentication/auth.module.ts
+++ b/backend/src/authentication/auth.module.ts
@@ -21,7 +21,6 @@ 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 { AuthTwoFaGuard } from './guards/auth-two-fa-guard'
import { AuthMethod } from './models/auth-method'
import { AuthManager } from './services/auth-manager.service'
import { AuthMethodDatabase } from './services/auth-methods/auth-method-database.service'
@@ -48,9 +47,8 @@ import { AuthMethod2FA } from './services/auth-methods/auth-method-two-fa.servic
AuthAnonymousStrategy,
AuthManager,
AuthMethod2FA,
- AuthTwoFaGuard,
{ provide: AuthMethod, useClass: configuration.auth.method === 'ldap' ? AuthMethodLdapService : AuthMethodDatabase }
],
- exports: [AuthManager, AuthMethod, AuthMethod2FA, AuthTwoFaGuard]
+ exports: [AuthManager, AuthMethod, AuthMethod2FA]
})
export class AuthModule {}
diff --git a/backend/src/authentication/constants/auth.ts b/backend/src/authentication/constants/auth.ts
index 7a7f3306..93055652 100644
--- a/backend/src/authentication/constants/auth.ts
+++ b/backend/src/authentication/constants/auth.ts
@@ -14,7 +14,8 @@ export const WS_KEY = 'sync-in-ws'
export const TWO_FA_CODE_LENGTH = 6
export const TWO_FA_VERIFY_EXPIRATION = '5m'
-export const TWO_FA_HEADER = 'sync-in-two-fa-code'
+export const TWO_FA_HEADER_CODE = 'sync-in-two-fa-code'
+export const TWO_FA_HEADER_PASSWORD = 'sync-in-two-fa-password'
export const TOKEN_PATHS = {
[TOKEN_TYPE.ACCESS]: '/',
diff --git a/backend/src/authentication/constants/routes.ts b/backend/src/authentication/constants/routes.ts
index 7ad24e6a..f5e6efe2 100644
--- a/backend/src/authentication/constants/routes.ts
+++ b/backend/src/authentication/constants/routes.ts
@@ -15,7 +15,6 @@ export enum AUTH_ROUTE {
TWO_FA_BASE = '2fa',
TWO_FA_ENABLE = 'enable',
TWO_FA_DISABLE = 'disable',
- TWO_FA_VERIFY = 'verify',
TWO_FA_LOGIN_VERIFY = 'login/verify',
TWO_FA_ADMIN_RESET_USER = 'reset/user'
}
@@ -28,6 +27,5 @@ export const API_AUTH_TOKEN_REFRESH = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TOKEN_REF
export const API_AUTH_WS = `/${AUTH_ROUTE.WS}`
export const API_TWO_FA_ENABLE = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ENABLE}`
export const API_TWO_FA_DISABLE = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_DISABLE}`
-export const API_TWO_FA_VERIFY = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_VERIFY}`
export const API_TWO_FA_LOGIN_VERIFY = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_LOGIN_VERIFY}`
export const API_TWO_FA_ADMIN_RESET_USER = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ADMIN_RESET_USER}`
diff --git a/backend/src/authentication/guards/auth-two-fa-guard.ts b/backend/src/authentication/guards/auth-two-fa-guard.ts
index 9e38f92a..6071e6f6 100644
--- a/backend/src/authentication/guards/auth-two-fa-guard.ts
+++ b/backend/src/authentication/guards/auth-two-fa-guard.ts
@@ -4,31 +4,53 @@
* See the LICENSE file for licensing details
*/
-import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable } from '@nestjs/common'
+import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, mixin, Type } from '@nestjs/common'
import { configuration } from '../../configuration/config.environment'
-import { TWO_FA_HEADER } from '../constants/auth'
+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'
-@Injectable()
-export class AuthTwoFaGuard implements CanActivate {
- constructor(private readonly authMethod2FA: AuthMethod2FA) {}
+export const AuthTwoFaGuard = AuthTwoFaGuardFactory()
+export const AuthTwoFaGuardWithoutPassword = AuthTwoFaGuardFactory({ withPassword: false })
+
+interface TwoFaGuardOptions {
+ withPassword?: boolean
+}
+
+function AuthTwoFaGuardFactory(options: TwoFaGuardOptions = { withPassword: true }): Type<CanActivate> {
+ @Injectable()
+ class MixinAuthTwoFaGuard implements CanActivate {
+ constructor(private readonly authMethod2FA: AuthMethod2FA) {}
+
+ async canActivate(ctx: ExecutionContext): Promise<boolean> {
+ const req: FastifyAuthenticatedRequest = ctx.switchToHttp().getRequest()
+ const user = await this.authMethod2FA.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)
+ }
+
+ if (!configuration.auth.mfa.totp.enabled || !user.twoFaEnabled) {
+ return true
+ }
+
+ if (!req.headers[TWO_FA_HEADER_CODE]) {
+ 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)
+
+ if (!auth.success) {
+ throw new HttpException(auth.message, HttpStatus.FORBIDDEN)
+ }
- async canActivate(ctx: ExecutionContext): Promise<boolean> {
- if (!configuration.auth.mfa.totp.enabled) {
- return true
- }
- const req: FastifyAuthenticatedRequest = ctx.switchToHttp().getRequest()
- if (!req.user.twoFaEnabled) {
return true
}
- if (!req.headers[TWO_FA_HEADER]) {
- throw new HttpException('Missing TWO-FA in headers', HttpStatus.FORBIDDEN)
- }
- const auth = await this.authMethod2FA.verify({ code: req.headers[TWO_FA_HEADER] as string }, req)
- if (!auth.success) {
- throw new HttpException(auth.message, HttpStatus.FORBIDDEN)
- }
- return auth.success
}
+
+ return mixin(MixinAuthTwoFaGuard)
}
diff --git a/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts b/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts
index f6039010..cca5a632 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts
+++ b/backend/src/authentication/services/auth-methods/auth-method-two-fa.service.ts
@@ -9,7 +9,6 @@ import { Totp } from 'time2fa'
import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../../applications/notifications/constants/notifications'
import { NotificationContent } from '../../../applications/notifications/interfaces/notification-properties.interface'
import { NotificationsManager } from '../../../applications/notifications/services/notifications-manager.service'
-import { UserPasswordDto } from '../../../applications/users/dto/user-properties.dto'
import { UserModel } from '../../../applications/users/models/user.model'
import { UsersManager } from '../../../applications/users/services/users-manager.service'
import { ACTION } from '../../../common/constants'
@@ -96,19 +95,20 @@ export class AuthMethod2FA {
return fromLogin ? [auth, user] : auth
}
- async adminResetUserTwoFa(adminId: number, userId: number, adminPassword: UserPasswordDto) {
- // check admin password
+ async adminResetUserTwoFa(userId: number) {
const auth: TwoFaVerifyResult = { success: false, message: '' }
- if (!(await this.usersManager.usersQueries.compareUserPassword(adminId, adminPassword.password))) {
- auth.message = 'Bad password'
- return auth
+ try {
+ await this.usersManager.updateSecrets(userId, { twoFaSecret: undefined, recoveryCodes: undefined })
+ auth.success = true
+ } catch (e) {
+ auth.success = false
+ auth.message = e.message
+ this.logger.error(`${this.adminResetUserTwoFa.name} - ${e}`)
}
- await this.usersManager.updateSecrets(userId, { twoFaSecret: undefined, recoveryCodes: undefined })
- auth.success = true
return auth
}
- private async loadUser(userId: number, ip: string) {
+ async loadUser(userId: number, ip: string) {
const user: UserModel = await this.usersManager.fromUserId(userId)
if (!user) {
this.logger.warn(`User *${user.login}* (${user.id}) not found`)
@@ -118,7 +118,7 @@ export class AuthMethod2FA {
return user
}
- private async verifyUserPassword(user: UserModel, password: string, ip: string) {
+ async verifyUserPassword(user: UserModel, password: string, ip: string) {
if (!(await this.usersManager.compareUserPassword(user.id, password))) {
this.usersManager.updateAccesses(user, ip, false, true).catch((e: Error) => this.logger.error(`${this.enableTwoFactor.name} - ${e}`))
throw new HttpException('Incorrect code or password', HttpStatus.BAD_REQUEST)
diff --git a/frontend/src/app/applications/admin/admin.service.ts b/frontend/src/app/applications/admin/admin.service.ts
index b57429df..65074c8e 100644
--- a/frontend/src/app/applications/admin/admin.service.ts
+++ b/frontend/src/app/applications/admin/admin.service.ts
@@ -25,15 +25,13 @@ import type {
UpdateUserDto,
UpdateUserFromGroupDto
} from '@sync-in-server/backend/src/applications/users/dto/create-or-update-user.dto'
-import type { AdminDeleteUserDto } from '@sync-in-server/backend/src/applications/users/dto/delete-user.dto'
+import type { DeleteUserDto } from '@sync-in-server/backend/src/applications/users/dto/delete-user.dto'
import type { SearchMembersDto } from '@sync-in-server/backend/src/applications/users/dto/search-members.dto'
-import type { UserPasswordDto } from '@sync-in-server/backend/src/applications/users/dto/user-properties.dto'
import type { AdminGroup } from '@sync-in-server/backend/src/applications/users/interfaces/admin-group.interface'
import type { AdminUser } from '@sync-in-server/backend/src/applications/users/interfaces/admin-user.interface'
import type { GroupBrowse } from '@sync-in-server/backend/src/applications/users/interfaces/group-browse.interface'
import type { GuestUser } from '@sync-in-server/backend/src/applications/users/interfaces/guest-user.interface'
import type { Member } from '@sync-in-server/backend/src/applications/users/interfaces/member.interface'
-import { TWO_FA_HEADER } from '@sync-in-server/backend/src/authentication/constants/auth'
import type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'
import { catchError, map, Observable } from 'rxjs'
import { AuthService } from '../../auth/auth.service'
@@ -66,31 +64,27 @@ export class AdminService {
.pipe(map((u) => (isGuest ? new GuestUserModel(u) : new AdminUserModel(u))))
}
- createUser(createUserDto: CreateUserDto, isGuest?: false): Observable<AdminUserModel>
- createUser(createUserDto: CreateUserDto, isGuest: true): Observable<GuestUserModel>
- createUser(createUserDto: CreateUserDto, isGuest = false): Observable<AdminUserModel | GuestUserModel> {
+ createUser(createUserDto: CreateUserDto, twoFaHeaders: HttpHeaders, isGuest?: false): Observable<AdminUserModel>
+ createUser(createUserDto: CreateUserDto, twoFaHeaders: HttpHeaders, isGuest: true): Observable<GuestUserModel>
+ createUser(createUserDto: CreateUserDto, twoFaHeaders: HttpHeaders, isGuest = false): Observable<AdminUserModel | GuestUserModel> {
return this.http
- .post<AdminUser | GuestUser>(isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS, createUserDto)
+ .post<AdminUser | GuestUser>(isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS, createUserDto, { headers: twoFaHeaders })
.pipe(map((u) => (isGuest ? new GuestUserModel(u) : new AdminUserModel(u))))
}
- updateUser(userId: number, updateUserDto: UpdateUserDto, isGuest?: false): Observable<AdminUserModel>
- updateUser(userId: number, updateUserDto: UpdateUserDto, isGuest: true): Observable<GuestUserModel>
- updateUser(userId: number, updateUserDto: UpdateUserDto, isGuest = false): Observable<AdminUserModel | GuestUserModel> {
+ updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: HttpHeaders, isGuest?: false): Observable<AdminUserModel>
+ updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: HttpHeaders, isGuest: true): Observable<GuestUserModel>
+ updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: HttpHeaders, isGuest = false): Observable<AdminUserModel | GuestUserModel> {
return this.http
- .put<AdminUser | GuestUser>(`${isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS}/${userId}`, updateUserDto)
+ .put<AdminUser | GuestUser>(`${isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS}/${userId}`, updateUserDto, { headers: twoFaHeaders })
.pipe(map((u) => (isGuest ? new GuestUserModel(u) : new AdminUserModel(u))))
}
- deleteUser(userId: number, adminDeleteUserDto?: AdminDeleteUserDto, isGuest = false, totpCode?: string): Observable<void> {
- if (isGuest) {
- return this.http.delete<void>(`${API_ADMIN_GUESTS}/${userId}`)
- } else {
- return this.http.request<void>('delete', `${API_ADMIN_USERS}/${userId}`, {
- headers: totpCode ? new HttpHeaders({ [TWO_FA_HEADER]: totpCode }) : undefined,
- body: adminDeleteUserDto
- })
- }
+ deleteUser(userId: number, deleteUserDto: DeleteUserDto, twoFaHeaders: HttpHeaders): Observable<void> {
+ return this.http.request<void>('delete', `${deleteUserDto.isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS}/${userId}`, {
+ headers: twoFaHeaders,
+ body: deleteUserDto
+ })
}
browseGroup(name?: string, personalGroups = false): Observable<GroupBrowseModel> {
@@ -141,10 +135,8 @@ export class AdminService {
)
}
- impersonateUser(userId: number, adminPasswordDto: UserPasswordDto, totpCode?: string): Observable<LoginResponseDto> {
- return this.http.post<LoginResponseDto>(`${API_ADMIN_IMPERSONATE}/${userId}`, adminPasswordDto, {
- headers: totpCode ? { [TWO_FA_HEADER]: totpCode } : {}
- })
+ impersonateUser(userId: number, twoFaHeaders: HttpHeaders): Observable<LoginResponseDto> {
+ return this.http.post<LoginResponseDto>(`${API_ADMIN_IMPERSONATE}/${userId}`, null, { headers: twoFaHeaders })
}
initImpersonateUser(r: LoginResponseDto) {
diff --git a/frontend/src/app/applications/admin/components/admin-users.component.ts b/frontend/src/app/applications/admin/components/admin-users.component.ts
index 2b4b01d8..75f0763d 100644
--- a/frontend/src/app/applications/admin/components/admin-users.component.ts
+++ b/frontend/src/app/applications/admin/components/admin-users.component.ts
@@ -24,6 +24,7 @@ import {
} from '@fortawesome/free-solid-svg-icons'
import { ContextMenuComponent, ContextMenuModule } from '@perfectmemory/ngx-contextmenu'
import { USER_ROLE } from '@sync-in-server/backend/src/applications/users/constants/user'
+import type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { ButtonCheckboxDirective } from 'ngx-bootstrap/buttons'
import { BsModalRef } from 'ngx-bootstrap/modal'
@@ -40,11 +41,11 @@ import { SortSettings, SortTable } from '../../../common/utils/sort-table'
import { LayoutService } from '../../../layout/layout.service'
import { UserAvatarComponent } from '../../users/components/utils/user-avatar.component'
import { GuestUserModel } from '../../users/models/guest.model'
+import { UserService } from '../../users/user.service'
import { ADMIN_ICON, ADMIN_PATH, ADMIN_TITLE } from '../admin.constants'
import { AdminService } from '../admin.service'
import { AdminUserModel } from '../models/admin-user.model'
import { AdminGuestDialogComponent } from './dialogs/admin-guest-dialog.component'
-import { AdminImpersonateUserDialogComponent } from './dialogs/admin-impersonate-user-dialog.component'
import { AdminUserDialogComponent } from './dialogs/admin-user-dialog.component'
@Component({
@@ -158,6 +159,7 @@ export class AdminUsersComponent {
private readonly activatedRoute = inject(ActivatedRoute)
private readonly layout = inject(LayoutService)
private readonly adminService = inject(AdminService)
+ private readonly userService = inject(UserService)
private readonly sortSettings: SortSettings = {
default: [{ prop: 'login', type: 'string' }],
login: [{ prop: 'login', type: 'string' }],
@@ -303,9 +305,14 @@ export class AdminUsersComponent {
}
}
- impersonateIdentity() {
- this.layout.openDialog(AdminImpersonateUserDialogComponent, 'sm', {
- initialState: { user: this.selected } as AdminImpersonateUserDialogComponent
+ async impersonateIdentity() {
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog(true)
+ if (auth2FaHeaders === false) return
+ this.adminService.impersonateUser(this.selected.id, auth2FaHeaders).subscribe({
+ next: (r: LoginResponseDto) => {
+ setTimeout(() => this.adminService.initImpersonateUser(r), 500)
+ },
+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Impersonate identity', this.selected.login, e)
})
}
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts b/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts
index 2bb077d0..48bd4430 100644
--- a/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts
+++ b/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts
@@ -10,6 +10,7 @@ import { Component, inject } from '@angular/core'
import { ReactiveFormsModule } from '@angular/forms'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { USER_ROLE } from '@sync-in-server/backend/src/applications/users/constants/user'
+import type { DeleteUserDto } from '@sync-in-server/backend/src/applications/users/dto/delete-user.dto'
import type { SearchMembersDto } from '@sync-in-server/backend/src/applications/users/dto/search-members.dto'
import { L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { TabDirective, TabHeadingDirective, TabsetComponent } from 'ngx-bootstrap/tabs'
@@ -63,11 +64,15 @@ export class AdminGuestDialogComponent extends UserGuestDialogComponent {
return this.adminService.searchMembers(search)
}
- override onSubmit() {
+ override async onSubmit() {
this.submitted = true
if (this.confirmDeletion) {
// delete
- this.adminService.deleteUser(this.guest.id, null, true).subscribe({
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog(true)
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.adminService.deleteUser(this.guest.id, { deleteSpace: true, isGuest: true } satisfies DeleteUserDto, auth2FaHeaders).subscribe({
next: () => {
this.guestChange.emit(['delete', this.guest])
this.layout.sendNotification('success', 'Guest deleted', this.guest.login)
@@ -77,7 +82,11 @@ export class AdminGuestDialogComponent extends UserGuestDialogComponent {
})
} else if (!this.guest) {
// create
- this.adminService.createUser(this.makeDto(true), true).subscribe({
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.adminService.createUser(this.makeDto(true), auth2FaHeaders, true).subscribe({
next: (g: GuestUserModel) => {
this.guestChange.emit(['add', g])
this.layout.sendNotification('success', 'Guest created', this.guestForm.value.login)
@@ -93,7 +102,11 @@ export class AdminGuestDialogComponent extends UserGuestDialogComponent {
this.submitted = false
return
}
- this.adminService.updateUser(this.guest.id, updateDto, true).subscribe({
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.adminService.updateUser(this.guest.id, updateDto, auth2FaHeaders, true).subscribe({
next: (g: GuestUserModel) => {
if (g) {
this.guestChange.emit(['update', g])
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-impersonate-user-dialog.component.html b/frontend/src/app/applications/admin/components/dialogs/admin-impersonate-user-dialog.component.html
deleted file mode 100644
index 6818fbd7..00000000
--- a/frontend/src/app/applications/admin/components/dialogs/admin-impersonate-user-dialog.component.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
- ~ Copyright (C) 2012-2025 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
- -->
-
-<div class="modal-header align-items-center">
- <h4 class="modal-title">
- <fa-icon [icon]="icons.faUserSecret" class="me-2"></fa-icon>
- <span>{{ user.fullName }}</span>
- </h4>
- @if (user) {
- <h4 class="modal-title ms-auto">
- <span l10nTranslate>Impersonate identity</span>
- </h4>
- }
- <button (click)="layout.closeDialog()" aria-label="Close" class="btn-close btn-close-white {{user ? 'ms-2' : 'ms-auto'}} ms-2" type="button"></button>
-</div>
-<div class="modal-body" [formGroup]="impersonateUserForm">
- <div class="d-flex align-items-center avatar mb-3">
- <img class="avatar-img" [src]="user.avatarUrl" alt="">
- <div class="d-flex flex-column">
- <span class="mx-2"><b>{{ user.login | capitalize }}</b></span>
- <span class="mx-2">{{ user.email }}</span>
- </div>
- </div>
- <app-input-password id="password"
- [password]="impersonateUserForm.value.password"
- (passwordChange)="impersonateUserForm.controls.password.setValue($event)"
- [passwordMinLength]="passwordMinLength"
- [isRequired]="true"
- [focus]="true"
- (keyup.enter)="!impersonateUserForm.invalid && !submitted && onSubmit()"
- placeholder="Enter your password to confirm">
- </app-input-password>
-</div>
-<div class="modal-footer">
- <button (click)="layout.closeDialog()"
- class="btn btn-sm btn-secondary ms-auto"
- data-dismiss="modal"
- type="button"
- l10nTranslate>
- Cancel
- </button>
- <button (click)="onSubmit()"
- [disabled]="impersonateUserForm.invalid || submitted" class="btn btn-sm btn-primary"
- type="button"
- l10nTranslate>
- Confirm
- </button>
-</div>
\ No newline at end of file
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-impersonate-user-dialog.component.ts b/frontend/src/app/applications/admin/components/dialogs/admin-impersonate-user-dialog.component.ts
deleted file mode 100644
index 934cb88f..00000000
--- a/frontend/src/app/applications/admin/components/dialogs/admin-impersonate-user-dialog.component.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2012-2025 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 { HttpErrorResponse } from '@angular/common/http'
-import { Component, inject, Input } from '@angular/core'
-import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'
-import { FaIconComponent } from '@fortawesome/angular-fontawesome'
-import { faUserSecret } from '@fortawesome/free-solid-svg-icons'
-import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'
-import type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'
-import { L10N_LOCALE, L10nLocale, L10nTranslateDirective } from 'angular-l10n'
-import { InputPasswordComponent } from '../../../../common/components/input-password.component'
-import { CapitalizePipe } from '../../../../common/pipes/capitalize.pipe'
-import { LayoutService } from '../../../../layout/layout.service'
-import { UserService } from '../../../users/user.service'
-import { AdminService } from '../../admin.service'
-import { AdminUserModel } from '../../models/admin-user.model'
-
-@Component({
- selector: 'app-admin-impersonate-user-dialog',
- imports: [FaIconComponent, L10nTranslateDirective, ReactiveFormsModule, CapitalizePipe, InputPasswordComponent],
- templateUrl: 'admin-impersonate-user-dialog.component.html'
-})
-export class AdminImpersonateUserDialogComponent {
- @Input({ required: true }) user: AdminUserModel
- protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
- protected readonly layout = inject(LayoutService)
- protected submitted = false
- protected readonly icons = { faUserSecret }
- protected readonly passwordMinLength = USER_PASSWORD_MIN_LENGTH
- protected impersonateUserForm = new FormGroup<{
- password: FormControl<string>
- }>({ password: new FormControl('', Validators.required) })
- private readonly userService = inject(UserService)
- private readonly adminService = inject(AdminService)
-
- async onSubmit() {
- this.submitted = true
- const auth2Fa = await this.userService.auth2FaVerifyDialog()
- if (auth2Fa === false) {
- this.layout.closeDialog()
- return
- }
- const totpCode = auth2Fa === true ? undefined : auth2Fa.totpCode
- this.adminService.impersonateUser(this.user.id, { password: this.impersonateUserForm.value.password }, totpCode).subscribe({
- next: (r: LoginResponseDto) => {
- this.layout.closeDialog()
- setTimeout(() => this.adminService.initImpersonateUser(r), 500)
- },
- error: (e: HttpErrorResponse) => {
- this.submitted = false
- this.layout.sendNotification('error', 'Impersonate identity', this.user.login, e)
- }
- })
- }
-}
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-reset-user-two-fa-dialog.component.html b/frontend/src/app/applications/admin/components/dialogs/admin-reset-user-two-fa-dialog.component.html
deleted file mode 100644
index cc76fe0b..00000000
--- a/frontend/src/app/applications/admin/components/dialogs/admin-reset-user-two-fa-dialog.component.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
- ~ Copyright (C) 2012-2025 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
- -->
-
-<div class="modal-header align-items-center">
- <h4 class="modal-title">
- <fa-icon [icon]="icons.faLockOpen" class="me-2"></fa-icon>
- <span>{{ user.fullName }}</span>
- </h4>
- @if (user) {
- <h4 class="modal-title ms-auto">
- <span l10nTranslate>Reset Two-Factor Authentication</span>
- </h4>
- }
- <button (click)="layout.closeDialog()" aria-label="Close" class="btn-close btn-close-white {{user ? 'ms-2' : 'ms-auto'}} ms-2" type="button"></button>
-</div>
-<div class="modal-body" [formGroup]="adminForm">
- <div class="d-flex align-items-center avatar mb-3">
- <img class="avatar-img" [src]="user.avatarUrl" alt="">
- <div class="d-flex flex-column">
- <span class="mx-2"><b>{{ user.login | capitalize }}</b></span>
- <span class="mx-2">{{ user.email }}</span>
- </div>
- </div>
- <app-input-password id="password"
- [password]="adminForm.value.password"
- (passwordChange)="adminForm.controls.password.setValue($event)"
- [passwordMinLength]="passwordMinLength"
- [isRequired]="true"
- [focus]="true"
- (keyup.enter)="!adminForm.invalid && !submitted && onSubmit()"
- placeholder="Enter your password to confirm">
- </app-input-password>
-</div>
-<div class="modal-footer">
- <button (click)="layout.closeDialog()"
- class="btn btn-sm btn-secondary ms-auto"
- data-dismiss="modal"
- type="button"
- l10nTranslate>
- Cancel
- </button>
- <button (click)="onSubmit()"
- [disabled]="adminForm.invalid || submitted" class="btn btn-sm btn-primary"
- type="button"
- l10nTranslate>
- Confirm
- </button>
-</div>
\ No newline at end of file
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-reset-user-two-fa-dialog.component.ts b/frontend/src/app/applications/admin/components/dialogs/admin-reset-user-two-fa-dialog.component.ts
deleted file mode 100644
index cf59beb9..00000000
--- a/frontend/src/app/applications/admin/components/dialogs/admin-reset-user-two-fa-dialog.component.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2012-2025 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 { HttpErrorResponse } from '@angular/common/http'
-import { Component, EventEmitter, inject, Input, Output } from '@angular/core'
-import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'
-import { FaIconComponent } from '@fortawesome/angular-fontawesome'
-import { faLockOpen } from '@fortawesome/free-solid-svg-icons'
-import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'
-import type { TwoFaVerifyResult } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'
-import { L10N_LOCALE, L10nLocale, L10nTranslateDirective } from 'angular-l10n'
-import { InputPasswordComponent } from '../../../../common/components/input-password.component'
-import { CapitalizePipe } from '../../../../common/pipes/capitalize.pipe'
-import { LayoutService } from '../../../../layout/layout.service'
-import { UserService } from '../../../users/user.service'
-import { AdminUserModel } from '../../models/admin-user.model'
-
-@Component({
- selector: 'app-admin-reset-user-two-fa-dialog',
- imports: [FaIconComponent, L10nTranslateDirective, ReactiveFormsModule, CapitalizePipe, InputPasswordComponent],
- templateUrl: 'admin-reset-user-two-fa-dialog.component.html'
-})
-export class AdminResetUserTwoFaDialogComponent {
- @Input({ required: true }) user: AdminUserModel
- @Output() wasReset = new EventEmitter<boolean>()
- protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
- protected readonly layout = inject(LayoutService)
- protected readonly icons = { faLockOpen }
- protected readonly passwordMinLength = USER_PASSWORD_MIN_LENGTH
- protected adminForm = new FormGroup<{
- password: FormControl<string>
- }>({ password: new FormControl('', Validators.required) })
- protected submitted = false
- private readonly userService = inject(UserService)
-
- async onSubmit() {
- this.submitted = true
- const auth2Fa = await this.userService.auth2FaVerifyDialog()
- if (auth2Fa === false) {
- this.layout.closeDialog()
- return
- }
- const totpCode = auth2Fa === true ? undefined : auth2Fa.totpCode
- this.userService.adminResetUser2Fa(this.user.id, { password: this.adminForm.value.password }, totpCode).subscribe({
- next: (verify: TwoFaVerifyResult) => {
- this.wasReset.emit(verify.success)
- if (verify.success) {
- this.layout.closeDialog()
- } else {
- this.submitted = false
- this.layout.sendNotification('error', 'Reset Two-Factor Authentication', verify.message)
- }
- },
- error: (e: HttpErrorResponse) => {
- this.submitted = false
- this.layout.sendNotification('error', 'Reset Two-Factor Authentication', this.user.login, e)
- }
- })
- }
-}
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.html b/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.html
index b1d452b5..bfb7cea5 100644
--- a/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.html
+++ b/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.html
@@ -16,7 +16,7 @@
}
<button (click)="onClose()" aria-label="Close" class="btn-close btn-close-white {{user ? 'ms-2' : 'ms-auto'}} ms-2" type="button"></button>
</div>
-<div class="modal-body" [formGroup]="deleteUserForm">
+<div class="modal-body">
<div class="d-flex align-items-center avatar mb-3">
<img class="avatar-img" [src]="user.avatarUrl" alt="">
<div class="d-flex flex-column">
@@ -24,18 +24,10 @@
<span class="mx-2">{{ user.email }}</span>
</div>
</div>
- <app-input-password id="password"
- [password]="deleteUserForm.value.adminPassword"
- (passwordChange)="deleteUserForm.controls.adminPassword.setValue($event)"
- [isRequired]="true"
- [focus]="true"
- (keyup.enter)="!deleteUserForm.invalid && !submitted && onSubmit()"
- placeholder="Enter your password to confirm">
- </app-input-password>
<div class="form-check form-check-inline mt-3">
<div class="d-flex">
<label class="form-check-label" for="deleteSpace">
- <input class="form-check-input" formControlName="deleteSpace" id="deleteSpace" type="checkbox">
+ <input class="form-check-input" [(ngModel)]="deleteSpace" id="deleteSpace" type="checkbox">
<span l10nTranslate>Delete all user files</span>
</label>
</div>
@@ -50,7 +42,7 @@
Cancel
</button>
<button (click)="onSubmit()"
- [disabled]="deleteUserForm.invalid || submitted" class="btn btn-sm btn-primary"
+ [disabled]="submitted" class="btn btn-sm btn-danger"
type="button"
l10nTranslate>
Confirm
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.ts b/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.ts
index f21f7224..1201cada 100644
--- a/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.ts
+++ b/frontend/src/app/applications/admin/components/dialogs/admin-user-delete-dialog.component.ts
@@ -6,12 +6,11 @@
import { HttpErrorResponse } from '@angular/common/http'
import { Component, EventEmitter, inject, Input, Output } from '@angular/core'
-import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'
+import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { faUserMinus } from '@fortawesome/free-solid-svg-icons'
-import type { AdminDeleteUserDto } from '@sync-in-server/backend/src/applications/users/dto/delete-user.dto'
+import type { DeleteUserDto } from '@sync-in-server/backend/src/applications/users/dto/delete-user.dto'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective } from 'angular-l10n'
-import { InputPasswordComponent } from '../../../../common/components/input-password.component'
import { CapitalizePipe } from '../../../../common/pipes/capitalize.pipe'
import { LayoutService } from '../../../../layout/layout.service'
import { UserService } from '../../../users/user.service'
@@ -20,7 +19,7 @@ import { AdminUserModel } from '../../models/admin-user.model'
@Component({
selector: 'app-admin-user-delete-dialog',
- imports: [FaIconComponent, L10nTranslateDirective, ReactiveFormsModule, CapitalizePipe, InputPasswordComponent],
+ imports: [FaIconComponent, L10nTranslateDirective, ReactiveFormsModule, CapitalizePipe, FormsModule],
templateUrl: 'admin-user-delete-dialog.component.html'
})
export class AdminUserDeleteDialogComponent {
@@ -29,10 +28,7 @@ export class AdminUserDeleteDialogComponent {
protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
protected submitted = false
protected readonly icons = { faUserMinus }
- protected deleteUserForm = new FormGroup<{
- adminPassword: FormControl<string>
- deleteSpace: FormControl<boolean>
- }>({ adminPassword: new FormControl('', Validators.required), deleteSpace: new FormControl(false) })
+ protected deleteSpace = false
private readonly layout = inject(LayoutService)
private readonly adminService = inject(AdminService)
private readonly userService = inject(UserService)
@@ -44,32 +40,21 @@ export class AdminUserDeleteDialogComponent {
async onSubmit() {
this.submitted = true
- const auth2Fa = await this.userService.auth2FaVerifyDialog()
- if (auth2Fa === false) {
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog(true)
+ if (auth2FaHeaders === false) {
this.onClose()
return
}
- const totpCode = auth2Fa === true ? undefined : auth2Fa.totpCode
- this.adminService
- .deleteUser(
- this.user.id,
- {
- adminPassword: this.deleteUserForm.value.adminPassword,
- deleteSpace: this.deleteUserForm.value.deleteSpace
- } satisfies AdminDeleteUserDto,
- false,
- totpCode
- )
- .subscribe({
- next: () => {
- this.wasDeleted.emit(true)
- this.layout.sendNotification('success', 'Delete user', this.user.login)
- this.onClose()
- },
- error: (e: HttpErrorResponse) => {
- this.submitted = false
- this.layout.sendNotification('error', 'Delete user', this.user.login, e)
- }
- })
+ this.adminService.deleteUser(this.user.id, { deleteSpace: this.deleteSpace, isGuest: false } satisfies DeleteUserDto, auth2FaHeaders).subscribe({
+ next: () => {
+ this.wasDeleted.emit(true)
+ this.layout.sendNotification('success', 'Delete user', this.user.login)
+ this.onClose()
+ },
+ error: (e: HttpErrorResponse) => {
+ this.submitted = false
+ this.layout.sendNotification('error', 'Delete user', this.user.login, e)
+ }
+ })
}
}
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 3925813c..20e9cabf 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
@@ -29,6 +29,7 @@ import {
} 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 { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { BsModalRef } from 'ngx-bootstrap/modal'
import { TabDirective, TabHeadingDirective, TabsetComponent } from 'ngx-bootstrap/tabs'
@@ -46,10 +47,10 @@ import { LayoutService } from '../../../../layout/layout.service'
import { UserSearchComponent } from '../../../users/components/utils/user-search.component'
import { MemberModel } from '../../../users/models/member.model'
import { USER_ICON, USER_LANGUAGE_AUTO, USER_PASSWORD_CHANGE_TEXT } from '../../../users/user.constants'
+import { UserService } from '../../../users/user.service'
import { AdminService } from '../../admin.service'
import { AdminUserModel } from '../../models/admin-user.model'
import { AdminPermissionsComponent } from '../utils/admin-permissions.component'
-import { AdminResetUserTwoFaDialogComponent } from './admin-reset-user-two-fa-dialog.component'
import { AdminUserDeleteDialogComponent } from './admin-user-delete-dialog.component'
@Component({
@@ -115,6 +116,7 @@ export class AdminUserDialogComponent implements OnInit {
applications: FormControl<USER_PERMISSION[]>
}>
private readonly adminService = inject(AdminService)
+ private readonly userService = inject(UserService)
ngOnInit() {
this.userForm = new FormGroup({
@@ -174,16 +176,26 @@ export class AdminUserDialogComponent implements OnInit {
}
}
- reset2Fa() {
- const modalRef: BsModalRef<AdminResetUserTwoFaDialogComponent> = this.layout.openDialog(AdminResetUserTwoFaDialogComponent, 'sm', {
- initialState: { user: this.user } as AdminResetUserTwoFaDialogComponent
- })
- modalRef.content.wasReset.pipe(take(1)).subscribe((wasReset: boolean) => {
- this.user.twoFaEnabled = wasReset
+ async reset2Fa() {
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog(true)
+ if (auth2FaHeaders === false) return
+ this.userService.adminResetUser2Fa(this.user.id, auth2FaHeaders).subscribe({
+ next: (verify: TwoFaVerifyResult) => {
+ this.user.twoFaEnabled = !verify.success
+ if (verify.success) {
+ this.layout.sendNotification('success', 'Two-Factor Authentication is disabled', this.user.login)
+ } else {
+ this.layout.sendNotification('error', 'Two-Factor Authentication', verify.message)
+ }
+ },
+ error: (e: HttpErrorResponse) => {
+ this.submitted = false
+ this.layout.sendNotification('error', 'Two-Factor Authentication', this.user.login, e)
+ }
})
}
- onSubmit() {
+ async onSubmit() {
this.submitted = true
if (this.confirmDeletion) {
// delete
@@ -201,7 +213,11 @@ export class AdminUserDialogComponent implements OnInit {
})
} else if (!this.user) {
// create
- this.adminService.createUser(this.makeDto(true)).subscribe({
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.adminService.createUser(this.makeDto(true), auth2FaHeaders).subscribe({
next: (u: AdminUserModel) => {
this.userChange.emit(['add', u])
this.layout.sendNotification('success', 'User created', this.userForm.value.login)
@@ -211,7 +227,11 @@ export class AdminUserDialogComponent implements OnInit {
})
} else {
// update
- this.adminService.updateUser(this.user.id, this.makeDto()).subscribe({
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.adminService.updateUser(this.user.id, this.makeDto(), auth2FaHeaders).subscribe({
next: (u: AdminUserModel) => {
this.userChange.emit(['update', u])
this.layout.sendNotification('success', 'User updated', this.userForm.value.login)
diff --git a/frontend/src/app/applications/sync/components/sync-clients.component.ts b/frontend/src/app/applications/sync/components/sync-clients.component.ts
index b43729ac..f200688c 100644
--- a/frontend/src/app/applications/sync/components/sync-clients.component.ts
+++ b/frontend/src/app/applications/sync/components/sync-clients.component.ts
@@ -105,7 +105,7 @@ export class SyncClientsComponent {
}
},
error: (e: HttpErrorResponse) => {
- console.log(e)
+ console.error(e)
this.loading = false
this.layout.sendNotification('error', 'Clients', e.error.message)
}
diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.html b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.html
index 4bb72ee2..de4b06b9 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.html
+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-enable-dialog.component.html
@@ -46,7 +46,7 @@
<strong (click)="clipBoardSecret()" role="button" class="ms-1 font-monospace link-primary">{{ secret }}</strong>
</div>
</div>
- <hr>
+ <hr style="border-width: 2px">
<form (ngSubmit)="onSubmit()" [formGroup]="twoFaForm">
<div class="text-align-center mb-3" l10nTranslate>Enter your password</div>
<div class="mb-3">
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 703f3109..3cb00fb2 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
@@ -69,12 +69,12 @@ export class UserAuth2faEnableDialogComponent {
clipBoardSecret() {
this.clipBoardService.copyFromContent(this.secret)
- this.layout.sendNotification('info', 'Two-factor authentication', 'Secret copied')
+ this.layout.sendNotification('info', 'Two-factor Authentication', 'Secret copied')
}
clipBoardRecoveryCodes() {
this.clipBoardService.copyFromContent(this.recoveryCodes.join('\n'))
- this.layout.sendNotification('info', 'Two-factor authentication', 'Recovery codes copied')
+ this.layout.sendNotification('info', 'Two-factor Authentication', 'Recovery codes copied')
}
downloadRecoveryCodes() {
diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.html b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.html
index c3662424..c6c6eae4 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.html
+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.html
@@ -6,49 +6,57 @@
<div class="modal-header align-items-center justify-content-center">
<h4 class="modal-title">
<fa-icon [icon]="icons.faLock" class="me-2"></fa-icon>
- <span l10nTranslate>Two-Factor Authentication</span>
+ @if (withTwoFaEnabled) {
+ <span l10nTranslate>Two-Factor Authentication</span>
+ } @else {
+ <span l10nTranslate>Password Authentication</span>
+ }
</h4>
</div>
<div class="modal-body modal-auth-verify-2fa">
<div class="card shadow-sm">
<div class="card-body">
- @if (hasError) {
- <p class="text-danger d-flex justify-content-center align-items-center mb-3" style="height: 36px" l10nTranslate>{{ hasError }}</p>
- } @else {
- <p class="text-muted d-flex justify-content-center align-items-center mb-3" style="height: 36px" l10nTranslate>
- @if (withPassword) {
- Enter your password
- } @else {
- Valid with your TOTP code
- }
- </p>
- }
+ <p [class.text-danger]="hasError" class="d-flex justify-content-center align-items-center mb-3" l10nTranslate>
+ @if (hasError) {
+ {{ hasError }}
+ } @else if (withPassword) {
+ Enter your password
+ } @else {
+ Valid with your TOTP code
+ }
+ </p>
<form (ngSubmit)="onSubmit()" [formGroup]="twoFaForm">
@if (withPassword) {
<div class="mb-4">
<app-input-password id="password"
[password]="twoFaForm.value.password"
- (passwordChange)="twoFaForm.controls.password.setValue($event)"
+ (passwordChange)="updatePassword($event)"
[focus]="true"
[centered]="true"
- placeholder="••••••">
+ placeholder="••••••••">
</app-input-password>
</div>
- <div class="text-muted text-align-center mb-3" l10nTranslate>Valid with your TOTP code</div>
}
- <div class="mb-3">
- <input
- appAutofocus
- type="text"
- [maxlength]=twoFaCodelength
- class="form-control text-center fs-4"
- formControlName="totpCode"
- placeholder="••••••"
- inputmode="numeric"
- autocomplete="one-time-code"
- name="totp"
- />
- </div>
+ @if (withTwoFaEnabled) {
+ @if (withPassword) {
+ <div class="text-align-center mb-3" l10nTranslate>Valid with your TOTP code</div>
+ }
+ <div class="mb-3">
+ <input
+ appAutofocus
+ [autoFocus]="!withPassword"
+ [autoSelect]="!withPassword"
+ type="text"
+ [maxlength]=twoFaCodelength
+ class="form-control text-center fs-4"
+ formControlName="totpCode"
+ placeholder="••••••"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ name="totp"
+ />
+ </div>
+ }
<div class="d-grid gap-2">
<button type="submit" [disabled]="twoFaForm.invalid || submitted" class="btn btn-primary" l10nTranslate>Confirm</button>
<button type="button" (click)="onClose()" class="btn btn-secondary" l10nTranslate>Cancel</button>
diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.ts b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.ts
index e8df6632..81dbab76 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.ts
+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-2fa-verify-dialog.component.ts
@@ -4,60 +4,61 @@
* See the LICENSE file for licensing details
*/
-import { Component, inject, Input } from '@angular/core'
+import { HttpHeaders } from '@angular/common/http'
+import { Component, inject, Input, OnInit } from '@angular/core'
import { FormGroup, ReactiveFormsModule, UntypedFormBuilder, Validators } from '@angular/forms'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { faKey, faLock } from '@fortawesome/free-solid-svg-icons'
-import { TWO_FA_CODE_LENGTH } from '@sync-in-server/backend/src/authentication/constants/auth'
-import { TwoFaVerifyResult } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'
+import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'
+import { TWO_FA_CODE_LENGTH, TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from '@sync-in-server/backend/src/authentication/constants/auth'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective } from 'angular-l10n'
import { InputPasswordComponent } from '../../../../common/components/input-password.component'
import { AutofocusDirective } from '../../../../common/directives/auto-focus.directive'
import { LayoutService } from '../../../../layout/layout.service'
-import { UserTwoFaVerify } from '../../interfaces/user.interface'
-import { UserService } from '../../user.service'
@Component({
selector: 'app-user-auth-2fa-verify-dialog',
imports: [FaIconComponent, L10nTranslateDirective, AutofocusDirective, ReactiveFormsModule, InputPasswordComponent],
templateUrl: 'user-auth-2fa-verify-dialog.component.html'
})
-export class UserAuth2FaVerifyDialogComponent {
+export class UserAuth2FaVerifyDialogComponent implements OnInit {
@Input() withPassword = false
- isValid!: (result: false | UserTwoFaVerify) => void // injected callback
+ @Input() withTwoFaEnabled = true
+ isValid!: (result: false | HttpHeaders) => void // injected callback
protected submitted = false
protected hasError: any = null
protected readonly icons = { faKey, faLock }
protected readonly twoFaCodelength = TWO_FA_CODE_LENGTH
protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
- private readonly userService = inject(UserService)
+ protected twoFaForm: FormGroup
private readonly fb = inject(UntypedFormBuilder)
- protected twoFaForm: FormGroup = this.fb.group({
- totpCode: this.fb.control('', [Validators.required, Validators.pattern(new RegExp(`^\\d{${TWO_FA_CODE_LENGTH}}$`))]),
- password: this.fb.control('')
- })
private readonly layout = inject(LayoutService)
- onClose(state: false | UserTwoFaVerify = false) {
+ ngOnInit() {
+ this.twoFaForm = this.fb.group({
+ totpCode: this.fb.control(
+ '',
+ this.withTwoFaEnabled ? [Validators.required, Validators.pattern(new RegExp(`^\\d{${TWO_FA_CODE_LENGTH}}$`))] : null
+ ),
+ password: this.fb.control('', this.withPassword ? [Validators.required, Validators.minLength(USER_PASSWORD_MIN_LENGTH)] : null)
+ })
+ }
+
+ onClose(state: false | HttpHeaders = false) {
this.isValid(state)
this.layout.closeDialog()
}
onSubmit() {
this.submitted = true
- this.userService.verify2Fa({ code: this.twoFaForm.value.totpCode }).subscribe({
- next: (res: TwoFaVerifyResult) => {
- if (res.success) {
- this.onClose({ totpCode: this.twoFaForm.value.totpCode, password: this.twoFaForm.value.password })
- } else {
- this.hasError = 'Incorrect code or password'
- }
- setTimeout(() => (this.submitted = false), 1000)
- },
- error: (e) => {
- this.hasError = e.error ? e.error.message : e
- setTimeout(() => (this.submitted = false), 1000)
- }
+ const headers = new HttpHeaders({
+ ...(this.withTwoFaEnabled ? { [TWO_FA_HEADER_CODE]: this.twoFaForm.value.totpCode } : {}),
+ ...(this.withPassword ? { [TWO_FA_HEADER_PASSWORD]: this.twoFaForm.value.password } : {})
})
+ this.onClose(headers)
+ }
+
+ updatePassword(password: string) {
+ this.twoFaForm.patchValue({ password: password })
}
}
diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts
index 5814ba1b..4d0085c7 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts
+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts
@@ -4,7 +4,7 @@
* See the LICENSE file for licensing details
*/
-import { HttpErrorResponse } from '@angular/common/http'
+import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'
import { Component, EventEmitter, inject, Input, OnInit, Output } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule, UntypedFormBuilder, Validators } from '@angular/forms'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
@@ -89,14 +89,18 @@ export class UserAuthManageAppPasswordsDialogComponent implements OnInit {
})
}
- genAppPassword() {
+ async genAppPassword() {
for (const appPwd of this.appPasswords) {
if (appPwd.name === this.appPasswordForm.value.name) {
this.hasError = 'This name is already used'
return
}
}
- this.userService.generateAppPassword(this.appPasswordForm.value).subscribe({
+ const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.userService.generateAppPassword(this.appPasswordForm.value, auth2FaHeaders).subscribe({
next: (appPassword: UserAppPassword) => {
this.appPasswordForm.patchValue({ name: '', expiration: null })
this.appPasswords.unshift(appPassword)
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 99e5a648..c1dca24e 100644
--- a/frontend/src/app/applications/users/components/user-account.component.ts
+++ b/frontend/src/app/applications/users/components/user-account.component.ts
@@ -4,7 +4,7 @@
* See the LICENSE file for licensing details
*/
-import { HttpErrorResponse } from '@angular/common/http'
+import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'
import { Component, inject, OnDestroy } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
@@ -16,6 +16,7 @@ import {
} from '@sync-in-server/backend/src/applications/users/constants/user'
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 { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { BsModalRef } from 'ngx-bootstrap/modal'
@@ -32,7 +33,7 @@ import { TimeAgoPipe } from '../../../common/pipes/time-ago.pipe'
import { TimeDateFormatPipe } from '../../../common/pipes/time-date-format.pipe'
import { LayoutService } from '../../../layout/layout.service'
import { StoreService } from '../../../store/store.service'
-import { UserTwoFaVerify, UserType } from '../interfaces/user.interface'
+import { UserType } from '../interfaces/user.interface'
import { USER_ICON, USER_LANGUAGE_AUTO, USER_PATH, USER_TITLE } from '../user.constants'
import { UserService } from '../user.service'
import { UserAuth2faEnableDialogComponent } from './dialogs/user-auth-2fa-enable-dialog.component'
@@ -128,14 +129,11 @@ export class UserAccountComponent implements OnDestroy {
this.layout.sendNotification('warning', 'Configuration', 'New password must have 8 characters minimum')
return
}
- const auth2Fa = await this.userService.auth2FaVerifyDialog()
- if (auth2Fa === false) {
- this.oldPassword = ''
- this.newPassword = ''
+ const auth2FaHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
return
}
- const totpCode = auth2Fa === true ? undefined : auth2Fa.totpCode
- this.userService.changePassword({ oldPassword: this.oldPassword, newPassword: this.newPassword }, totpCode).subscribe({
+ this.userService.changePassword({ oldPassword: this.oldPassword, newPassword: this.newPassword }, auth2FaHeaders).subscribe({
next: () => {
this.oldPassword = ''
this.newPassword = ''
@@ -191,12 +189,12 @@ export class UserAccountComponent implements OnDestroy {
}
async disable2Fa() {
- const auth2Fa: boolean | UserTwoFaVerify = await this.userService.auth2FaVerifyDialog(true)
- if (typeof auth2Fa === 'boolean') {
- // two-fa must be enabled to be disabled
+ const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog(true)
+ if (!auth2FaHeaders) {
+ // two-fa is already enabled to be disabled
return
}
- this.userService.disable2Fa({ code: auth2Fa.totpCode, password: auth2Fa.password }).subscribe({
+ this.userService.disable2Fa({ code: auth2FaHeaders.get(TWO_FA_HEADER_CODE), password: auth2FaHeaders.get(TWO_FA_HEADER_PASSWORD) }).subscribe({
next: () => {
this.layout.sendNotification('success', 'Configuration', 'Two-Factor Authentication is disabled')
this.store.user.next({ ...this.store.user.getValue(), twoFaEnabled: false })
@@ -208,7 +206,11 @@ export class UserAccountComponent implements OnDestroy {
}
async manageAppPasswords() {
- this.userService.listAppPasswords().subscribe({
+ const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog()
+ if (auth2FaHeaders === false) {
+ return
+ }
+ this.userService.listAppPasswords(auth2FaHeaders).subscribe({
next: (appPasswords: Omit<UserAppPassword, 'password'>[]) => {
const modalRef: BsModalRef<UserAuthManageAppPasswordsDialogComponent> = this.layout.openDialog(
UserAuthManageAppPasswordsDialogComponent,
diff --git a/frontend/src/app/applications/users/interfaces/user.interface.ts b/frontend/src/app/applications/users/interfaces/user.interface.ts
index 01ca6b12..c6baf366 100644
--- a/frontend/src/app/applications/users/interfaces/user.interface.ts
+++ b/frontend/src/app/applications/users/interfaces/user.interface.ts
@@ -9,8 +9,3 @@ import type { UserModel } from '@sync-in-server/backend/src/applications/users/m
export type UserType = Omit<UserModel, 'permissions' | 'password'>
export type UserStatus = keyof Pick<UserType, 'isAdmin' | 'isUser' | 'isGuest' | 'isLink' | 'clientId'>
-
-export interface UserTwoFaVerify {
- totpCode: string
- password: string
-}
diff --git a/frontend/src/app/applications/users/user.service.ts b/frontend/src/app/applications/users/user.service.ts
index 357a5fc7..23400fc2 100644
--- a/frontend/src/app/applications/users/user.service.ts
+++ b/frontend/src/app/applications/users/user.service.ts
@@ -4,7 +4,7 @@
* See the LICENSE file for licensing details
*/
-import { HttpClient, HttpErrorResponse } from '@angular/common/http'
+import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'
import { inject, Injectable } from '@angular/core'
import { NOTIFICATIONS_WS } from '@sync-in-server/backend/src/applications/notifications/constants/websocket'
import { SPACE_OPERATION } from '@sync-in-server/backend/src/applications/spaces/constants/spaces'
@@ -35,7 +35,6 @@ import type {
UserAppPasswordDto,
UserLanguageDto,
UserNotificationDto,
- UserPasswordDto,
UserUpdatePasswordDto
} from '@sync-in-server/backend/src/applications/users/dto/user-properties.dto'
import type { GroupBrowse } from '@sync-in-server/backend/src/applications/users/interfaces/group-browse.interface'
@@ -48,14 +47,8 @@ import type {
EventUpdateOnlineStatus,
UserOnline
} from '@sync-in-server/backend/src/applications/users/interfaces/websocket.interface'
-import { TWO_FA_HEADER } from '@sync-in-server/backend/src/authentication/constants/auth'
-import {
- API_TWO_FA_ADMIN_RESET_USER,
- API_TWO_FA_DISABLE,
- API_TWO_FA_ENABLE,
- API_TWO_FA_VERIFY
-} from '@sync-in-server/backend/src/authentication/constants/routes'
-import type { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from '@sync-in-server/backend/src/authentication/dto/two-fa-verify.dto'
+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 { BsModalRef } from 'ngx-bootstrap/modal'
import { Socket } from 'ngx-socket-io'
@@ -66,7 +59,7 @@ import { StoreService } from '../../store/store.service'
import { NotificationsService } from '../notifications/notifications.service'
import { SPACES_TITLE } from '../spaces/spaces.constants'
import { UserAuth2FaVerifyDialogComponent } from './components/dialogs/user-auth-2fa-verify-dialog.component'
-import { UserTwoFaVerify, UserType } from './interfaces/user.interface'
+import { UserType } from './interfaces/user.interface'
import { GroupBrowseModel } from './models/group-browse.model'
import { GuestUserModel } from './models/guest.model'
import { MemberModel } from './models/member.model'
@@ -211,10 +204,8 @@ export class UserService {
})
}
- changePassword(userPasswordDto: UserUpdatePasswordDto, totpCode?: string): Observable<any> {
- return this.http.put(API_USERS_MY_PASSWORD, userPasswordDto, {
- headers: totpCode ? { [TWO_FA_HEADER]: totpCode } : {}
- })
+ changePassword(userPasswordDto: UserUpdatePasswordDto, twoFaHeaders: HttpHeaders): Observable<any> {
+ return this.http.put(API_USERS_MY_PASSWORD, userPasswordDto, { headers: twoFaHeaders })
}
changeLanguage(userLanguageDto: UserLanguageDto): Observable<any> {
@@ -288,12 +279,12 @@ export class UserService {
})
}
- listAppPasswords(): Observable<Omit<UserAppPassword, 'password'>[]> {
- return this.http.get<Omit<UserAppPassword, 'password'>[]>(API_USERS_MY_APP_PASSWORDS)
+ listAppPasswords(twoFaHeaders: HttpHeaders): Observable<Omit<UserAppPassword, 'password'>[]> {
+ return this.http.get<Omit<UserAppPassword, 'password'>[]>(API_USERS_MY_APP_PASSWORDS, { headers: twoFaHeaders })
}
- generateAppPassword(userAppPasswordDto: UserAppPasswordDto): Observable<UserAppPassword> {
- return this.http.post<UserAppPassword>(API_USERS_MY_APP_PASSWORDS, userAppPasswordDto)
+ generateAppPassword(userAppPasswordDto: UserAppPasswordDto, twoFaHeaders: HttpHeaders): Observable<UserAppPassword> {
+ return this.http.post<UserAppPassword>(API_USERS_MY_APP_PASSWORDS, userAppPasswordDto, { headers: twoFaHeaders })
}
deleteAppPassword(name: string): Observable<void> {
@@ -312,32 +303,27 @@ export class UserService {
return this.http.post<TwoFaVerifyResult>(API_TWO_FA_DISABLE, twoFaVerifyDto)
}
- verify2Fa(twoFaVerifyDto: TwoFaVerifyDto): Observable<TwoFaVerifyResult> {
- return this.http.post<TwoFaVerifyResult>(API_TWO_FA_VERIFY, twoFaVerifyDto)
- }
-
- adminResetUser2Fa(userId: number, adminPasswordDto: UserPasswordDto, totpCode?: string): Observable<TwoFaVerifyResult> {
- return this.http.post<TwoFaVerifyResult>(`${API_TWO_FA_ADMIN_RESET_USER}/${userId}`, adminPasswordDto, {
- headers: totpCode ? { [TWO_FA_HEADER]: totpCode } : {}
- })
+ adminResetUser2Fa(userId: number, twoFaHeaders: HttpHeaders): Observable<TwoFaVerifyResult> {
+ return this.http.post<TwoFaVerifyResult>(`${API_TWO_FA_ADMIN_RESET_USER}/${userId}`, null, { headers: twoFaHeaders })
}
- async auth2FaVerifyDialog(withPassword = false): Promise<boolean | UserTwoFaVerify> {
- // returns: true (no check), false (check failed), `UserTwoFaVerify` (totpCode & password?)
- if (this.store.server().twoFaEnabled && this.user.twoFaEnabled) {
+ async auth2FaVerifyDialog(withPassword = false): Promise<false | HttpHeaders> {
+ // returns: false (dialog closed), undefined (no check), `HttpHeaders` (code and/or password to check)
+ const TwoFaEnabled = this.store.server().twoFaEnabled && this.user.twoFaEnabled
+ if (withPassword || TwoFaEnabled) {
return new Promise((resolve) => {
const modalRef: BsModalRef<UserAuth2FaVerifyDialogComponent> = this.layout.openDialog(
UserAuth2FaVerifyDialogComponent,
'xs',
- { initialState: { withPassword: withPassword } },
+ { initialState: { withPassword: withPassword, withTwoFaEnabled: TwoFaEnabled } },
{ keyboard: false }
)
- modalRef.content.isValid = (result: false | UserTwoFaVerify) => {
+ modalRef.content.isValid = (result: false | HttpHeaders) => {
resolve(result)
}
})
}
- return true
+ return undefined
}
private checkQuota(user: UserType) {
diff --git a/frontend/src/app/auth/auth.component.html b/frontend/src/app/auth/auth.component.html
index d51b86b6..4a097bb6 100644
--- a/frontend/src/app/auth/auth.component.html
+++ b/frontend/src/app/auth/auth.component.html
@@ -12,7 +12,7 @@
</div>
<div class="body">
@if (twoFaVerify) {
- <p class="fs-sm mb-3 {{hasError ? 'text-danger' : 'text-white-50'}}" l10nTranslate>{{ hasError || 'Two-factor authentication' }}</p>
+ <p class="fs-sm mb-3 {{hasError ? 'text-danger' : 'text-white-50'}}" l10nTranslate>{{ hasError || 'Two-factor Authentication' }}</p>
<form (ngSubmit)="onSubmit2Fa()" [formGroup]="twoFaForm">
<div class="input-group mt-2 mb-4">
@if (twoFaForm.value.isRecoveryCode) {
diff --git a/frontend/src/app/auth/auth.component.ts b/frontend/src/app/auth/auth.component.ts
index fca7b3d6..34fae185 100644
--- a/frontend/src/app/auth/auth.component.ts
+++ b/frontend/src/app/auth/auth.component.ts
@@ -10,6 +10,7 @@ import { FormGroup, ReactiveFormsModule, UntypedFormBuilder, Validators } from '
import { Router } from '@angular/router'
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'
@@ -40,7 +41,7 @@ export class AuthComponent {
})
protected twoFaForm: FormGroup = this.fb.group({
totpCode: this.fb.control('', [Validators.required, Validators.pattern(new RegExp(`^\\d{${TWO_FA_CODE_LENGTH}}$`))]),
- recoveryCode: this.fb.control('', [Validators.required, Validators.minLength(8)]),
+ recoveryCode: this.fb.control('', [Validators.required, Validators.minLength(USER_PASSWORD_MIN_LENGTH)]),
isRecoveryCode: this.fb.control(false)
})
private readonly router = inject(Router)
diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.json
index 5fb71e76..2e34b859 100644
--- a/frontend/src/i18n/fr.json
+++ b/frontend/src/i18n/fr.json
@@ -676,7 +676,6 @@
"Feature not enabled": "Fonctionnalité non activée",
"Check the settings": "Vérifiez les paramètres",
"Security": "Sécurité",
- "Two-factor authentication": "Authentification à deux facteurs",
"Recovery code": "Code de récupération",
"Use a recovery code": "Utiliser un code de récupération",
"TOTP code": "Code TOTP",
@@ -692,10 +691,10 @@
"Password name": "Nom du mot de passe",
"Manage": "Gérer",
"Manage app passwords": "Gérer les mots de passe d’application",
+ "Password Authentication": "Authentification par mot de passe",
"Two-Factor Authentication": "Authentification à deux facteurs",
"Two-Factor Authentication is enabled": "L’authentification à deux facteurs est activée",
"Two-Factor Authentication is disabled": "L’authentification à deux facteurs est désactivée",
- "Reset Two-Factor Authentication": "Réinitialiser l’authentification à deux facteurs",
"Scan this QR code using your authenticator app.": "Scannez ce code QR avec votre application d’authentification.",
"(Such as FreeOTP, Proton Authenticator etc.)": "(Par ex. FreeOTP, Proton Authenticator, etc.)",
"Or enter this secret manually": "Ou entrez ce secret manuellement",
diff --git a/frontend/src/styles/components/_theme_dark.scss b/frontend/src/styles/components/_theme_dark.scss
index 25c11f25..bf6e8d9a 100755
--- a/frontend/src/styles/components/_theme_dark.scss
+++ b/frontend/src/styles/components/_theme_dark.scss
@@ -450,6 +450,7 @@
.modal-auth-verify-2fa {
.card {
+ color: $gray-light;
background-color: $sidebar-dark-icons-menu-bg;
border-color: $sidebar-dark-icons-menu-border-color;
}