1
0
mirror of https://github.com/immich-app/immich.git synced 2024-12-25 10:43:13 +02: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:
Jason Rasmussen 2022-12-29 15:47:30 -05:00 committed by GitHub
parent 0b65bb7e9a
commit 6974d4068b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 351 additions and 184 deletions

View File

@ -2,6 +2,10 @@
This page contains details about using OAuth in Immich. This page contains details about using OAuth in Immich.
:::tip
Unable to set `app.immich:/` as a valid redirect URI? See [Mobile Redirect URI](#mobile-redirect-uri) for an alternative solution.
:::
## Overview ## Overview
Immich supports 3rd party authentication via [OpenID Connect][oidc] (OIDC), an identity layer built on top of OAuth2. OIDC is supported by most identity providers, including: Immich supports 3rd party authentication via [OpenID Connect][oidc] (OIDC), an identity layer built on top of OAuth2. OIDC is supported by most identity providers, including:
@ -24,50 +28,47 @@ Before enabling OAuth in Immich, a new client application needs to be configured
2. Configure Redirect URIs/Origins 2. Configure Redirect URIs/Origins
The **Sign-in redirect URIs** should include: The **Sign-in redirect URIs** should include:
- `app.immich:/` - for logging in with OAuth from the [Mobile App](/docs/features/mobile-app.mdx) - `app.immich:/` - for logging in with OAuth from the [Mobile App](/docs/features/mobile-app.mdx)
- `http://DOMAIN:PORT/auth/login` - for logging in with OAuth from the Web Client - `http://DOMAIN:PORT/auth/login` - for logging in with OAuth from the Web Client
- `http://DOMAIN:PORT/user-settings` - for manually linking OAuth in the Web Client - `http://DOMAIN:PORT/user-settings` - for manually linking OAuth in the Web Client
:::info Redirect URIs Redirect URIs should contain all the domains you will be using to access Immich. Some examples include:
Redirect URIs should contain all the domains you will be using to access Immich. Some examples include: Mobile
Mobile - `app.immich:/` (You **MUST** include this for iOS and Android mobile apps to work properly)
- `app.immich:/` (You **MUST** include this for iOS and Android mobile apps to work properly) Localhost
Localhost - `http://localhost:2283/auth/login`
- `http://localhost:2283/user-settings`
- `http://localhost:2283/auth/login` Local IP
- `http://localhost:2283/user-settings`
Local IP - `http://192.168.0.200:2283/auth/login`
- `http://192.168.0.200:2283/user-settings`
- `http://192.168.0.200:2283/auth/login` Hostname
- `http://192.168.0.200:2283/user-settings`
Hostname - `https://immich.example.com/auth/login`)
- `https://immich.example.com/user-settings`)
- `https://immich.example.com/auth/login`)
- `https://immich.example.com/user-settings`)
:::
## Enable OAuth ## Enable OAuth
Once you have a new OAuth client application configured, Immich can be configured using the Administration Settings page, available on the web (Administration -> Settings). Once you have a new OAuth client application configured, Immich can be configured using the Administration Settings page, available on the web (Administration -> Settings).
| Setting | Type | Default | Description | | Setting | Type | Default | Description |
| ------------- | ------- | -------------------- | ------------------------------------------------------------------------- | | ---------------------------- | ------- | -------------------- | ------------------------------------------------------------------------- |
| Enabled | boolean | false | Enable/disable OAuth | | Enabled | boolean | false | Enable/disable OAuth |
| Issuer URL | URL | (required) | Required. Self-discovery URL for client (from previous step) | | Issuer URL | URL | (required) | Required. Self-discovery URL for client (from previous step) |
| Client ID | string | (required) | Required. Client ID (from previous step) | | Client ID | string | (required) | Required. Client ID (from previous step) |
| Client secret | string | (required) | Required. Client Secret (previous step) | | Client secret | string | (required) | Required. Client Secret (previous step) |
| Scope | string | openid email profile | Full list of scopes to send with the request (space delimited) | | Scope | string | openid email profile | Full list of scopes to send with the request (space delimited) |
| Button text | string | Login with OAuth | Text for the OAuth button on the web | | Button text | string | Login with OAuth | Text for the OAuth button on the web |
| Auto register | boolean | true | When true, will automatically register a user the first time they sign in | | Auto register | boolean | true | When true, will automatically register a user the first time they sign in |
| Mobile Redirect URI Override | URL | (empty) | Http(s) alternative mobile redirect URI |
:::info :::info
The Issuer URL should look something like the following, and return a valid json document. The Issuer URL should look something like the following, and return a valid json document.
@ -78,6 +79,22 @@ The Issuer URL should look something like the following, and return a valid json
The `.well-known/openid-configuration` part of the url is optional and will be automatically added during discovery. The `.well-known/openid-configuration` part of the url is optional and will be automatically added during discovery.
::: :::
## Mobile Redirect URI
The redirect URI for the mobile app is `app.immich:/`, which is a [Custom Scheme](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app). If this custom scheme is an invalid redirect URI for your OAuth Provider, you can work around this by doing the following:
1. Configure an http(s) endpoint to forwards requests to `app.immich:/`
2. Whitelist the new endpoint as a valid redirect URI with your provider.
3. Specify the new endpoint as the `Mobile Redirect URI Override`, in the OAuth settings.
With these steps in place, you should be able to use OAuth from the [Mobile App](/docs/features/mobile-app.mdx) without a custom scheme redirect URI.
:::info
Immich has a route (`/api/oauth/mobile-redirect`) that is already configured to forward requests to `app.immich:/`, and can be used for step 1.
:::
## Example Configuration
Here's an example of OAuth configured for Authentik: Here's an example of OAuth configured for Authentik:
![OAuth Settings](./img/oauth-settings.png) ![OAuth Settings](./img/oauth-settings.png)

BIN
mobile/openapi/README.md generated

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -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 { ApiTags } from '@nestjs/swagger';
import { Response } from 'express'; import { Request, Response } from 'express';
import { AuthType } from '../../constants/jwt.constant'; import { AuthType } from '../../constants/jwt.constant';
import { AuthUserDto, GetAuthUser } from '../../decorators/auth-user.decorator'; import { AuthUserDto, GetAuthUser } from '../../decorators/auth-user.decorator';
import { Authenticated } from '../../decorators/authenticated.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 { UserResponseDto } from '../user/response-dto/user-response.dto';
import { OAuthCallbackDto } from './dto/oauth-auth-code.dto'; import { OAuthCallbackDto } from './dto/oauth-auth-code.dto';
import { OAuthConfigDto } from './dto/oauth-config.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'; import { OAuthConfigResponseDto } from './response-dto/oauth-config-response.dto';
@ApiTags('OAuth') @ApiTags('OAuth')
@ -17,12 +17,19 @@ import { OAuthConfigResponseDto } from './response-dto/oauth-config-response.dto
export class OAuthController { export class OAuthController {
constructor(private readonly immichJwtService: ImmichJwtService, private readonly oauthService: OAuthService) {} 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> { public generateConfig(@Body(ValidationPipe) dto: OAuthConfigDto): Promise<OAuthConfigResponseDto> {
return this.oauthService.generateConfig(dto); return this.oauthService.generateConfig(dto);
} }
@Post('/callback') @Post('callback')
public async callback( public async callback(
@Res({ passthrough: true }) response: Response, @Res({ passthrough: true }) response: Response,
@Body(ValidationPipe) dto: OAuthCallbackDto, @Body(ValidationPipe) dto: OAuthCallbackDto,

View File

@ -12,6 +12,38 @@ import { IUserRepository } from '../user/user-repository';
const email = 'user@immich.com'; const email = 'user@immich.com';
const sub = 'my-auth-user-sub'; 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 = { const user = {
id: 'user_id', id: 'user_id',
email, email,
@ -49,8 +81,11 @@ describe('OAuthService', () => {
let userRepositoryMock: jest.Mocked<IUserRepository>; let userRepositoryMock: jest.Mocked<IUserRepository>;
let immichConfigServiceMock: jest.Mocked<ImmichConfigService>; let immichConfigServiceMock: jest.Mocked<ImmichConfigService>;
let immichJwtServiceMock: jest.Mocked<ImmichJwtService>; let immichJwtServiceMock: jest.Mocked<ImmichJwtService>;
let callbackMock: jest.Mock;
beforeEach(async () => { beforeEach(async () => {
callbackMock = jest.fn().mockReturnValue({ access_token: 'access-token' });
jest.spyOn(generators, 'state').mockReturnValue('state'); jest.spyOn(generators, 'state').mockReturnValue('state');
jest.spyOn(Issuer, 'discover').mockResolvedValue({ jest.spyOn(Issuer, 'discover').mockResolvedValue({
id_token_signing_alg_values_supported: ['HS256'], id_token_signing_alg_values_supported: ['HS256'],
@ -62,7 +97,7 @@ describe('OAuthService', () => {
}, },
authorizationUrl: jest.fn().mockReturnValue('http://authorization-url'), authorizationUrl: jest.fn().mockReturnValue('http://authorization-url'),
callbackParams: jest.fn().mockReturnValue({ state: 'state' }), callbackParams: jest.fn().mockReturnValue({ state: 'state' }),
callback: jest.fn().mockReturnValue({ access_token: 'access-token' }), callback: callbackMock,
userinfo: jest.fn().mockResolvedValue({ sub, email }), userinfo: jest.fn().mockResolvedValue({ sub, email }),
}), }),
} as any); } as any);
@ -89,10 +124,11 @@ describe('OAuthService', () => {
} as unknown as jest.Mocked<ImmichJwtService>; } as unknown as jest.Mocked<ImmichJwtService>;
immichConfigServiceMock = { immichConfigServiceMock = {
config$: { subscribe: jest.fn() },
getConfig: jest.fn().mockResolvedValue({ oauth: { enabled: false } }), getConfig: jest.fn().mockResolvedValue({ oauth: { enabled: false } }),
} as unknown as jest.Mocked<ImmichConfigService>; } as unknown as jest.Mocked<ImmichConfigService>;
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock); sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.disabled);
}); });
it('should be defined', () => { it('should be defined', () => {
@ -102,17 +138,10 @@ describe('OAuthService', () => {
describe('generateConfig', () => { describe('generateConfig', () => {
it('should work when oauth is not configured', async () => { it('should work when oauth is not configured', async () => {
await expect(sut.generateConfig({ redirectUri: 'http://callback' })).resolves.toEqual({ enabled: false }); await expect(sut.generateConfig({ redirectUri: 'http://callback' })).resolves.toEqual({ enabled: false });
expect(immichConfigServiceMock.getConfig).toHaveBeenCalled();
}); });
it('should generate the config', async () => { it('should generate the config', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
oauth: {
enabled: true,
buttonText: 'OAuth',
},
} as SystemConfig);
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
await expect(sut.generateConfig({ redirectUri: 'http://redirect' })).resolves.toEqual({ await expect(sut.generateConfig({ redirectUri: 'http://redirect' })).resolves.toEqual({
enabled: true, enabled: true,
buttonText: 'OAuth', buttonText: 'OAuth',
@ -127,13 +156,7 @@ describe('OAuthService', () => {
}); });
it('should not allow auto registering', async () => { it('should not allow auto registering', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.noAutoRegister);
oauth: {
enabled: true,
autoRegister: false,
},
} as SystemConfig);
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
userRepositoryMock.getByEmail.mockResolvedValue(null); userRepositoryMock.getByEmail.mockResolvedValue(null);
await expect(sut.login({ url: 'http://immich/auth/login?code=abc123' })).rejects.toBeInstanceOf( await expect(sut.login({ url: 'http://immich/auth/login?code=abc123' })).rejects.toBeInstanceOf(
BadRequestException, BadRequestException,
@ -142,13 +165,7 @@ describe('OAuthService', () => {
}); });
it('should link an existing user', async () => { it('should link an existing user', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.noAutoRegister);
oauth: {
enabled: true,
autoRegister: false,
},
} as SystemConfig);
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
userRepositoryMock.getByEmail.mockResolvedValue(user); userRepositoryMock.getByEmail.mockResolvedValue(user);
userRepositoryMock.update.mockResolvedValue(user); userRepositoryMock.update.mockResolvedValue(user);
immichJwtServiceMock.createLoginResponse.mockResolvedValue(loginResponse); immichJwtServiceMock.createLoginResponse.mockResolvedValue(loginResponse);
@ -160,13 +177,8 @@ describe('OAuthService', () => {
}); });
it('should allow auto registering by default', async () => { it('should allow auto registering by default', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
oauth: {
enabled: true,
autoRegister: true,
},
} as SystemConfig);
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
userRepositoryMock.getByEmail.mockResolvedValue(null); userRepositoryMock.getByEmail.mockResolvedValue(null);
userRepositoryMock.getAdmin.mockResolvedValue(user); userRepositoryMock.getAdmin.mockResolvedValue(user);
userRepositoryMock.create.mockResolvedValue(user); userRepositoryMock.create.mockResolvedValue(user);
@ -178,16 +190,21 @@ describe('OAuthService', () => {
expect(userRepositoryMock.create).toHaveBeenCalledTimes(1); expect(userRepositoryMock.create).toHaveBeenCalledTimes(1);
expect(immichJwtServiceMock.createLoginResponse).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', () => { describe('link', () => {
it('should link an account', async () => { it('should link an account', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
oauth: {
enabled: true,
autoRegister: true,
},
} as SystemConfig);
userRepositoryMock.update.mockResolvedValue(user); userRepositoryMock.update.mockResolvedValue(user);
@ -197,12 +214,7 @@ describe('OAuthService', () => {
}); });
it('should not link an already linked oauth.sub', async () => { it('should not link an already linked oauth.sub', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
oauth: {
enabled: true,
autoRegister: true,
},
} as SystemConfig);
userRepositoryMock.getByOAuthId.mockResolvedValue({ id: 'other-user' } as UserEntity); userRepositoryMock.getByOAuthId.mockResolvedValue({ id: 'other-user' } as UserEntity);
@ -216,12 +228,7 @@ describe('OAuthService', () => {
describe('unlink', () => { describe('unlink', () => {
it('should unlink an account', async () => { it('should unlink an account', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
oauth: {
enabled: true,
autoRegister: true,
},
} as SystemConfig);
userRepositoryMock.update.mockResolvedValue(user); userRepositoryMock.update.mockResolvedValue(user);
@ -237,13 +244,7 @@ describe('OAuthService', () => {
}); });
it('should get the session endpoint from the discovery document', async () => { it('should get the session endpoint from the discovery document', async () => {
immichConfigServiceMock.getConfig.mockResolvedValue({ sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock, config.enabled);
oauth: {
enabled: true,
issuerUrl: 'http://issuer,',
},
} as SystemConfig);
sut = new OAuthService(immichJwtServiceMock, immichConfigServiceMock, userRepositoryMock);
await expect(sut.getLogoutEndpoint()).resolves.toBe('http://end-session-endpoint'); await expect(sut.getLogoutEndpoint()).resolves.toBe('http://end-session-endpoint');
}); });

View File

@ -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 { BadRequestException, Inject, Injectable, Logger } from '@nestjs/common';
import { ClientMetadata, custom, generators, Issuer, UserinfoResponse } from 'openid-client'; import { ClientMetadata, custom, generators, Issuer, UserinfoResponse } from 'openid-client';
import { AuthUserDto } from '../../decorators/auth-user.decorator'; import { AuthUserDto } from '../../decorators/auth-user.decorator';
@ -15,6 +16,8 @@ type OAuthProfile = UserinfoResponse & {
email: string; email: string;
}; };
export const MOBILE_REDIRECT = 'app.immich:/';
@Injectable() @Injectable()
export class OAuthService { export class OAuthService {
private readonly userCore: UserCore; private readonly userCore: UserCore;
@ -22,26 +25,29 @@ export class OAuthService {
constructor( constructor(
private immichJwtService: ImmichJwtService, private immichJwtService: ImmichJwtService,
private immichConfigService: ImmichConfigService, immichConfigService: ImmichConfigService,
@Inject(USER_REPOSITORY) userRepository: IUserRepository, @Inject(USER_REPOSITORY) userRepository: IUserRepository,
@Inject(INITIAL_SYSTEM_CONFIG) private config: SystemConfig,
) { ) {
this.userCore = new UserCore(userRepository); this.userCore = new UserCore(userRepository);
custom.setHttpOptionsDefaults({ custom.setHttpOptionsDefaults({
timeout: 30000, timeout: 30000,
}); });
immichConfigService.config$.subscribe((config) => (this.config = config));
} }
public async generateConfig(dto: OAuthConfigDto): Promise<OAuthConfigResponseDto> { public async generateConfig(dto: OAuthConfigDto): Promise<OAuthConfigResponseDto> {
const config = await this.immichConfigService.getConfig(); const { enabled, scope, buttonText } = this.config.oauth;
const { enabled, scope, buttonText } = config.oauth; const redirectUri = this.normalize(dto.redirectUri);
if (!enabled) { if (!enabled) {
return { enabled: false }; return { enabled: false };
} }
const url = (await this.getClient()).authorizationUrl({ const url = (await this.getClient()).authorizationUrl({
redirect_uri: dto.redirectUri, redirect_uri: redirectUri,
scope, scope,
state: generators.state(), state: generators.state(),
}); });
@ -64,9 +70,7 @@ export class OAuthService {
// register new user // register new user
if (!user) { if (!user) {
const config = await this.immichConfigService.getConfig(); if (!this.config.oauth.autoRegister) {
const { autoRegister } = config.oauth;
if (!autoRegister) {
this.logger.warn( this.logger.warn(
`Unable to register ${profile.email}. To enable set OAuth Auto Register to true in admin settings.`, `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> { public async getLogoutEndpoint(): Promise<string | null> {
const config = await this.immichConfigService.getConfig(); if (!this.config.oauth.enabled) {
const { enabled } = config.oauth;
if (!enabled) {
return null; return null;
} }
return (await this.getClient()).issuer.metadata.end_session_endpoint || null; return (await this.getClient()).issuer.metadata.end_session_endpoint || null;
} }
private async callback(url: string): Promise<any> { 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 client = await this.getClient();
const params = client.callbackParams(url); const params = client.callbackParams(url);
const tokens = await client.callback(redirectUri, params, { state: params.state }); const tokens = await client.callback(redirectUri, params, { state: params.state });
@ -118,8 +119,7 @@ export class OAuthService {
} }
private async getClient() { private async getClient() {
const config = await this.immichConfigService.getConfig(); const { enabled, clientId, clientSecret, issuerUrl } = this.config.oauth;
const { enabled, clientId, clientSecret, issuerUrl } = config.oauth;
if (!enabled) { if (!enabled) {
throw new BadRequestException('OAuth2 is not enabled'); throw new BadRequestException('OAuth2 is not enabled');
@ -139,4 +139,13 @@ export class OAuthService {
return new issuer.Client(metadata); 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;
}
} }

View File

@ -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 isEnabled = (config: SystemConfigOAuthDto) => config.enabled;
const isOverrideEnabled = (config: SystemConfigOAuthDto) => config.mobileOverrideEnabled;
export class SystemConfigOAuthDto { export class SystemConfigOAuthDto {
@IsBoolean() @IsBoolean()
@ -29,4 +30,11 @@ export class SystemConfigOAuthDto {
@IsBoolean() @IsBoolean()
autoRegister!: boolean; autoRegister!: boolean;
@IsBoolean()
mobileOverrideEnabled!: boolean;
@ValidateIf(isOverrideEnabled)
@IsUrl()
mobileRedirectUri!: string;
} }

View File

@ -1764,6 +1764,20 @@
] ]
} }
}, },
"/oauth/mobile-redirect": {
"get": {
"operationId": "mobileRedirect",
"parameters": [],
"responses": {
"200": {
"description": ""
}
},
"tags": [
"OAuth"
]
}
},
"/oauth/config": { "/oauth/config": {
"post": { "post": {
"operationId": "generateConfig", "operationId": "generateConfig",
@ -3799,6 +3813,12 @@
}, },
"autoRegister": { "autoRegister": {
"type": "boolean" "type": "boolean"
},
"mobileOverrideEnabled": {
"type": "boolean"
},
"mobileRedirectUri": {
"type": "string"
} }
}, },
"required": [ "required": [
@ -3808,7 +3828,9 @@
"clientSecret", "clientSecret",
"scope", "scope",
"buttonText", "buttonText",
"autoRegister" "autoRegister",
"mobileOverrideEnabled",
"mobileRedirectUri"
] ]
}, },
"SystemConfigStorageTemplateDto": { "SystemConfigStorageTemplateDto": {

View File

@ -25,6 +25,8 @@ export enum SystemConfigKey {
OAUTH_SCOPE = 'oauth.scope', OAUTH_SCOPE = 'oauth.scope',
OAUTH_BUTTON_TEXT = 'oauth.buttonText', OAUTH_BUTTON_TEXT = 'oauth.buttonText',
OAUTH_AUTO_REGISTER = 'oauth.autoRegister', OAUTH_AUTO_REGISTER = 'oauth.autoRegister',
OAUTH_MOBILE_OVERRIDE_ENABLED = 'oauth.mobileOverrideEnabled',
OAUTH_MOBILE_REDIRECT_URI = 'oauth.mobileRedirectUri',
STORAGE_TEMPLATE = 'storageTemplate.template', STORAGE_TEMPLATE = 'storageTemplate.template',
} }
@ -44,6 +46,8 @@ export interface SystemConfig {
scope: string; scope: string;
buttonText: string; buttonText: string;
autoRegister: boolean; autoRegister: boolean;
mobileOverrideEnabled: boolean;
mobileRedirectUri: string;
}; };
storageTemplate: { storageTemplate: {
template: string; template: string;

View File

@ -20,6 +20,8 @@ const defaults: SystemConfig = Object.freeze({
issuerUrl: '', issuerUrl: '',
clientId: '', clientId: '',
clientSecret: '', clientSecret: '',
mobileOverrideEnabled: false,
mobileRedirectUri: '',
scope: 'openid email profile', scope: 'openid email profile',
buttonText: 'Login with OAuth', buttonText: 'Login with OAuth',
autoRegister: true, autoRegister: true,

View File

@ -4,7 +4,7 @@
* Immich * Immich
* Immich API * Immich API
* *
* The version of the OpenAPI document: 1.39.0 * The version of the OpenAPI document: 1.40.0
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
@ -1567,6 +1567,18 @@ export interface SystemConfigOAuthDto {
* @memberof SystemConfigOAuthDto * @memberof SystemConfigOAuthDto
*/ */
'autoRegister': boolean; 'autoRegister': boolean;
/**
*
* @type {boolean}
* @memberof SystemConfigOAuthDto
*/
'mobileOverrideEnabled': boolean;
/**
*
* @type {string}
* @memberof SystemConfigOAuthDto
*/
'mobileRedirectUri': string;
} }
/** /**
* *
@ -5111,6 +5123,35 @@ export const OAuthApiAxiosParamCreator = function (configuration?: Configuration
options: localVarRequestOptions, options: localVarRequestOptions,
}; };
}, },
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
mobileRedirect: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/oauth/mobile-redirect`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/** /**
* *
* @param {*} [options] Override http request option. * @param {*} [options] Override http request option.
@ -5180,6 +5221,15 @@ export const OAuthApiFp = function(configuration?: Configuration) {
const localVarAxiosArgs = await localVarAxiosParamCreator.link(oAuthCallbackDto, options); const localVarAxiosArgs = await localVarAxiosParamCreator.link(oAuthCallbackDto, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
}, },
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async mobileRedirect(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.mobileRedirect(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/** /**
* *
* @param {*} [options] Override http request option. * @param {*} [options] Override http request option.
@ -5226,6 +5276,14 @@ export const OAuthApiFactory = function (configuration?: Configuration, basePath
link(oAuthCallbackDto: OAuthCallbackDto, options?: any): AxiosPromise<UserResponseDto> { link(oAuthCallbackDto: OAuthCallbackDto, options?: any): AxiosPromise<UserResponseDto> {
return localVarFp.link(oAuthCallbackDto, options).then((request) => request(axios, basePath)); return localVarFp.link(oAuthCallbackDto, options).then((request) => request(axios, basePath));
}, },
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
mobileRedirect(options?: any): AxiosPromise<void> {
return localVarFp.mobileRedirect(options).then((request) => request(axios, basePath));
},
/** /**
* *
* @param {*} [options] Override http request option. * @param {*} [options] Override http request option.
@ -5277,6 +5335,16 @@ export class OAuthApi extends BaseAPI {
return OAuthApiFp(this.configuration).link(oAuthCallbackDto, options).then((request) => request(this.axios, this.basePath)); return OAuthApiFp(this.configuration).link(oAuthCallbackDto, options).then((request) => request(this.axios, this.basePath));
} }
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OAuthApi
*/
public mobileRedirect(options?: AxiosRequestConfig) {
return OAuthApiFp(this.configuration).mobileRedirect(options).then((request) => request(this.axios, this.basePath));
}
/** /**
* *
* @param {*} [options] Override http request option. * @param {*} [options] Override http request option.

View File

@ -4,7 +4,7 @@
* Immich * Immich
* Immich API * Immich API
* *
* The version of the OpenAPI document: 1.39.0 * The version of the OpenAPI document: 1.40.0
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

View File

@ -4,7 +4,7 @@
* Immich * Immich
* Immich API * Immich API
* *
* The version of the OpenAPI document: 1.39.0 * The version of the OpenAPI document: 1.40.0
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

View File

@ -4,7 +4,7 @@
* Immich * Immich
* Immich API * Immich API
* *
* The version of the OpenAPI document: 1.39.0 * The version of the OpenAPI document: 1.40.0
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

View File

@ -4,7 +4,7 @@
* Immich * Immich
* Immich API * Immich API
* *
* The version of the OpenAPI document: 1.39.0 * The version of the OpenAPI document: 1.40.0
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

View File

@ -3,18 +3,27 @@
notificationController, notificationController,
NotificationType NotificationType
} from '$lib/components/shared-components/notification/notification'; } from '$lib/components/shared-components/notification/notification';
import { handleError } from '$lib/utils/handle-error';
import { api, SystemConfigOAuthDto } from '@api'; import { api, SystemConfigOAuthDto } from '@api';
import _ from 'lodash';
import { fade } from 'svelte/transition';
import SettingButtonsRow from '../setting-buttons-row.svelte'; import SettingButtonsRow from '../setting-buttons-row.svelte';
import SettingInputField, { SettingInputFieldType } from '../setting-input-field.svelte'; import SettingInputField, { SettingInputFieldType } from '../setting-input-field.svelte';
import SettingSwitch from '../setting-switch.svelte'; import SettingSwitch from '../setting-switch.svelte';
import _ from 'lodash';
import { fade } from 'svelte/transition';
export let oauthConfig: SystemConfigOAuthDto; export let oauthConfig: SystemConfigOAuthDto;
let savedConfig: SystemConfigOAuthDto; let savedConfig: SystemConfigOAuthDto;
let defaultConfig: SystemConfigOAuthDto; let defaultConfig: SystemConfigOAuthDto;
const handleToggleOverride = () => {
// click runs before bind
const previouslyEnabled = oauthConfig.mobileOverrideEnabled;
if (!previouslyEnabled && !oauthConfig.mobileRedirectUri) {
oauthConfig.mobileRedirectUri = window.location.origin + '/api/oauth/mobile-redirect';
}
};
async function getConfigs() { async function getConfigs() {
[savedConfig, defaultConfig] = await Promise.all([ [savedConfig, defaultConfig] = await Promise.all([
api.systemConfigApi.getConfig().then((res) => res.data.oauth), api.systemConfigApi.getConfig().then((res) => res.data.oauth),
@ -38,6 +47,10 @@
try { try {
const { data: currentConfig } = await api.systemConfigApi.getConfig(); const { data: currentConfig } = await api.systemConfigApi.getConfig();
if (!oauthConfig.mobileOverrideEnabled) {
oauthConfig.mobileRedirectUri = '';
}
const result = await api.systemConfigApi.updateConfig({ const result = await api.systemConfigApi.updateConfig({
...currentConfig, ...currentConfig,
oauth: oauthConfig oauth: oauthConfig
@ -50,12 +63,8 @@
message: 'OAuth settings saved', message: 'OAuth settings saved',
type: NotificationType.Info type: NotificationType.Info
}); });
} catch (e) { } catch (error) {
console.error('Error [oauth-settings] [saveSetting]', e); handleError(error, 'Unable to save OAuth settings');
notificationController.show({
message: 'Unable to save settings',
type: NotificationType.Error
});
} }
} }
@ -74,76 +83,95 @@
<div class="mt-2"> <div class="mt-2">
{#await getConfigs() then} {#await getConfigs() then}
<div in:fade={{ duration: 500 }}> <div in:fade={{ duration: 500 }}>
<form autocomplete="off" on:submit|preventDefault> <form autocomplete="off" on:submit|preventDefault class="flex flex-col mx-4 gap-4 py-4">
<div class="mt-4"> <p class="text-sm dark:text-immich-dark-fg">
<SettingSwitch title="Enable" bind:checked={oauthConfig.enabled} /> For more details about this feature, refer to the <a
</div> href="http://immich.app/docs/features/oauth#mobile-redirect-uri"
class="underline"
target="_blank"
rel="noreferrer">docs</a
>.
</p>
<hr class="m-4" /> <SettingSwitch title="Enable" bind:checked={oauthConfig.enabled} />
<div class="flex flex-col gap-4 ml-4"> <hr />
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="ISSUER URL"
bind:value={oauthConfig.issuerUrl}
required={true}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.issuerUrl == savedConfig.issuerUrl)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="CLIENT ID"
bind:value={oauthConfig.clientId}
required={true}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.clientId == savedConfig.clientId)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="CLIENT SECRET"
bind:value={oauthConfig.clientSecret}
required={true}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.clientSecret == savedConfig.clientSecret)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="SCOPE"
bind:value={oauthConfig.scope}
required={true}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.scope == savedConfig.scope)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="BUTTON TEXT"
bind:value={oauthConfig.buttonText}
required={false}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.buttonText == savedConfig.buttonText)}
/>
<SettingSwitch
title="AUTO REGISTER"
subtitle="Automatically register new users after signing in with OAuth"
bind:checked={oauthConfig.autoRegister}
disabled={!oauthConfig.enabled}
/>
<SettingSwitch
title="MOBILE REDIRECT URI OVERRIDE"
subtitle="Enable when `app.immich:/` is an invalid redirect URI."
disabled={!oauthConfig.enabled}
on:click={() => handleToggleOverride()}
bind:checked={oauthConfig.mobileOverrideEnabled}
/>
{#if oauthConfig.mobileOverrideEnabled}
<SettingInputField <SettingInputField
inputType={SettingInputFieldType.TEXT} inputType={SettingInputFieldType.TEXT}
label="ISSUER URL" label="MOBILE REDIRECT URI"
bind:value={oauthConfig.issuerUrl} bind:value={oauthConfig.mobileRedirectUri}
required={true} required={true}
disabled={!oauthConfig.enabled} disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.issuerUrl == savedConfig.issuerUrl)} isEdited={!(oauthConfig.mobileRedirectUri == savedConfig.mobileRedirectUri)}
/> />
{/if}
<SettingInputField <SettingButtonsRow
inputType={SettingInputFieldType.TEXT} on:reset={reset}
label="CLIENT ID" on:save={saveSetting}
bind:value={oauthConfig.clientId} on:reset-to-default={resetToDefault}
required={true} showResetToDefault={!_.isEqual(savedConfig, defaultConfig)}
disabled={!oauthConfig.enabled} />
isEdited={!(oauthConfig.clientId == savedConfig.clientId)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="CLIENT SECRET"
bind:value={oauthConfig.clientSecret}
required={true}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.clientSecret == savedConfig.clientSecret)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="SCOPE"
bind:value={oauthConfig.scope}
required={true}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.scope == savedConfig.scope)}
/>
<SettingInputField
inputType={SettingInputFieldType.TEXT}
label="BUTTON TEXT"
bind:value={oauthConfig.buttonText}
required={false}
disabled={!oauthConfig.enabled}
isEdited={!(oauthConfig.buttonText == savedConfig.buttonText)}
/>
</div>
<div class="mt-4">
<SettingSwitch
title="AUTO REGISTER"
subtitle="Automatically register new users after signing in with OAuth"
bind:checked={oauthConfig.autoRegister}
disabled={!oauthConfig.enabled}
/>
</div>
<div class="ml-4">
<SettingButtonsRow
on:reset={reset}
on:save={saveSetting}
on:reset-to-default={resetToDefault}
showResetToDefault={!_.isEqual(savedConfig, defaultConfig)}
/>
</div>
</form> </form>
</div> </div>
{/await} {/await}

View File

@ -5,7 +5,7 @@
export let disabled = false; export let disabled = false;
</script> </script>
<div class="flex justify-between mx-4 place-items-center"> <div class="flex justify-between place-items-center">
<div> <div>
<h2 class="immich-form-label text-sm"> <h2 class="immich-form-label text-sm">
{title.toUpperCase()} {title.toUpperCase()}
@ -19,6 +19,7 @@
class="opacity-0 w-0 h-0 disabled::cursor-not-allowed" class="opacity-0 w-0 h-0 disabled::cursor-not-allowed"
type="checkbox" type="checkbox"
bind:checked bind:checked
on:click
{disabled} {disabled}
/> />