mirror of
https://github.com/immich-app/immich
synced 2025-11-14 17:36:12 +00:00
feat(server): mobile oauth with custom scheme redirect uri (#1204)
* feat(server): support providers without support for custom schemas * chore: unit tests * chore: test mobile override * chore: add details to the docs
This commit is contained in:
parent
0b65bb7e9a
commit
6974d4068b
22 changed files with 459 additions and 188 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { Body, Controller, Post, Res, ValidationPipe } from '@nestjs/common';
|
||||
import { Body, Controller, Get, HttpStatus, Post, Redirect, Req, Res, ValidationPipe } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Response } from 'express';
|
||||
import { Request, Response } from 'express';
|
||||
import { AuthType } from '../../constants/jwt.constant';
|
||||
import { AuthUserDto, GetAuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { Authenticated } from '../../decorators/authenticated.decorator';
|
||||
|
|
@ -9,7 +9,7 @@ import { LoginResponseDto } from '../auth/response-dto/login-response.dto';
|
|||
import { UserResponseDto } from '../user/response-dto/user-response.dto';
|
||||
import { OAuthCallbackDto } from './dto/oauth-auth-code.dto';
|
||||
import { OAuthConfigDto } from './dto/oauth-config.dto';
|
||||
import { OAuthService } from './oauth.service';
|
||||
import { MOBILE_REDIRECT, OAuthService } from './oauth.service';
|
||||
import { OAuthConfigResponseDto } from './response-dto/oauth-config-response.dto';
|
||||
|
||||
@ApiTags('OAuth')
|
||||
|
|
@ -17,12 +17,19 @@ import { OAuthConfigResponseDto } from './response-dto/oauth-config-response.dto
|
|||
export class OAuthController {
|
||||
constructor(private readonly immichJwtService: ImmichJwtService, private readonly oauthService: OAuthService) {}
|
||||
|
||||
@Post('/config')
|
||||
@Get('mobile-redirect')
|
||||
@Redirect()
|
||||
public mobileRedirect(@Req() req: Request) {
|
||||
const url = `${MOBILE_REDIRECT}?${req.url.split('?')[1] || ''}`;
|
||||
return { url, statusCode: HttpStatus.TEMPORARY_REDIRECT };
|
||||
}
|
||||
|
||||
@Post('config')
|
||||
public generateConfig(@Body(ValidationPipe) dto: OAuthConfigDto): Promise<OAuthConfigResponseDto> {
|
||||
return this.oauthService.generateConfig(dto);
|
||||
}
|
||||
|
||||
@Post('/callback')
|
||||
@Post('callback')
|
||||
public async callback(
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
@Body(ValidationPipe) dto: OAuthCallbackDto,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,38 @@ import { IUserRepository } from '../user/user-repository';
|
|||
const email = 'user@immich.com';
|
||||
const sub = 'my-auth-user-sub';
|
||||
|
||||
const config = {
|
||||
disabled: {
|
||||
oauth: {
|
||||
enabled: false,
|
||||
buttonText: 'OAuth',
|
||||
issuerUrl: 'http://issuer,',
|
||||
},
|
||||
} as SystemConfig,
|
||||
enabled: {
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: true,
|
||||
buttonText: 'OAuth',
|
||||
},
|
||||
} as SystemConfig,
|
||||
noAutoRegister: {
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: false,
|
||||
},
|
||||
} as SystemConfig,
|
||||
override: {
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: true,
|
||||
buttonText: 'OAuth',
|
||||
mobileOverrideEnabled: true,
|
||||
mobileRedirectUri: 'http://mobile-redirect',
|
||||
},
|
||||
} as SystemConfig,
|
||||
};
|
||||
|
||||
const user = {
|
||||
id: 'user_id',
|
||||
email,
|
||||
|
|
@ -49,8 +81,11 @@ describe('OAuthService', () => {
|
|||
let userRepositoryMock: jest.Mocked<IUserRepository>;
|
||||
let immichConfigServiceMock: jest.Mocked<ImmichConfigService>;
|
||||
let immichJwtServiceMock: jest.Mocked<ImmichJwtService>;
|
||||
let callbackMock: jest.Mock;
|
||||
|
||||
beforeEach(async () => {
|
||||
callbackMock = jest.fn().mockReturnValue({ access_token: 'access-token' });
|
||||
|
||||
jest.spyOn(generators, 'state').mockReturnValue('state');
|
||||
jest.spyOn(Issuer, 'discover').mockResolvedValue({
|
||||
id_token_signing_alg_values_supported: ['HS256'],
|
||||
|
|
@ -62,7 +97,7 @@ describe('OAuthService', () => {
|
|||
},
|
||||
authorizationUrl: jest.fn().mockReturnValue('http://authorization-url'),
|
||||
callbackParams: jest.fn().mockReturnValue({ state: 'state' }),
|
||||
callback: jest.fn().mockReturnValue({ access_token: 'access-token' }),
|
||||
callback: callbackMock,
|
||||
userinfo: jest.fn().mockResolvedValue({ sub, email }),
|
||||
}),
|
||||
} as any);
|
||||
|
|
@ -89,10 +124,11 @@ describe('OAuthService', () => {
|
|||
} as unknown as jest.Mocked<ImmichJwtService>;
|
||||
|
||||
immichConfigServiceMock = {
|
||||
config$: { subscribe: jest.fn() },
|
||||
getConfig: jest.fn().mockResolvedValue({ oauth: { enabled: false } }),
|
||||
} as unknown as jest.Mocked<ImmichConfigService>;
|
||||
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.disabled);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
|
|
@ -102,17 +138,10 @@ describe('OAuthService', () => {
|
|||
describe('generateConfig', () => {
|
||||
it('should work when oauth is not configured', async () => {
|
||||
await expect(sut.generateConfig({ redirectUri: 'http://callback' })).resolves.toEqual({ enabled: false });
|
||||
expect(immichConfigServiceMock.getConfig).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should generate the config', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
buttonText: 'OAuth',
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
|
||||
await expect(sut.generateConfig({ redirectUri: 'http://redirect' })).resolves.toEqual({
|
||||
enabled: true,
|
||||
buttonText: 'OAuth',
|
||||
|
|
@ -127,13 +156,7 @@ describe('OAuthService', () => {
|
|||
});
|
||||
|
||||
it('should not allow auto registering', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: false,
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.noAutoRegister);
|
||||
userRepositoryMock.getByEmail.mockResolvedValue(null);
|
||||
await expect(sut.login({ url: 'http://immich/auth/login?code=abc123' })).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
|
|
@ -142,13 +165,7 @@ describe('OAuthService', () => {
|
|||
});
|
||||
|
||||
it('should link an existing user', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: false,
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.noAutoRegister);
|
||||
userRepositoryMock.getByEmail.mockResolvedValue(user);
|
||||
userRepositoryMock.update.mockResolvedValue(user);
|
||||
immichJwtServiceMock.createLoginResponse.mockResolvedValue(loginResponse);
|
||||
|
|
@ -160,13 +177,8 @@ describe('OAuthService', () => {
|
|||
});
|
||||
|
||||
it('should allow auto registering by default', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: true,
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
|
||||
|
||||
userRepositoryMock.getByEmail.mockResolvedValue(null);
|
||||
userRepositoryMock.getAdmin.mockResolvedValue(user);
|
||||
userRepositoryMock.create.mockResolvedValue(user);
|
||||
|
|
@ -178,16 +190,21 @@ describe('OAuthService', () => {
|
|||
expect(userRepositoryMock.create).toHaveBeenCalledTimes(1);
|
||||
expect(immichJwtServiceMock.createLoginResponse).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should use the mobile redirect override', async () => {
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.override);
|
||||
|
||||
userRepositoryMock.getByOAuthId.mockResolvedValue(user);
|
||||
|
||||
await sut.login({ url: `app.immich:/?code=abc123` });
|
||||
|
||||
expect(callbackMock).toHaveBeenCalledWith('http://mobile-redirect', { state: 'state' }, { state: 'state' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('link', () => {
|
||||
it('should link an account', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: true,
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
|
||||
|
||||
userRepositoryMock.update.mockResolvedValue(user);
|
||||
|
||||
|
|
@ -197,12 +214,7 @@ describe('OAuthService', () => {
|
|||
});
|
||||
|
||||
it('should not link an already linked oauth.sub', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: true,
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
|
||||
|
||||
userRepositoryMock.getByOAuthId.mockResolvedValue({ id: 'other-user' } as UserEntity);
|
||||
|
||||
|
|
@ -216,12 +228,7 @@ describe('OAuthService', () => {
|
|||
|
||||
describe('unlink', () => {
|
||||
it('should unlink an account', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
autoRegister: true,
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
|
||||
|
||||
userRepositoryMock.update.mockResolvedValue(user);
|
||||
|
||||
|
|
@ -237,13 +244,7 @@ describe('OAuthService', () => {
|
|||
});
|
||||
|
||||
it('should get the session endpoint from the discovery document', async () => {
|
||||
immichConfigServiceMock.getConfig.mockResolvedValue({
|
||||
oauth: {
|
||||
enabled: true,
|
||||
issuerUrl: 'http://issuer,',
|
||||
},
|
||||
} as SystemConfig);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
|
||||
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
|
||||
|
||||
await expect(sut.getLogoutEndpoint()).resolves.toBe('http://end-session-endpoint');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { ImmichConfigService } from '@app/immich-config';
|
||||
import { SystemConfig } from '@app/database/entities/system-config.entity';
|
||||
import { ImmichConfigService, INITIAL_SYSTEM_CONFIG } from '@app/immich-config';
|
||||
import { BadRequestException, Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import { ClientMetadata, custom, generators, Issuer, UserinfoResponse } from 'openid-client';
|
||||
import { AuthUserDto } from '../../decorators/auth-user.decorator';
|
||||
|
|
@ -15,6 +16,8 @@ type OAuthProfile = UserinfoResponse & {
|
|||
email: string;
|
||||
};
|
||||
|
||||
export const MOBILE_REDIRECT = 'app.immich:/';
|
||||
|
||||
@Injectable()
|
||||
export class OAuthService {
|
||||
private readonly userCore: UserCore;
|
||||
|
|
@ -22,26 +25,29 @@ export class OAuthService {
|
|||
|
||||
constructor(
|
||||
private immichJwtService: ImmichJwtService,
|
||||
private immichConfigService: ImmichConfigService,
|
||||
immichConfigService: ImmichConfigService,
|
||||
@Inject(USER_REPOSITORY) userRepository: IUserRepository,
|
||||
@Inject(INITIAL_SYSTEM_CONFIG) private config: SystemConfig,
|
||||
) {
|
||||
this.userCore = new UserCore(userRepository);
|
||||
|
||||
custom.setHttpOptionsDefaults({
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
immichConfigService.config$.subscribe((config) => (this.config = config));
|
||||
}
|
||||
|
||||
public async generateConfig(dto: OAuthConfigDto): Promise<OAuthConfigResponseDto> {
|
||||
const config = await this.immichConfigService.getConfig();
|
||||
const { enabled, scope, buttonText } = config.oauth;
|
||||
const { enabled, scope, buttonText } = this.config.oauth;
|
||||
const redirectUri = this.normalize(dto.redirectUri);
|
||||
|
||||
if (!enabled) {
|
||||
return { enabled: false };
|
||||
}
|
||||
|
||||
const url = (await this.getClient()).authorizationUrl({
|
||||
redirect_uri: dto.redirectUri,
|
||||
redirect_uri: redirectUri,
|
||||
scope,
|
||||
state: generators.state(),
|
||||
});
|
||||
|
|
@ -64,9 +70,7 @@ export class OAuthService {
|
|||
|
||||
// register new user
|
||||
if (!user) {
|
||||
const config = await this.immichConfigService.getConfig();
|
||||
const { autoRegister } = config.oauth;
|
||||
if (!autoRegister) {
|
||||
if (!this.config.oauth.autoRegister) {
|
||||
this.logger.warn(
|
||||
`Unable to register ${profile.email}. To enable set OAuth Auto Register to true in admin settings.`,
|
||||
);
|
||||
|
|
@ -100,17 +104,14 @@ export class OAuthService {
|
|||
}
|
||||
|
||||
public async getLogoutEndpoint(): Promise<string | null> {
|
||||
const config = await this.immichConfigService.getConfig();
|
||||
const { enabled } = config.oauth;
|
||||
|
||||
if (!enabled) {
|
||||
if (!this.config.oauth.enabled) {
|
||||
return null;
|
||||
}
|
||||
return (await this.getClient()).issuer.metadata.end_session_endpoint || null;
|
||||
}
|
||||
|
||||
private async callback(url: string): Promise<any> {
|
||||
const redirectUri = url.split('?')[0];
|
||||
const redirectUri = this.normalize(url.split('?')[0]);
|
||||
const client = await this.getClient();
|
||||
const params = client.callbackParams(url);
|
||||
const tokens = await client.callback(redirectUri, params, { state: params.state });
|
||||
|
|
@ -118,8 +119,7 @@ export class OAuthService {
|
|||
}
|
||||
|
||||
private async getClient() {
|
||||
const config = await this.immichConfigService.getConfig();
|
||||
const { enabled, clientId, clientSecret, issuerUrl } = config.oauth;
|
||||
const { enabled, clientId, clientSecret, issuerUrl } = this.config.oauth;
|
||||
|
||||
if (!enabled) {
|
||||
throw new BadRequestException('OAuth2 is not enabled');
|
||||
|
|
@ -139,4 +139,13 @@ export class OAuthService {
|
|||
|
||||
return new issuer.Client(metadata);
|
||||
}
|
||||
|
||||
private normalize(redirectUri: string) {
|
||||
const isMobile = redirectUri === MOBILE_REDIRECT;
|
||||
const { mobileRedirectUri, mobileOverrideEnabled } = this.config.oauth;
|
||||
if (isMobile && mobileOverrideEnabled && mobileRedirectUri) {
|
||||
return mobileRedirectUri;
|
||||
}
|
||||
return redirectUri;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { IsBoolean, IsNotEmpty, IsString, ValidateIf } from 'class-validator';
|
||||
import { IsBoolean, IsNotEmpty, IsString, IsUrl, ValidateIf } from 'class-validator';
|
||||
|
||||
const isEnabled = (config: SystemConfigOAuthDto) => config.enabled;
|
||||
const isOverrideEnabled = (config: SystemConfigOAuthDto) => config.mobileOverrideEnabled;
|
||||
|
||||
export class SystemConfigOAuthDto {
|
||||
@IsBoolean()
|
||||
|
|
@ -29,4 +30,11 @@ export class SystemConfigOAuthDto {
|
|||
|
||||
@IsBoolean()
|
||||
autoRegister!: boolean;
|
||||
|
||||
@IsBoolean()
|
||||
mobileOverrideEnabled!: boolean;
|
||||
|
||||
@ValidateIf(isOverrideEnabled)
|
||||
@IsUrl()
|
||||
mobileRedirectUri!: string;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue