feat: view the user's app version on the user page (#21345)

Co-authored-by: Daniel Dietzler <mail@ddietzler.dev>
This commit is contained in:
aviv926
2025-10-22 01:36:18 +03:00
committed by GitHub
parent c3a533ab40
commit 032de9ff2f
27 changed files with 301 additions and 50 deletions

View File

@@ -2,6 +2,7 @@ import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put,
import { ApiTags } from '@nestjs/swagger';
import { AssetStatsDto, AssetStatsResponseDto } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { SessionResponseDto } from 'src/dtos/session.dto';
import { UserPreferencesResponseDto, UserPreferencesUpdateDto } from 'src/dtos/user-preferences.dto';
import {
UserAdminCreateDto,
@@ -58,6 +59,12 @@ export class UserAdminController {
return this.service.delete(auth, id, dto);
}
@Get(':id/sessions')
@Authenticated({ permission: Permission.AdminSessionRead, admin: true })
getUserSessionsAdmin(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<SessionResponseDto[]> {
return this.service.getSessions(auth, id);
}
@Get(':id/statistics')
@Authenticated({ permission: Permission.AdminUserRead, admin: true })
getUserStatisticsAdmin(

View File

@@ -238,6 +238,7 @@ export type Session = {
expiresAt: Date | null;
deviceOS: string;
deviceType: string;
appVersion: string | null;
pinExpiresAt: Date | null;
isPendingSyncReset: boolean;
};
@@ -308,7 +309,7 @@ export const columns = {
assetFiles: ['asset_file.id', 'asset_file.path', 'asset_file.type'],
authUser: ['user.id', 'user.name', 'user.email', 'user.isAdmin', 'user.quotaUsageInBytes', 'user.quotaSizeInBytes'],
authApiKey: ['api_key.id', 'api_key.permissions'],
authSession: ['session.id', 'session.updatedAt', 'session.pinExpiresAt'],
authSession: ['session.id', 'session.updatedAt', 'session.pinExpiresAt', 'session.appVersion'],
authSharedLink: [
'shared_link.id',
'shared_link.userId',

View File

@@ -34,6 +34,7 @@ export class SessionResponseDto {
current!: boolean;
deviceType!: string;
deviceOS!: string;
appVersion!: string | null;
isPendingSyncReset!: boolean;
}
@@ -47,6 +48,7 @@ export const mapSession = (entity: Session, currentId?: string): SessionResponse
updatedAt: entity.updatedAt.toISOString(),
expiresAt: entity.expiresAt?.toISOString(),
current: currentId === entity.id,
appVersion: entity.appVersion,
deviceOS: entity.deviceOS,
deviceType: entity.deviceType,
isPendingSyncReset: entity.isPendingSyncReset,

View File

@@ -173,6 +173,7 @@ export function mapUserAdmin(entity: UserAdmin): UserAdminResponseDto {
const license = metadata.find(
(item): item is UserMetadataItem<UserMetadataKey.License> => item.key === UserMetadataKey.License,
)?.value;
return {
...mapUser(entity),
storageLabel: entity.storageLabel,

View File

@@ -236,6 +236,8 @@ export enum Permission {
AdminUserUpdate = 'adminUser.update',
AdminUserDelete = 'adminUser.delete',
AdminSessionRead = 'adminSession.read',
AdminAuthUnlinkAll = 'adminAuth.unlinkAll',
}

View File

@@ -13,7 +13,7 @@ import { AuthDto } from 'src/dtos/auth.dto';
import { ApiCustomExtension, ImmichQuery, MetadataKey, Permission } from 'src/enum';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { AuthService, LoginDetails } from 'src/services/auth.service';
import { UAParser } from 'ua-parser-js';
import { getUserAgentDetails } from 'src/utils/request';
type AdminRoute = { admin?: true };
type SharedLinkRoute = { sharedLink?: true };
@@ -56,13 +56,14 @@ export const FileResponse = () =>
export const GetLoginDetails = createParamDecorator((data, context: ExecutionContext): LoginDetails => {
const request = context.switchToHttp().getRequest<Request>();
const userAgent = UAParser(request.headers['user-agent']);
const { deviceType, deviceOS, appVersion } = getUserAgentDetails(request.headers);
return {
clientIp: request.ip ?? '',
isSecure: request.secure,
deviceType: userAgent.browser.name || userAgent.device.type || (request.headers.devicemodel as string) || '',
deviceOS: userAgent.os.name || (request.headers.devicetype as string) || '',
deviceType,
deviceOS,
appVersion,
};
});
@@ -86,7 +87,6 @@ export class AuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const targets = [context.getHandler()];
const options = this.reflector.getAllAndOverride<AuthenticatedOptions | undefined>(MetadataKey.AuthRoute, targets);
if (!options) {
return true;

View File

@@ -23,6 +23,7 @@ select
"session"."id",
"session"."updatedAt",
"session"."pinExpiresAt",
"session"."appVersion",
(
select
to_json(obj)

View File

@@ -0,0 +1,9 @@
import { Kysely, sql } from 'kysely';
export async function up(db: Kysely<any>): Promise<void> {
await sql`ALTER TABLE "session" ADD "appVersion" character varying;`.execute(db);
}
export async function down(db: Kysely<any>): Promise<void> {
await sql`ALTER TABLE "session" DROP COLUMN "appVersion";`.execute(db);
}

View File

@@ -42,6 +42,9 @@ export class SessionTable {
@Column({ default: '' })
deviceOS!: Generated<string>;
@Column({ nullable: true })
appVersion!: string | null;
@UpdateIdColumn({ index: true })
updateId!: Generated<string>;

View File

@@ -41,6 +41,7 @@ const loginDetails = {
clientIp: '127.0.0.1',
deviceOS: '',
deviceType: '',
appVersion: null,
};
const fixtures = {
@@ -243,6 +244,7 @@ describe(AuthService.name, () => {
updatedAt: session.updatedAt,
user: factory.authUser(),
pinExpiresAt: null,
appVersion: null,
};
mocks.session.getByToken.mockResolvedValue(sessionWithToken);
@@ -408,6 +410,7 @@ describe(AuthService.name, () => {
updatedAt: session.updatedAt,
user: factory.authUser(),
pinExpiresAt: null,
appVersion: null,
};
mocks.session.getByToken.mockResolvedValue(sessionWithToken);
@@ -435,6 +438,7 @@ describe(AuthService.name, () => {
user: factory.authUser(),
isPendingSyncReset: false,
pinExpiresAt: null,
appVersion: null,
};
mocks.session.getByToken.mockResolvedValue(sessionWithToken);
@@ -456,6 +460,7 @@ describe(AuthService.name, () => {
user: factory.authUser(),
isPendingSyncReset: false,
pinExpiresAt: null,
appVersion: null,
};
mocks.session.getByToken.mockResolvedValue(sessionWithToken);

View File

@@ -29,11 +29,13 @@ import { BaseService } from 'src/services/base.service';
import { isGranted } from 'src/utils/access';
import { HumanReadableSize } from 'src/utils/bytes';
import { mimeTypes } from 'src/utils/mime-types';
import { getUserAgentDetails } from 'src/utils/request';
export interface LoginDetails {
isSecure: boolean;
clientIp: string;
deviceType: string;
deviceOS: string;
appVersion: string | null;
}
interface ClaimOptions<T> {
@@ -218,7 +220,7 @@ export class AuthService extends BaseService {
}
if (session) {
return this.validateSession(session);
return this.validateSession(session, headers);
}
if (apiKey) {
@@ -463,15 +465,22 @@ export class AuthService extends BaseService {
return this.cryptoRepository.compareBcrypt(inputSecret, existingHash);
}
private async validateSession(tokenValue: string): Promise<AuthDto> {
private async validateSession(tokenValue: string, headers: IncomingHttpHeaders): Promise<AuthDto> {
const hashedToken = this.cryptoRepository.hashSha256(tokenValue);
const session = await this.sessionRepository.getByToken(hashedToken);
if (session?.user) {
const { appVersion, deviceOS, deviceType } = getUserAgentDetails(headers);
const now = DateTime.now();
const updatedAt = DateTime.fromJSDate(session.updatedAt);
const diff = now.diff(updatedAt, ['hours']);
if (diff.hours > 1) {
await this.sessionRepository.update(session.id, { id: session.id, updatedAt: new Date() });
if (diff.hours > 1 || appVersion != session.appVersion) {
await this.sessionRepository.update(session.id, {
id: session.id,
updatedAt: new Date(),
appVersion,
deviceOS,
deviceType,
});
}
// Pin check
@@ -529,6 +538,7 @@ export class AuthService extends BaseService {
token: tokenHashed,
deviceOS: loginDetails.deviceOS,
deviceType: loginDetails.deviceType,
appVersion: loginDetails.appVersion,
userId: user.id,
});

View File

@@ -2,6 +2,7 @@ import { BadRequestException, ForbiddenException, Injectable } from '@nestjs/com
import { SALT_ROUNDS } from 'src/constants';
import { AssetStatsDto, AssetStatsResponseDto, mapStats } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { SessionResponseDto, mapSession } from 'src/dtos/session.dto';
import { UserPreferencesResponseDto, UserPreferencesUpdateDto, mapPreferences } from 'src/dtos/user-preferences.dto';
import {
UserAdminCreateDto,
@@ -119,6 +120,11 @@ export class UserAdminService extends BaseService {
return mapUserAdmin(user);
}
async getSessions(auth: AuthDto, id: string): Promise<SessionResponseDto[]> {
const sessions = await this.sessionRepository.getByUserId(id);
return sessions.map((session) => mapSession(session));
}
async getStatistics(auth: AuthDto, id: string, dto: AssetStatsDto): Promise<AssetStatsResponseDto> {
const stats = await this.assetRepository.getStatistics(id, dto);
return mapStats(stats);

View File

@@ -1,5 +1,22 @@
import { IncomingHttpHeaders } from 'node:http';
import { UAParser } from 'ua-parser-js';
export const fromChecksum = (checksum: string): Buffer => {
return Buffer.from(checksum, checksum.length === 28 ? 'base64' : 'hex');
};
export const fromMaybeArray = <T>(param: T | T[]) => (Array.isArray(param) ? param[0] : param);
const getAppVersionFromUA = (ua: string) =>
ua.match(/^Immich_(?:Android|iOS)_(?<appVersion>.+)$/)?.groups?.appVersion ?? null;
export const getUserAgentDetails = (headers: IncomingHttpHeaders) => {
const userAgent = UAParser(headers['user-agent']);
const appVersion = getAppVersionFromUA(headers['user-agent'] ?? '');
return {
deviceType: userAgent.browser.name || userAgent.device.type || (headers['devicemodel'] as string) || '',
deviceOS: userAgent.os.name || (headers['devicetype'] as string) || '',
appVersion,
};
};