2023-07-15 06:03:56 +02:00
|
|
|
import { SystemConfig, UserEntity } from '@app/infra/entities';
|
2023-12-14 17:55:40 +01:00
|
|
|
import { ImmichLogger } from '@app/infra/logger';
|
2023-09-01 13:08:42 +02:00
|
|
|
import {
|
|
|
|
BadRequestException,
|
|
|
|
Inject,
|
|
|
|
Injectable,
|
|
|
|
InternalServerErrorException,
|
|
|
|
UnauthorizedException,
|
|
|
|
} from '@nestjs/common';
|
2023-06-16 21:54:17 +02:00
|
|
|
import cookieParser from 'cookie';
|
2023-07-15 06:03:56 +02:00
|
|
|
import { DateTime } from 'luxon';
|
2024-02-02 04:18:00 +01:00
|
|
|
import { IncomingHttpHeaders } from 'node:http';
|
2023-09-04 21:45:59 +02:00
|
|
|
import { ClientMetadata, Issuer, UserinfoResponse, custom, generators } from 'openid-client';
|
2023-10-30 16:48:38 +01:00
|
|
|
import { AccessCore, Permission } from '../access';
|
2023-10-09 16:25:03 +02:00
|
|
|
import {
|
2023-10-30 16:48:38 +01:00
|
|
|
IAccessRepository,
|
2023-10-09 16:25:03 +02:00
|
|
|
ICryptoRepository,
|
|
|
|
IKeyRepository,
|
|
|
|
ILibraryRepository,
|
|
|
|
ISharedLinkRepository,
|
|
|
|
ISystemConfigRepository,
|
|
|
|
IUserRepository,
|
|
|
|
IUserTokenRepository,
|
|
|
|
} from '../repositories';
|
2023-07-15 06:03:56 +02:00
|
|
|
import { SystemConfigCore } from '../system-config/system-config.core';
|
2023-10-30 22:02:36 +01:00
|
|
|
import { UserCore, UserResponseDto, mapUser } from '../user';
|
2023-07-15 06:03:56 +02:00
|
|
|
import {
|
|
|
|
AuthType,
|
|
|
|
IMMICH_ACCESS_COOKIE,
|
|
|
|
IMMICH_API_KEY_HEADER,
|
|
|
|
IMMICH_AUTH_TYPE_COOKIE,
|
|
|
|
LOGIN_URL,
|
|
|
|
MOBILE_REDIRECT,
|
|
|
|
} from './auth.constant';
|
2023-06-16 21:54:17 +02:00
|
|
|
import {
|
|
|
|
AuthDeviceResponseDto,
|
2023-12-10 05:34:12 +01:00
|
|
|
AuthDto,
|
2023-11-09 16:14:15 +01:00
|
|
|
ChangePasswordDto,
|
|
|
|
LoginCredentialDto,
|
2023-06-16 21:54:17 +02:00
|
|
|
LoginResponseDto,
|
|
|
|
LogoutResponseDto,
|
2023-09-04 21:45:59 +02:00
|
|
|
OAuthAuthorizeResponseDto,
|
2023-11-09 16:14:15 +01:00
|
|
|
OAuthCallbackDto,
|
|
|
|
OAuthConfigDto,
|
|
|
|
SignUpDto,
|
2023-07-15 06:03:56 +02:00
|
|
|
mapLoginResponse,
|
2023-06-16 21:54:17 +02:00
|
|
|
mapUserToken,
|
2023-11-09 16:14:15 +01:00
|
|
|
} from './auth.dto';
|
2023-07-15 06:03:56 +02:00
|
|
|
|
|
|
|
export interface LoginDetails {
|
|
|
|
isSecure: boolean;
|
|
|
|
clientIp: string;
|
|
|
|
deviceType: string;
|
|
|
|
deviceOS: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface LoginResponse {
|
|
|
|
response: LoginResponseDto;
|
|
|
|
cookie: string[];
|
|
|
|
}
|
|
|
|
|
|
|
|
interface OAuthProfile extends UserinfoResponse {
|
|
|
|
email: string;
|
|
|
|
}
|
2023-01-24 05:13:42 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class AuthService {
|
2023-10-30 16:48:38 +01:00
|
|
|
private access: AccessCore;
|
2023-07-15 06:03:56 +02:00
|
|
|
private configCore: SystemConfigCore;
|
2023-12-14 17:55:40 +01:00
|
|
|
private logger = new ImmichLogger(AuthService.name);
|
2023-10-30 16:48:38 +01:00
|
|
|
private userCore: UserCore;
|
2023-01-24 05:13:42 +01:00
|
|
|
|
|
|
|
constructor(
|
2023-10-30 16:48:38 +01:00
|
|
|
@Inject(IAccessRepository) accessRepository: IAccessRepository,
|
2023-07-01 03:49:30 +02:00
|
|
|
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
|
2023-01-24 05:13:42 +01:00
|
|
|
@Inject(ISystemConfigRepository) configRepository: ISystemConfigRepository,
|
2023-10-30 16:48:38 +01:00
|
|
|
@Inject(ILibraryRepository) libraryRepository: ILibraryRepository,
|
2023-10-30 22:02:36 +01:00
|
|
|
@Inject(IUserRepository) private userRepository: IUserRepository,
|
2023-07-15 06:03:56 +02:00
|
|
|
@Inject(IUserTokenRepository) private userTokenRepository: IUserTokenRepository,
|
2023-06-21 03:08:43 +02:00
|
|
|
@Inject(ISharedLinkRepository) private sharedLinkRepository: ISharedLinkRepository,
|
2023-07-01 03:49:30 +02:00
|
|
|
@Inject(IKeyRepository) private keyRepository: IKeyRepository,
|
2023-01-24 05:13:42 +01:00
|
|
|
) {
|
2023-10-30 16:48:38 +01:00
|
|
|
this.access = AccessCore.create(accessRepository);
|
2023-10-09 02:51:03 +02:00
|
|
|
this.configCore = SystemConfigCore.create(configRepository);
|
2023-10-23 14:38:48 +02:00
|
|
|
this.userCore = UserCore.create(cryptoRepository, libraryRepository, userRepository);
|
2023-07-15 06:03:56 +02:00
|
|
|
|
2024-02-02 04:18:00 +01:00
|
|
|
custom.setHttpOptionsDefaults({ timeout: 30_000 });
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-07-15 06:03:56 +02:00
|
|
|
async login(dto: LoginCredentialDto, details: LoginDetails): Promise<LoginResponse> {
|
|
|
|
const config = await this.configCore.getConfig();
|
|
|
|
if (!config.passwordLogin.enabled) {
|
2023-01-24 05:13:42 +01:00
|
|
|
throw new UnauthorizedException('Password login has been disabled');
|
|
|
|
}
|
|
|
|
|
2023-10-30 22:02:36 +01:00
|
|
|
let user = await this.userRepository.getByEmail(dto.email, true);
|
2023-01-24 05:13:42 +01:00
|
|
|
if (user) {
|
2023-07-15 06:03:56 +02:00
|
|
|
const isAuthenticated = this.validatePassword(dto.password, user);
|
2023-01-24 05:13:42 +01:00
|
|
|
if (!isAuthenticated) {
|
|
|
|
user = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!user) {
|
2023-07-15 06:03:56 +02:00
|
|
|
this.logger.warn(`Failed login attempt for user ${dto.email} from ip address ${details.clientIp}`);
|
2023-08-01 17:49:50 +02:00
|
|
|
throw new UnauthorizedException('Incorrect email or password');
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-07-15 06:03:56 +02:00
|
|
|
return this.createLoginResponse(user, AuthType.PASSWORD, details);
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async logout(auth: AuthDto, authType: AuthType): Promise<LogoutResponseDto> {
|
|
|
|
if (auth.userToken) {
|
|
|
|
await this.userTokenRepository.delete(auth.userToken.id);
|
2023-02-06 06:31:16 +01:00
|
|
|
}
|
|
|
|
|
2023-07-15 06:03:56 +02:00
|
|
|
return {
|
|
|
|
successful: true,
|
|
|
|
redirectUri: await this.getLogoutEndpoint(authType),
|
|
|
|
};
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async changePassword(auth: AuthDto, dto: ChangePasswordDto) {
|
2023-01-24 05:13:42 +01:00
|
|
|
const { password, newPassword } = dto;
|
2023-12-10 05:34:12 +01:00
|
|
|
const user = await this.userRepository.getByEmail(auth.user.email, true);
|
2023-01-24 05:13:42 +01:00
|
|
|
if (!user) {
|
|
|
|
throw new UnauthorizedException();
|
|
|
|
}
|
|
|
|
|
2023-07-15 06:03:56 +02:00
|
|
|
const valid = this.validatePassword(password, user);
|
2023-01-24 05:13:42 +01:00
|
|
|
if (!valid) {
|
|
|
|
throw new BadRequestException('Wrong password');
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
return this.userCore.updateUser(auth.user, auth.user.id, { password: newPassword });
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-11-09 16:14:15 +01:00
|
|
|
async adminSignUp(dto: SignUpDto): Promise<UserResponseDto> {
|
2023-10-30 22:02:36 +01:00
|
|
|
const adminUser = await this.userRepository.getAdmin();
|
2023-01-24 05:13:42 +01:00
|
|
|
|
|
|
|
if (adminUser) {
|
|
|
|
throw new BadRequestException('The server already has an admin');
|
|
|
|
}
|
|
|
|
|
2023-08-01 17:49:50 +02:00
|
|
|
const admin = await this.userCore.createUser({
|
|
|
|
isAdmin: true,
|
|
|
|
email: dto.email,
|
2023-11-12 02:03:32 +01:00
|
|
|
name: dto.name,
|
2023-08-01 17:49:50 +02:00
|
|
|
password: dto.password,
|
|
|
|
storageLabel: 'admin',
|
|
|
|
});
|
|
|
|
|
2023-11-09 16:14:15 +01:00
|
|
|
return mapUser(admin);
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async validate(headers: IncomingHttpHeaders, params: Record<string, string>): Promise<AuthDto> {
|
2023-01-31 19:11:49 +01:00
|
|
|
const shareKey = (headers['x-immich-share-key'] || params.key) as string;
|
|
|
|
const userToken = (headers['x-immich-user-token'] ||
|
|
|
|
params.userToken ||
|
|
|
|
this.getBearerToken(headers) ||
|
|
|
|
this.getCookieToken(headers)) as string;
|
2023-05-04 18:41:29 +02:00
|
|
|
const apiKey = (headers[IMMICH_API_KEY_HEADER] || params.apiKey) as string;
|
2023-01-31 19:11:49 +01:00
|
|
|
|
|
|
|
if (shareKey) {
|
2023-06-21 03:08:43 +02:00
|
|
|
return this.validateSharedLink(shareKey);
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-01-31 19:11:49 +01:00
|
|
|
if (userToken) {
|
2023-07-15 06:03:56 +02:00
|
|
|
return this.validateUserToken(userToken);
|
2023-01-31 19:11:49 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (apiKey) {
|
2023-07-01 03:49:30 +02:00
|
|
|
return this.validateApiKey(apiKey);
|
2023-01-31 19:11:49 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new UnauthorizedException('Authentication required');
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async getDevices(auth: AuthDto): Promise<AuthDeviceResponseDto[]> {
|
|
|
|
const userTokens = await this.userTokenRepository.getAll(auth.user.id);
|
|
|
|
return userTokens.map((userToken) => mapUserToken(userToken, auth.userToken?.id));
|
2023-04-26 04:19:23 +02:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async logoutDevice(auth: AuthDto, id: string): Promise<void> {
|
|
|
|
await this.access.requirePermission(auth, Permission.AUTH_DEVICE_DELETE, id);
|
2023-10-30 16:48:38 +01:00
|
|
|
await this.userTokenRepository.delete(id);
|
2023-04-26 04:19:23 +02:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async logoutDevices(auth: AuthDto): Promise<void> {
|
|
|
|
const devices = await this.userTokenRepository.getAll(auth.user.id);
|
2023-05-09 21:34:17 +02:00
|
|
|
for (const device of devices) {
|
2023-12-10 05:34:12 +01:00
|
|
|
if (device.id === auth.userToken?.id) {
|
2023-05-09 21:34:17 +02:00
|
|
|
continue;
|
|
|
|
}
|
2023-10-30 16:48:38 +01:00
|
|
|
await this.userTokenRepository.delete(device.id);
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
getMobileRedirect(url: string) {
|
|
|
|
return `${MOBILE_REDIRECT}?${url.split('?')[1] || ''}`;
|
|
|
|
}
|
|
|
|
|
2023-09-01 13:08:42 +02:00
|
|
|
async authorize(dto: OAuthConfigDto): Promise<OAuthAuthorizeResponseDto> {
|
|
|
|
const config = await this.configCore.getConfig();
|
|
|
|
if (!config.oauth.enabled) {
|
|
|
|
throw new BadRequestException('OAuth is not enabled');
|
|
|
|
}
|
|
|
|
|
|
|
|
const client = await this.getOAuthClient(config);
|
2023-10-28 21:35:09 +02:00
|
|
|
const url = client.authorizationUrl({
|
2023-09-01 13:08:42 +02:00
|
|
|
redirect_uri: this.normalize(config, dto.redirectUri),
|
|
|
|
scope: config.oauth.scope,
|
|
|
|
state: generators.state(),
|
|
|
|
});
|
|
|
|
|
|
|
|
return { url };
|
|
|
|
}
|
|
|
|
|
2023-07-15 06:03:56 +02:00
|
|
|
async callback(
|
|
|
|
dto: OAuthCallbackDto,
|
|
|
|
loginDetails: LoginDetails,
|
|
|
|
): Promise<{ response: LoginResponseDto; cookie: string[] }> {
|
|
|
|
const config = await this.configCore.getConfig();
|
|
|
|
const profile = await this.getOAuthProfile(config, dto.url);
|
|
|
|
this.logger.debug(`Logging in with OAuth: ${JSON.stringify(profile)}`);
|
2023-10-30 22:02:36 +01:00
|
|
|
let user = await this.userRepository.getByOAuthId(profile.sub);
|
2023-07-15 06:03:56 +02:00
|
|
|
|
|
|
|
// link existing user
|
|
|
|
if (!user) {
|
2023-10-30 22:02:36 +01:00
|
|
|
const emailUser = await this.userRepository.getByEmail(profile.email);
|
2023-07-15 06:03:56 +02:00
|
|
|
if (emailUser) {
|
2023-10-30 22:02:36 +01:00
|
|
|
user = await this.userRepository.update(emailUser.id, { oauthId: profile.sub });
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// register new user
|
|
|
|
if (!user) {
|
|
|
|
if (!config.oauth.autoRegister) {
|
|
|
|
this.logger.warn(
|
|
|
|
`Unable to register ${profile.email}. To enable set OAuth Auto Register to true in admin settings.`,
|
|
|
|
);
|
|
|
|
throw new BadRequestException(`User does not exist and auto registering is disabled.`);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.logger.log(`Registering new user: ${profile.email}/${profile.sub}`);
|
2023-07-15 21:50:29 +02:00
|
|
|
this.logger.verbose(`OAuth Profile: ${JSON.stringify(profile)}`);
|
|
|
|
|
|
|
|
let storageLabel: string | null = profile[config.oauth.storageLabelClaim as keyof OAuthProfile] as string;
|
|
|
|
if (typeof storageLabel !== 'string') {
|
|
|
|
storageLabel = null;
|
|
|
|
}
|
|
|
|
|
2023-11-12 02:03:32 +01:00
|
|
|
const userName = profile.name ?? `${profile.given_name || ''} ${profile.family_name || ''}`;
|
2023-07-15 06:03:56 +02:00
|
|
|
user = await this.userCore.createUser({
|
2023-11-12 02:03:32 +01:00
|
|
|
name: userName,
|
2023-07-15 06:03:56 +02:00
|
|
|
email: profile.email,
|
|
|
|
oauthId: profile.sub,
|
2023-07-15 21:50:29 +02:00
|
|
|
storageLabel,
|
2023-07-15 06:03:56 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.createLoginResponse(user, AuthType.OAUTH, loginDetails);
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async link(auth: AuthDto, dto: OAuthCallbackDto): Promise<UserResponseDto> {
|
2023-07-15 06:03:56 +02:00
|
|
|
const config = await this.configCore.getConfig();
|
|
|
|
const { sub: oauthId } = await this.getOAuthProfile(config, dto.url);
|
2023-10-30 22:02:36 +01:00
|
|
|
const duplicate = await this.userRepository.getByOAuthId(oauthId);
|
2023-12-10 05:34:12 +01:00
|
|
|
if (duplicate && duplicate.id !== auth.user.id) {
|
2023-07-15 06:03:56 +02:00
|
|
|
this.logger.warn(`OAuth link account failed: sub is already linked to another user (${duplicate.email}).`);
|
|
|
|
throw new BadRequestException('This OAuth account has already been linked to another user.');
|
|
|
|
}
|
2023-12-10 05:34:12 +01:00
|
|
|
return mapUser(await this.userRepository.update(auth.user.id, { oauthId }));
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async unlink(auth: AuthDto): Promise<UserResponseDto> {
|
|
|
|
return mapUser(await this.userRepository.update(auth.user.id, { oauthId: '' }));
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private async getLogoutEndpoint(authType: AuthType): Promise<string> {
|
|
|
|
if (authType !== AuthType.OAUTH) {
|
|
|
|
return LOGIN_URL;
|
2023-05-09 21:34:17 +02:00
|
|
|
}
|
2023-07-15 06:03:56 +02:00
|
|
|
|
|
|
|
const config = await this.configCore.getConfig();
|
|
|
|
if (!config.oauth.enabled) {
|
|
|
|
return LOGIN_URL;
|
|
|
|
}
|
|
|
|
|
|
|
|
const client = await this.getOAuthClient(config);
|
|
|
|
return client.issuer.metadata.end_session_endpoint || LOGIN_URL;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async getOAuthProfile(config: SystemConfig, url: string): Promise<OAuthProfile> {
|
|
|
|
const redirectUri = this.normalize(config, url.split('?')[0]);
|
|
|
|
const client = await this.getOAuthClient(config);
|
|
|
|
const params = client.callbackParams(url);
|
2024-02-02 06:27:54 +01:00
|
|
|
try {
|
|
|
|
const tokens = await client.callback(redirectUri, params, { state: params.state });
|
|
|
|
return client.userinfo<OAuthProfile>(tokens.access_token || '');
|
|
|
|
} catch (error: Error | any) {
|
|
|
|
if (error.message.includes('unexpected JWT alg received')) {
|
|
|
|
this.logger.warn(
|
|
|
|
[
|
|
|
|
'Algorithm mismatch. Make sure the signing algorithm is set correctly in the OAuth settings.',
|
|
|
|
'Or, that you have specified a signing key in your OAuth provider.',
|
|
|
|
].join(' '),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw error;
|
|
|
|
}
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private async getOAuthClient(config: SystemConfig) {
|
2024-02-02 06:27:54 +01:00
|
|
|
const { enabled, clientId, clientSecret, issuerUrl, signingAlgorithm } = config.oauth;
|
2023-07-15 06:03:56 +02:00
|
|
|
|
|
|
|
if (!enabled) {
|
|
|
|
throw new BadRequestException('OAuth2 is not enabled');
|
|
|
|
}
|
|
|
|
|
|
|
|
const metadata: ClientMetadata = {
|
|
|
|
client_id: clientId,
|
|
|
|
client_secret: clientSecret,
|
|
|
|
response_types: ['code'],
|
|
|
|
};
|
|
|
|
|
2023-10-28 21:35:09 +02:00
|
|
|
try {
|
|
|
|
const issuer = await Issuer.discover(issuerUrl);
|
2024-02-02 06:27:54 +01:00
|
|
|
metadata.id_token_signed_response_alg = signingAlgorithm;
|
2023-07-15 06:03:56 +02:00
|
|
|
|
2023-10-28 21:35:09 +02:00
|
|
|
return new issuer.Client(metadata);
|
2023-10-30 18:22:30 +01:00
|
|
|
} catch (error: any | AggregateError) {
|
|
|
|
this.logger.error(`Error in OAuth discovery: ${error}`, error?.stack, error?.errors);
|
2023-10-28 21:35:09 +02:00
|
|
|
throw new InternalServerErrorException(`Error in OAuth discovery: ${error}`, { cause: error });
|
|
|
|
}
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private normalize(config: SystemConfig, redirectUri: string) {
|
|
|
|
const isMobile = redirectUri.startsWith(MOBILE_REDIRECT);
|
|
|
|
const { mobileRedirectUri, mobileOverrideEnabled } = config.oauth;
|
|
|
|
if (isMobile && mobileOverrideEnabled && mobileRedirectUri) {
|
|
|
|
return mobileRedirectUri;
|
|
|
|
}
|
|
|
|
return redirectUri;
|
2023-05-09 21:34:17 +02:00
|
|
|
}
|
|
|
|
|
2023-01-31 19:11:49 +01:00
|
|
|
private getBearerToken(headers: IncomingHttpHeaders): string | null {
|
|
|
|
const [type, token] = (headers.authorization || '').split(' ');
|
|
|
|
if (type.toLowerCase() === 'bearer') {
|
|
|
|
return token;
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-01-28 06:12:11 +01:00
|
|
|
return null;
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
|
|
|
|
2023-01-31 19:11:49 +01:00
|
|
|
private getCookieToken(headers: IncomingHttpHeaders): string | null {
|
|
|
|
const cookies = cookieParser.parse(headers.cookie || '');
|
|
|
|
return cookies[IMMICH_ACCESS_COOKIE] || null;
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|
2023-06-21 03:08:43 +02:00
|
|
|
|
2023-12-11 20:37:47 +01:00
|
|
|
async validateSharedLink(key: string | string[]): Promise<AuthDto> {
|
2023-06-21 03:08:43 +02:00
|
|
|
key = Array.isArray(key) ? key[0] : key;
|
|
|
|
|
|
|
|
const bytes = Buffer.from(key, key.length === 100 ? 'hex' : 'base64url');
|
2023-12-10 05:34:12 +01:00
|
|
|
const sharedLink = await this.sharedLinkRepository.getByKey(bytes);
|
2024-02-02 04:18:00 +01:00
|
|
|
if (sharedLink && (!sharedLink.expiresAt || new Date(sharedLink.expiresAt) > new Date())) {
|
|
|
|
const user = sharedLink.user;
|
|
|
|
if (user) {
|
|
|
|
return { user, sharedLink };
|
2023-06-21 03:08:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
throw new UnauthorizedException('Invalid share key');
|
|
|
|
}
|
2023-07-01 03:49:30 +02:00
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
private async validateApiKey(key: string): Promise<AuthDto> {
|
2023-07-01 03:49:30 +02:00
|
|
|
const hashedKey = this.cryptoRepository.hashSha256(key);
|
2023-12-10 05:34:12 +01:00
|
|
|
const apiKey = await this.keyRepository.getKey(hashedKey);
|
|
|
|
if (apiKey?.user) {
|
|
|
|
return { user: apiKey.user, apiKey };
|
2023-07-01 03:49:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new UnauthorizedException('Invalid API key');
|
|
|
|
}
|
2023-07-15 06:03:56 +02:00
|
|
|
|
|
|
|
private validatePassword(inputPassword: string, user: UserEntity): boolean {
|
|
|
|
if (!user || !user.password) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return this.cryptoRepository.compareBcrypt(inputPassword, user.password);
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
private async validateUserToken(tokenValue: string): Promise<AuthDto> {
|
2023-07-15 06:03:56 +02:00
|
|
|
const hashedToken = this.cryptoRepository.hashSha256(tokenValue);
|
2023-12-10 05:34:12 +01:00
|
|
|
let userToken = await this.userTokenRepository.getByToken(hashedToken);
|
2023-07-15 06:03:56 +02:00
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
if (userToken?.user) {
|
2023-07-15 06:03:56 +02:00
|
|
|
const now = DateTime.now();
|
2023-12-10 05:34:12 +01:00
|
|
|
const updatedAt = DateTime.fromJSDate(userToken.updatedAt);
|
2023-07-15 06:03:56 +02:00
|
|
|
const diff = now.diff(updatedAt, ['hours']);
|
|
|
|
if (diff.hours > 1) {
|
2023-12-10 05:34:12 +01:00
|
|
|
userToken = await this.userTokenRepository.save({ ...userToken, updatedAt: new Date() });
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
return { user: userToken.user, userToken };
|
2023-07-15 06:03:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new UnauthorizedException('Invalid user token');
|
|
|
|
}
|
|
|
|
|
|
|
|
private async createLoginResponse(user: UserEntity, authType: AuthType, loginDetails: LoginDetails) {
|
2024-02-02 04:18:00 +01:00
|
|
|
const key = this.cryptoRepository.randomBytes(32).toString('base64').replaceAll(/\W/g, '');
|
2023-07-15 06:03:56 +02:00
|
|
|
const token = this.cryptoRepository.hashSha256(key);
|
|
|
|
|
|
|
|
await this.userTokenRepository.create({
|
|
|
|
token,
|
|
|
|
user,
|
|
|
|
deviceOS: loginDetails.deviceOS,
|
|
|
|
deviceType: loginDetails.deviceType,
|
|
|
|
});
|
|
|
|
|
|
|
|
const response = mapLoginResponse(user, key);
|
|
|
|
const cookie = this.getCookies(response, authType, loginDetails);
|
|
|
|
return { response, cookie };
|
|
|
|
}
|
|
|
|
|
|
|
|
private getCookies(loginResponse: LoginResponseDto, authType: AuthType, { isSecure }: LoginDetails) {
|
|
|
|
const maxAge = 400 * 24 * 3600; // 400 days
|
|
|
|
|
|
|
|
let authTypeCookie = '';
|
|
|
|
let accessTokenCookie = '';
|
|
|
|
|
|
|
|
if (isSecure) {
|
|
|
|
accessTokenCookie = `${IMMICH_ACCESS_COOKIE}=${loginResponse.accessToken}; HttpOnly; Secure; Path=/; Max-Age=${maxAge}; SameSite=Lax;`;
|
|
|
|
authTypeCookie = `${IMMICH_AUTH_TYPE_COOKIE}=${authType}; HttpOnly; Secure; Path=/; Max-Age=${maxAge}; SameSite=Lax;`;
|
|
|
|
} else {
|
|
|
|
accessTokenCookie = `${IMMICH_ACCESS_COOKIE}=${loginResponse.accessToken}; HttpOnly; Path=/; Max-Age=${maxAge}; SameSite=Lax;`;
|
|
|
|
authTypeCookie = `${IMMICH_AUTH_TYPE_COOKIE}=${authType}; HttpOnly; Path=/; Max-Age=${maxAge}; SameSite=Lax;`;
|
|
|
|
}
|
|
|
|
return [accessTokenCookie, authTypeCookie];
|
|
|
|
}
|
2023-01-24 05:13:42 +01:00
|
|
|
}
|