mirror of
https://github.com/fallenbagel/jellyseerr.git
synced 2025-12-24 02:39:18 -05:00
Compare commits
19 Commits
advanced-o
...
preview-OI
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f39794116 | ||
|
|
be5ee1e980 | ||
|
|
ab3c8e4e7e | ||
|
|
05b0a1fa99 | ||
|
|
cfbf7edf7e | ||
|
|
8f8a4153b6 | ||
|
|
f4988aba15 | ||
|
|
4a3f38fa10 | ||
|
|
67bbc73564 | ||
|
|
205aa5da92 | ||
|
|
27292c02ea | ||
|
|
80217c70ea | ||
|
|
7d426f0c7e | ||
|
|
55870fed20 | ||
|
|
7bd26eebb5 | ||
|
|
d36dcbed7e | ||
|
|
03d869ca59 | ||
|
|
51849cd9de | ||
|
|
fa7efa31bc |
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_1.png
Normal file
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 375 KiB |
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_2.png
Normal file
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 296 KiB |
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_3.png
Normal file
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 306 KiB |
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_4.png
Normal file
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 306 KiB |
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_5.png
Normal file
BIN
docs/using-jellyseerr/settings/users/assets/oidc_keycloak_5.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 285 KiB |
@@ -22,6 +22,14 @@ When disabled, users will only be able to sign in using their email address. Use
|
||||
|
||||
This setting is **enabled** by default.
|
||||
|
||||
## Enable OpenID Connect Sign-In
|
||||
|
||||
When enabled, users will be able to sign in to Jellyseerr using their OpenID Connect credentials, provided they have linked their OpenID Connect accounts. Once enabled, the [OpenID Connect settings](./oidc.md) can be accessed using the settings cog to the right of this option, and OpenID Connect providers can be configured.
|
||||
|
||||
When disabled, users will only be able to sign in using their Jellyseerr username or email address. Users without a password set will not be able to sign in to Jellyseerr.
|
||||
|
||||
This setting is **disabled** by default.
|
||||
|
||||
## Enable New Jellyfin/Emby/Plex Sign-In
|
||||
|
||||
When enabled, users with access to your media server will be able to sign in to Jellyseerr even if they have not yet been imported. Users will be automatically assigned the permissions configured in the [Default Permissions](#default-permissions) setting upon first sign-in.
|
||||
82
docs/using-jellyseerr/settings/users/oidc.md
Normal file
82
docs/using-jellyseerr/settings/users/oidc.md
Normal file
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: OpenID Connect
|
||||
description: Configure OpenID Connect settings.
|
||||
sidebar_position: 2.5
|
||||
---
|
||||
|
||||
# OpenID Connect
|
||||
|
||||
Jellyseerr supports OpenID Connect (OIDC) for authentication and authorization. To begin setting up OpenID Connect, follow these steps:
|
||||
|
||||
1. First, enable OpenID Connect [on the User settings page](./index.md#enable-openid-connect-sign-in).
|
||||
2. Once enabled, access OpenID Connect settings using the cog icon to the right.
|
||||
3. Add a new provider by clicking the "Add Provider" button.
|
||||
4. Configure the provider with the options described below.
|
||||
5. Link your OpenID Connect account to your Jellyseerr account using the "Link Account" button on the Linked Accounts page in your user's settings.
|
||||
6. Finally, you should be able to log in using your OpenID Connect account.
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Provider Name
|
||||
|
||||
Name of the provider which appears on the login screen.
|
||||
|
||||
Configuring this setting will automatically determine the [provider slug](#provider-slug), unless it is manually specified.
|
||||
|
||||
### Logo
|
||||
|
||||
The logo to display for the provider. Should be a URL or base64 encoded image.
|
||||
|
||||
:::tip
|
||||
|
||||
The search icon at the right of the logo field opens the [selfh.st/icons](https://selfh.st/icons) database. These icons include popular self-hosted OpenID Connect providers.
|
||||
|
||||
:::
|
||||
|
||||
### Issuer URL
|
||||
The base URL of the identity provider's OpenID Connect endpoint
|
||||
|
||||
### Client ID
|
||||
|
||||
The Client ID assigned to Jellyseerr
|
||||
|
||||
### Client Secret
|
||||
|
||||
The Client Secret assigned to Jellyseerr
|
||||
|
||||
### Provider Slug
|
||||
|
||||
Unique identifier for the provider
|
||||
|
||||
### Scopes
|
||||
|
||||
Space-separated list of scopes to request from the provider
|
||||
|
||||
### Required Claims
|
||||
|
||||
Space-separated list of boolean claims that are required to log in
|
||||
|
||||
### Allow New Users
|
||||
|
||||
Create accounts for new users logging in with this provider
|
||||
|
||||
## Provider Guides
|
||||
|
||||
### Keycloak
|
||||
|
||||
To set up Keycloak, follow these steps:
|
||||
|
||||
1. First, create a new client in Keycloak.
|
||||

|
||||
|
||||
1. Set the client ID to `jellyseerr`, and set the name to "Jellyseerr" (or whatever you prefer).
|
||||

|
||||
|
||||
1. Next, be sure to enable "Client authentication" in the capabilities section. The remaining defaults should be fine.
|
||||

|
||||
|
||||
1. Finally, set the root url to your Jellyseerr instance's URL, and add the login page as a valid redirect URL.
|
||||

|
||||
|
||||
1. With all that set up, you should be able to configure Jellyseerr to use Keycloak for authentication. Be sure to copy the client secret from the credentials page, as shown above. The issuer URL can be obtained from the "Realm Settings" page, by copying the link titled "OpenID Endpoint Configuration".
|
||||

|
||||
@@ -254,6 +254,41 @@ components:
|
||||
enableSpecialEpisodes:
|
||||
type: boolean
|
||||
example: false
|
||||
OidcProvider:
|
||||
type: object
|
||||
properties:
|
||||
slug:
|
||||
type: string
|
||||
readOnly: true
|
||||
name:
|
||||
type: string
|
||||
issuerUrl:
|
||||
type: string
|
||||
clientId:
|
||||
type: string
|
||||
clientSecret:
|
||||
type: string
|
||||
logo:
|
||||
type: string
|
||||
requiredClaims:
|
||||
type: string
|
||||
scopes:
|
||||
type: string
|
||||
newUserLogin:
|
||||
type: boolean
|
||||
required:
|
||||
- slug
|
||||
- name
|
||||
- issuerUrl
|
||||
- clientId
|
||||
- clientSecret
|
||||
OidcSettings:
|
||||
type: object
|
||||
properties:
|
||||
providers:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/OidcProvider'
|
||||
NetworkSettings:
|
||||
type: object
|
||||
properties:
|
||||
@@ -2212,6 +2247,64 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/MainSettings'
|
||||
/settings/oidc:
|
||||
get:
|
||||
summary: Get OpenID Connect settings
|
||||
description: Retrieves all OpenID Connect settings in a JSON object.
|
||||
tags:
|
||||
- settings
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OidcSettings'
|
||||
/settings/oidc/{provider}:
|
||||
put:
|
||||
summary: Update OpenID Connect provider
|
||||
description: Updates an existing OpenID Connect provider with the provided values.
|
||||
tags:
|
||||
- settings
|
||||
parameters:
|
||||
- in: path
|
||||
name: provider
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
description: Provider slug
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OidcProvider'
|
||||
responses:
|
||||
'200':
|
||||
description: 'Radarr instance updated'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RadarrSettings'
|
||||
delete:
|
||||
summary: Delete OpenID Connect provider
|
||||
description: Deletes an existing OpenID Connect provider based on the provider slug parameter.
|
||||
tags:
|
||||
- settings
|
||||
parameters:
|
||||
- in: path
|
||||
name: provider
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
description: Provider slug
|
||||
responses:
|
||||
'200':
|
||||
description: 'OpenID Connect provider deleted'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OidcSettings'
|
||||
/settings/network:
|
||||
get:
|
||||
summary: Get network settings
|
||||
@@ -4005,6 +4098,81 @@ paths:
|
||||
required:
|
||||
- email
|
||||
- password
|
||||
/auth/oidc/login/{slug}:
|
||||
get:
|
||||
security: []
|
||||
summary: Redirect to the OpenID Connect provider
|
||||
description: Constructs the redirect URL to the OpenID Connect provider, and redirects the user to it.
|
||||
tags:
|
||||
- auth
|
||||
parameters:
|
||||
- in: path
|
||||
name: slug
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
example: 'authentik'
|
||||
responses:
|
||||
'200':
|
||||
description: Authentication redirect url for the OpenID Connect provider
|
||||
headers:
|
||||
Set-Cookie:
|
||||
schema:
|
||||
type: string
|
||||
example: 'oidc-state=123456789; HttpOnly; max-age=60000; Secure'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
redirectUrl:
|
||||
type: string
|
||||
example: https://example.com/auth/oidc/callback?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Foidc%2Fcallback&scope=openid%20email&state=state
|
||||
/auth/oidc/callback/{slug}:
|
||||
get:
|
||||
security: []
|
||||
summary: The callback endpoint for the OpenID Connect provider redirect
|
||||
description: Takes the `code` and `state` parameters from the OpenID Connect provider, and exchanges them for a token.
|
||||
x-allow-unknown-query-parameters: true
|
||||
tags:
|
||||
- auth
|
||||
parameters:
|
||||
- in: path
|
||||
name: slug
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
example: 'authentik'
|
||||
- in: query
|
||||
name: code
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
example: '123456789'
|
||||
- in: query
|
||||
name: state
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
example: '123456789'
|
||||
- in: cookie
|
||||
name: oidc-state
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
example: '123456789'
|
||||
responses:
|
||||
'302':
|
||||
description: A redirect to the home page if successful or back to the login page if not
|
||||
headers:
|
||||
Location:
|
||||
schema:
|
||||
type: string
|
||||
example: /
|
||||
Set-Cookie:
|
||||
schema:
|
||||
type: string
|
||||
example: 'oidc-state=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT'
|
||||
/auth/logout:
|
||||
post:
|
||||
summary: Sign out and clear session cookie
|
||||
@@ -4808,6 +4976,23 @@ paths:
|
||||
responses:
|
||||
'204':
|
||||
description: User password updated
|
||||
/user/{userId}/settings/linked-accounts:
|
||||
get:
|
||||
summary: Lists the user's linked OpenID Connect accounts
|
||||
description: Lists the user's linked OpenID Connect accounts
|
||||
tags:
|
||||
- users
|
||||
parameters:
|
||||
- in: path
|
||||
name: userId
|
||||
required: true
|
||||
schema:
|
||||
type: number
|
||||
responses:
|
||||
'200':
|
||||
description: List of linked accounts
|
||||
'403':
|
||||
description: Invalid credentials
|
||||
/user/{userId}/settings/linked-accounts/plex:
|
||||
post:
|
||||
summary: Link the provided Plex account to the current user
|
||||
@@ -4906,6 +5091,28 @@ paths:
|
||||
description: Unlink request invalid
|
||||
'404':
|
||||
description: User does not exist
|
||||
/user/{userId}/settings/linked-accounts/{acctId}:
|
||||
delete:
|
||||
summary: Remove a linked account for a user
|
||||
description: Removes the linked account with the given ID for a specific user. Requires `MANAGE_USERS` permission if editing other users.
|
||||
tags:
|
||||
- users
|
||||
parameters:
|
||||
- in: path
|
||||
name: userId
|
||||
required: true
|
||||
schema:
|
||||
type: number
|
||||
- in: path
|
||||
name: acctId
|
||||
required: true
|
||||
schema:
|
||||
type: number
|
||||
responses:
|
||||
'204':
|
||||
description: Unlinking account succeeded
|
||||
'404':
|
||||
description: User or linked account does not exist
|
||||
/user/{userId}/settings/notifications:
|
||||
get:
|
||||
summary: Get notification settings for a user
|
||||
|
||||
@@ -68,6 +68,7 @@
|
||||
"gravatar-url": "3.1.0",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lodash": "4.17.21",
|
||||
"mime": "3",
|
||||
"next": "^14.2.25",
|
||||
|
||||
13
pnpm-lock.yaml
generated
13
pnpm-lock.yaml
generated
@@ -116,6 +116,9 @@ importers:
|
||||
https-proxy-agent:
|
||||
specifier: ^7.0.6
|
||||
version: 7.0.6
|
||||
jwt-decode:
|
||||
specifier: ^4.0.0
|
||||
version: 4.0.0
|
||||
lodash:
|
||||
specifier: 4.17.21
|
||||
version: 4.17.21
|
||||
@@ -6520,6 +6523,10 @@ packages:
|
||||
jws@4.0.0:
|
||||
resolution: {integrity: sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==}
|
||||
|
||||
jwt-decode@4.0.0:
|
||||
resolution: {integrity: sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
keyv@4.5.4:
|
||||
resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}
|
||||
|
||||
@@ -16093,7 +16100,7 @@ snapshots:
|
||||
debug: 4.4.0(supports-color@5.5.0)
|
||||
enhanced-resolve: 5.17.0
|
||||
eslint: 8.35.0
|
||||
eslint-module-utils: 2.8.1(@typescript-eslint/parser@7.2.0(eslint@8.35.0)(typescript@4.9.5))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@7.2.0(eslint@8.35.0)(typescript@4.9.5))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1)(eslint@8.35.0))(eslint@8.35.0)
|
||||
eslint-module-utils: 2.8.1(@typescript-eslint/parser@7.2.0(eslint@8.35.0)(typescript@4.9.5))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1)(eslint@8.35.0)
|
||||
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@5.54.0(eslint@8.35.0)(typescript@4.9.5))(eslint@8.35.0)
|
||||
fast-glob: 3.3.2
|
||||
get-tsconfig: 4.7.5
|
||||
@@ -16115,7 +16122,7 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-module-utils@2.8.1(@typescript-eslint/parser@7.2.0(eslint@8.35.0)(typescript@4.9.5))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@7.2.0(eslint@8.35.0)(typescript@4.9.5))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1)(eslint@8.35.0))(eslint@8.35.0):
|
||||
eslint-module-utils@2.8.1(@typescript-eslint/parser@7.2.0(eslint@8.35.0)(typescript@4.9.5))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1)(eslint@8.35.0):
|
||||
dependencies:
|
||||
debug: 3.2.7(supports-color@8.1.1)
|
||||
optionalDependencies:
|
||||
@@ -17814,6 +17821,8 @@ snapshots:
|
||||
jwa: 2.0.0
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
jwt-decode@4.0.0: {}
|
||||
|
||||
keyv@4.5.4:
|
||||
dependencies:
|
||||
json-buffer: 3.0.1
|
||||
|
||||
57
public/images/openid.svg
Normal file
57
public/images/openid.svg
Normal file
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
version="1.0"
|
||||
width="120"
|
||||
height="120"
|
||||
id="svg2593"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="OpenID_logo_2.svg"
|
||||
inkscape:version="1.3.2 (091e20e, 2023-11-25)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#505050"
|
||||
bordercolor="#eeeeee"
|
||||
borderopacity="1"
|
||||
inkscape:showpageshadow="0"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#505050"
|
||||
showgrid="false"
|
||||
inkscape:zoom="5.3731101"
|
||||
inkscape:cx="69.60587"
|
||||
inkscape:cy="65.883631"
|
||||
inkscape:window-width="1512"
|
||||
inkscape:window-height="945"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="37"
|
||||
inkscape:window-maximized="0"
|
||||
inkscape:current-layer="svg2593" /><defs
|
||||
id="defs2596"><clipPath
|
||||
id="clipPath2616"><path
|
||||
d="M 0,14400 H 14400 V 0 H 0 Z"
|
||||
id="path2618" /></clipPath></defs><g
|
||||
transform="matrix(1.25,0,0,-1.25,-8601.6804,9121.1624)"
|
||||
id="g2602"><g
|
||||
transform="matrix(0.375,0,0,0.375,4301.4506,4557.5812)"
|
||||
id="g2734"><g
|
||||
id="g2726"><g
|
||||
transform="translate(6998.0969,7259.1135)"
|
||||
id="g2604"><path
|
||||
d="M 0,0 V -159.939 -180 l 32,15.061 V 15.633 Z"
|
||||
id="path2606"
|
||||
style="fill:#f8931e;fill-opacity:1;fill-rule:nonzero;stroke:none" /></g><g
|
||||
transform="translate(7108.9192,7206.3137)"
|
||||
id="g2608"><path
|
||||
d="M 0,0 4.417,-45.864 -57.466,-32.4"
|
||||
id="path2610"
|
||||
style="fill:#b3b3b3;fill-opacity:1;fill-rule:nonzero;stroke:none" /></g><g
|
||||
transform="translate(6934.0969,7147.6213)"
|
||||
id="g2620"><path
|
||||
d="M 0,0 C 0,22.674 24.707,41.769 58.383,47.598 V 67.923 C 6.873,61.697 -32,33.656 -32,0 -32,-34.869 9.725,-63.709 64,-68.508 v 20.061 C 27.484,-43.869 0,-23.919 0,0 M 101.617,67.915 V 47.598 c 13.399,-2.319 25.385,-6.727 34.951,-12.64 l 22.627,13.984 c -15.42,9.531 -35.322,16.283 -57.578,18.973"
|
||||
id="path2622"
|
||||
style="fill:#b3b3b3;fill-opacity:1;fill-rule:nonzero;stroke:none" /></g></g></g></g></svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
27
server/entity/LinkedAccount.ts
Normal file
27
server/entity/LinkedAccount.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
|
||||
import { User } from './User';
|
||||
|
||||
@Entity('linked_accounts')
|
||||
export class LinkedAccount {
|
||||
constructor(options: Omit<LinkedAccount, 'id'>) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.linkedAccounts, { onDelete: 'CASCADE' })
|
||||
user: User;
|
||||
|
||||
/** Slug of the OIDC provider. */
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
provider: string;
|
||||
|
||||
/** Unique ID from the OAuth provider */
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
sub: string;
|
||||
|
||||
/** Account username from the OAuth provider */
|
||||
@Column()
|
||||
username: string;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MediaRequestStatus, MediaType } from '@server/constants/media';
|
||||
import { UserType } from '@server/constants/user';
|
||||
import { getRepository } from '@server/datasource';
|
||||
import { LinkedAccount } from '@server/entity/LinkedAccount';
|
||||
import { Watchlist } from '@server/entity/Watchlist';
|
||||
import type { QuotaResponse } from '@server/interfaces/api/userInterfaces';
|
||||
import PreparedEmail from '@server/lib/email';
|
||||
@@ -91,6 +92,9 @@ export class User {
|
||||
@Column({ type: 'varchar', nullable: true, select: false })
|
||||
public plexToken?: string | null;
|
||||
|
||||
@OneToMany(() => LinkedAccount, (link) => link.user)
|
||||
public linkedAccounts: LinkedAccount[];
|
||||
|
||||
@Column({ type: 'integer', default: 0 })
|
||||
public permissions = 0;
|
||||
|
||||
|
||||
239
server/interfaces/api/oidcInterfaces.ts
Normal file
239
server/interfaces/api/oidcInterfaces.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type Mandatory<T, K extends keyof T> = Required<Pick<T, K>> & Omit<T, K>;
|
||||
|
||||
/**
|
||||
* Standard OpenID Connect discovery document.
|
||||
*
|
||||
* @public
|
||||
* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
|
||||
*/
|
||||
export interface OidcProviderMetadata {
|
||||
issuer: string; // REQUIRED
|
||||
|
||||
authorization_endpoint: string; // REQUIRED
|
||||
|
||||
token_endpoint: string; // REQUIRED
|
||||
|
||||
token_endpoint_auth_methods_supported?: string[]; // OPTIONAL
|
||||
|
||||
token_endpoint_auth_signing_alg_values_supported?: string[]; // OPTIONAL
|
||||
|
||||
userinfo_endpoint: string; // RECOMMENDED
|
||||
|
||||
check_session_iframe: string; // REQUIRED
|
||||
|
||||
end_session_endpoint: string; // REQUIRED
|
||||
|
||||
jwks_uri: string; // REQUIRED
|
||||
|
||||
registration_endpoint: string; // RECOMMENDED
|
||||
|
||||
scopes_supported: string[]; // RECOMMENDED
|
||||
|
||||
response_types_supported: string[]; // REQUIRED
|
||||
|
||||
acr_values_supported?: string[]; // OPTIONAL
|
||||
|
||||
subject_types_supported: string[]; // REQUIRED
|
||||
|
||||
request_object_signing_alg_values_supported?: string[]; // OPTIONAL
|
||||
|
||||
display_values_supported?: string[]; // OPTIONAL
|
||||
|
||||
claim_types_supported?: string[]; // OPTIONAL
|
||||
|
||||
claims_supported: string[]; // RECOMMENDED
|
||||
|
||||
claims_parameter_supported?: boolean; // OPTIONAL
|
||||
|
||||
service_documentation?: string; // OPTIONAL
|
||||
|
||||
ui_locales_supported?: string[]; // OPTIONAL
|
||||
|
||||
revocation_endpoint: string; // REQUIRED
|
||||
|
||||
introspection_endpoint: string; // REQUIRED
|
||||
|
||||
frontchannel_logout_supported?: boolean; // OPTIONAL
|
||||
|
||||
frontchannel_logout_session_supported?: boolean; // OPTIONAL
|
||||
|
||||
backchannel_logout_supported?: boolean; // OPTIONAL
|
||||
|
||||
backchannel_logout_session_supported?: boolean; // OPTIONAL
|
||||
|
||||
grant_types_supported?: string[]; // OPTIONAL
|
||||
|
||||
response_modes_supported?: string[]; // OPTIONAL
|
||||
|
||||
code_challenge_methods_supported?: string[]; // OPTIONAL
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard OpenID Connect address claim.
|
||||
* The Address Claim represents a physical mailing address.
|
||||
*
|
||||
* @public
|
||||
* @see https://openid.net/specs/openid-connect-core-1_0.html#AddressClaim
|
||||
*/
|
||||
export interface OidcAddressClaim {
|
||||
/** Full mailing address, formatted for display or use on a mailing label. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a carriage return/line feed pair ("\\r\\n") or as a single line feed character ("\\n"). */
|
||||
formatted?: string;
|
||||
/** Full street address component, which MAY include house number, street name, Post Office Box, and multi-line extended street address information. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a carriage return/line feed pair ("\\r\\n") or as a single line feed character ("\\n"). */
|
||||
street_address?: string;
|
||||
/** City or locality component. */
|
||||
locality?: string;
|
||||
/** State, province, prefecture, or region component. */
|
||||
region?: string;
|
||||
/** Zip code or postal code component. */
|
||||
postal_code?: string;
|
||||
/** Country name component. */
|
||||
country?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard OpenID Connect claims.
|
||||
* They can be requested to be returned either in the UserInfo Response or in the ID Token.
|
||||
*
|
||||
* @public
|
||||
* @see https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
|
||||
*/
|
||||
export interface OidcStandardClaims {
|
||||
/** Subject - Identifier for the End-User at the Issuer. */
|
||||
sub?: string;
|
||||
/** End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. */
|
||||
name?: string;
|
||||
/** Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters. */
|
||||
given_name?: string;
|
||||
/** Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters. */
|
||||
family_name?: string;
|
||||
/** Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used. */
|
||||
middle_name?: string;
|
||||
/** Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael. */
|
||||
nickname?: string;
|
||||
/** Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as \@, /, or whitespace. */
|
||||
preferred_username?: string;
|
||||
/** URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User. */
|
||||
profile?: string;
|
||||
/** URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User. */
|
||||
picture?: string;
|
||||
/** URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with. */
|
||||
website?: string;
|
||||
/** End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 addr-spec syntax. */
|
||||
email?: string;
|
||||
/** True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. */
|
||||
email_verified?: boolean;
|
||||
/** End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable. */
|
||||
gender?: string;
|
||||
/** End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates. */
|
||||
birthdate?: string;
|
||||
/** String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles. */
|
||||
zoneinfo?: string;
|
||||
/** End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; */
|
||||
locale?: string;
|
||||
/** End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678. */
|
||||
phone_number?: string;
|
||||
/** True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format. */
|
||||
phone_number_verified?: boolean;
|
||||
/** End-User's preferred postal address. The value of the address member is a JSON [RFC4627] structure containing some or all of the members defined in Section 5.1.1. */
|
||||
address?: OidcAddressClaim;
|
||||
/** Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. */
|
||||
updated_at?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard JWT claims.
|
||||
*
|
||||
* @public
|
||||
* @see https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
|
||||
*/
|
||||
export interface JwtClaims {
|
||||
[claim: string]: unknown;
|
||||
|
||||
/** The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. */
|
||||
iss?: string;
|
||||
/** The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The "sub" value is a case-sensitive string containing a StringOrURI value. */
|
||||
sub?: string;
|
||||
/** The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case-sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. */
|
||||
aud?: string | string[];
|
||||
/** The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. */
|
||||
exp?: number;
|
||||
/** The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the "nbf" claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the "nbf" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. */
|
||||
nbf?: number;
|
||||
/** The "iat" (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. */
|
||||
iat?: number;
|
||||
/** The "jti" (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The "jti" claim can be used to prevent the JWT from being replayed. The "jti" value is a case-sensitive string. */
|
||||
jti?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard ID Token claims.
|
||||
*
|
||||
* @public
|
||||
* @see https://openid.net/specs/openid-connect-core-1_0.html#IDToken
|
||||
*/
|
||||
export interface IdTokenClaims
|
||||
extends Mandatory<OidcStandardClaims, 'sub'>,
|
||||
Mandatory<JwtClaims, 'iss' | 'sub' | 'aud' | 'exp' | 'iat'> {
|
||||
[claim: string]: unknown;
|
||||
|
||||
/** Time when the End-User authentication occurred. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time response parameter.) */
|
||||
auth_time?: number;
|
||||
/** String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case sensitive string. */
|
||||
nonce?: string;
|
||||
/** Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that identifies the Authentication Context Class that the authentication performed satisfied. The value "0" indicates the End-User authentication did not meet the requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a long-lived browser cookie, for instance, is one example where the use of "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used to authorize access to any resource of any monetary value. (This corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as the acr value; registered names MUST NOT be used with a different meaning than that which is registered. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The acr value is a case sensitive string. */
|
||||
acr?: string;
|
||||
/** Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in the authentication. For instance, values might indicate that both password and OTP authentication methods were used. The definition of particular values to be used in the amr Claim is beyond the scope of this specification. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The amr value is an array of case sensitive strings. */
|
||||
amr?: unknown;
|
||||
/** Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value. */
|
||||
azp?: string;
|
||||
/**
|
||||
* Session ID - String identifier for a Session. This represents a Session of a User Agent or device for a logged-in End-User at an RP. Different sid values are used to identify distinct sessions at an OP. The sid value need only be unique in the context of a particular issuer. Its contents are opaque to the RP. Its syntax is the same as an OAuth 2.0 Client Identifier.
|
||||
* @see https://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
|
||||
* */
|
||||
sid?: string;
|
||||
}
|
||||
|
||||
type OidcTokenSuccessResponse = {
|
||||
/**
|
||||
* REQUIRED. ID Token value associated with the authenticated session.
|
||||
*
|
||||
* @see https://openid.net/specs/openid-connect-core-1_0.html#IDToken
|
||||
*/
|
||||
id_token: string;
|
||||
/**
|
||||
* REQUIRED. The access token issued by the authorization server.
|
||||
*/
|
||||
access_token: string;
|
||||
/**
|
||||
* REQUIRED. The type of the token issued as described in
|
||||
* Section 7.1. Value is case insensitive.
|
||||
*
|
||||
* @see https://datatracker.ietf.org/doc/html/rfc6749#section-7.1
|
||||
*/
|
||||
token_type: string;
|
||||
/**
|
||||
* RECOMMENDED. The lifetime in seconds of the access token. For
|
||||
* example, the value "3600" denotes that the access token will
|
||||
* expire in one hour from the time the response was generated.
|
||||
* If omitted, the authorization server SHOULD provide the
|
||||
* expiration time via other means or document the default value.
|
||||
*/
|
||||
expires_in?: number;
|
||||
};
|
||||
|
||||
type OidcTokenErrorResponse = {
|
||||
error: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Standard response from the OpenID Connect token request endpoint.
|
||||
*
|
||||
* @public
|
||||
* @see https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
|
||||
*/
|
||||
export type OidcTokenResponse =
|
||||
| OidcTokenSuccessResponse
|
||||
| OidcTokenErrorResponse;
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PublicOidcProvider } from '@server/lib/settings';
|
||||
import type { DnsEntries, DnsStats } from 'dns-caching';
|
||||
import type { PaginatedResponse } from './common';
|
||||
|
||||
@@ -48,6 +49,7 @@ export interface PublicSettingsResponse {
|
||||
emailEnabled: boolean;
|
||||
newPlexLogin: boolean;
|
||||
youtubeUrl: string;
|
||||
openIdProviders: PublicOidcProvider[];
|
||||
}
|
||||
|
||||
export interface CacheItem {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { NotificationAgentKey } from '@server/lib/settings';
|
||||
import type {
|
||||
NotificationAgentKey,
|
||||
PublicOidcProvider,
|
||||
} from '@server/lib/settings';
|
||||
|
||||
export interface UserSettingsGeneralResponse {
|
||||
username?: string;
|
||||
@@ -39,3 +42,11 @@ export interface UserSettingsNotificationsResponse {
|
||||
webPushEnabled?: boolean;
|
||||
notificationTypes: Partial<NotificationAgentTypes>;
|
||||
}
|
||||
|
||||
export type UserSettingsLinkedAccount = {
|
||||
id: number;
|
||||
username: string;
|
||||
provider: PublicOidcProvider;
|
||||
};
|
||||
|
||||
export type UserSettingsLinkedAccountResponse = UserSettingsLinkedAccount[];
|
||||
|
||||
@@ -49,6 +49,25 @@ export interface JellyfinSettings {
|
||||
serverId: string;
|
||||
apiKey: string;
|
||||
}
|
||||
|
||||
export type OidcProvider = {
|
||||
slug: string;
|
||||
name: string;
|
||||
issuerUrl: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
logo?: string;
|
||||
requiredClaims?: string;
|
||||
scopes?: string;
|
||||
newUserLogin?: boolean;
|
||||
};
|
||||
|
||||
export type PublicOidcProvider = Pick<OidcProvider, 'slug' | 'name' | 'logo'>;
|
||||
|
||||
export interface OidcSettings {
|
||||
providers: OidcProvider[];
|
||||
}
|
||||
|
||||
export interface TautulliSettings {
|
||||
hostname?: string;
|
||||
port?: number;
|
||||
@@ -135,6 +154,7 @@ export interface MainSettings {
|
||||
hideBlacklisted: boolean;
|
||||
localLogin: boolean;
|
||||
mediaServerLogin: boolean;
|
||||
oidcLogin: boolean;
|
||||
newPlexLogin: boolean;
|
||||
discoverRegion: string;
|
||||
streamingRegion: string;
|
||||
@@ -203,6 +223,7 @@ interface FullPublicSettings extends PublicSettings {
|
||||
userEmailRequired: boolean;
|
||||
newPlexLogin: boolean;
|
||||
youtubeUrl: string;
|
||||
openIdProviders: PublicOidcProvider[];
|
||||
}
|
||||
|
||||
export interface NotificationAgentConfig {
|
||||
@@ -354,6 +375,7 @@ export interface AllSettings {
|
||||
main: MainSettings;
|
||||
plex: PlexSettings;
|
||||
jellyfin: JellyfinSettings;
|
||||
oidc: OidcSettings;
|
||||
tautulli: TautulliSettings;
|
||||
radarr: RadarrSettings[];
|
||||
sonarr: SonarrSettings[];
|
||||
@@ -390,6 +412,7 @@ class Settings {
|
||||
hideBlacklisted: false,
|
||||
localLogin: true,
|
||||
mediaServerLogin: true,
|
||||
oidcLogin: false,
|
||||
newPlexLogin: true,
|
||||
discoverRegion: '',
|
||||
streamingRegion: '',
|
||||
@@ -421,6 +444,9 @@ class Settings {
|
||||
serverId: '',
|
||||
apiKey: '',
|
||||
},
|
||||
oidc: {
|
||||
providers: [],
|
||||
},
|
||||
tautulli: {},
|
||||
metadataSettings: {
|
||||
tv: MetadataProviderType.TMDB,
|
||||
@@ -622,6 +648,14 @@ class Settings {
|
||||
this.data.jellyfin = data;
|
||||
}
|
||||
|
||||
get oidc(): OidcSettings {
|
||||
return this.data.oidc;
|
||||
}
|
||||
|
||||
set oidc(data: OidcSettings) {
|
||||
this.data.oidc = data;
|
||||
}
|
||||
|
||||
get tautulli(): TautulliSettings {
|
||||
return this.data.tautulli;
|
||||
}
|
||||
@@ -694,6 +728,13 @@ class Settings {
|
||||
this.data.notifications.agents.email.options.userEmailRequired,
|
||||
newPlexLogin: this.data.main.newPlexLogin,
|
||||
youtubeUrl: this.data.main.youtubeUrl,
|
||||
openIdProviders: this.data.main.oidcLogin
|
||||
? this.data.oidc.providers.map((p) => ({
|
||||
slug: p.slug,
|
||||
name: p.name,
|
||||
logo: p.logo,
|
||||
}))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
21
server/migration/postgres/1742858617989-AddLinkedAccount.ts
Normal file
21
server/migration/postgres/1742858617989-AddLinkedAccount.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddLinkedAccount1742858617989 implements MigrationInterface {
|
||||
name = 'AddLinkedAccount1742858617989';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "linked_accounts" ("id" SERIAL NOT NULL, "provider" character varying(255) NOT NULL, "sub" character varying(255) NOT NULL, "username" character varying NOT NULL, "userId" integer, CONSTRAINT "PK_445bf7a50aeeb7f0084052935a6" PRIMARY KEY ("id"))`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "linked_accounts" ADD CONSTRAINT "FK_2c77d2a0c06eeab6e62dc35af64" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "linked_accounts" DROP CONSTRAINT "FK_2c77d2a0c06eeab6e62dc35af64"`
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "linked_accounts"`);
|
||||
}
|
||||
}
|
||||
15
server/migration/sqlite/1742858484395-AddLinkedAccounts.ts
Normal file
15
server/migration/sqlite/1742858484395-AddLinkedAccounts.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddLinkedAccounts1742858484395 implements MigrationInterface {
|
||||
name = 'AddLinkedAccounts1742858484395';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "linked_accounts" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "provider" varchar(255) NOT NULL, "sub" varchar(255) NOT NULL, "username" varchar NOT NULL, "userId" integer, CONSTRAINT "FK_2c77d2a0c06eeab6e62dc35af64" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP TABLE "linked_accounts"`);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import { ApiErrorCode } from '@server/constants/error';
|
||||
import { MediaServerType, ServerType } from '@server/constants/server';
|
||||
import { UserType } from '@server/constants/user';
|
||||
import { getRepository } from '@server/datasource';
|
||||
import { LinkedAccount } from '@server/entity/LinkedAccount';
|
||||
import { User } from '@server/entity/User';
|
||||
import type { IdTokenClaims } from '@server/interfaces/api/oidcInterfaces';
|
||||
import { startJobs } from '@server/job/schedule';
|
||||
import { Permission } from '@server/lib/permissions';
|
||||
import { getSettings } from '@server/lib/settings';
|
||||
@@ -14,9 +16,21 @@ import { checkAvatarChanged } from '@server/routes/avatarproxy';
|
||||
import { ApiError } from '@server/types/error';
|
||||
import { getAppVersion } from '@server/utils/appVersion';
|
||||
import { getHostname } from '@server/utils/getHostname';
|
||||
import {
|
||||
createIdTokenSchema,
|
||||
fetchOpenIdTokenData,
|
||||
getOpenIdConfiguration,
|
||||
getOpenIdRedirectUrl,
|
||||
getOpenIdUserInfo,
|
||||
validateUserClaims,
|
||||
type FullUserInfo,
|
||||
} from '@server/utils/oidc';
|
||||
import axios from 'axios';
|
||||
import { randomBytes } from 'crypto';
|
||||
import * as EmailValidator from 'email-validator';
|
||||
import { Router } from 'express';
|
||||
import gravatarUrl from 'gravatar-url';
|
||||
import { jwtDecode } from 'jwt-decode';
|
||||
import net from 'net';
|
||||
|
||||
const authRoutes = Router();
|
||||
@@ -721,6 +735,287 @@ authRoutes.post('/local', async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
authRoutes.get('/oidc/login/:slug', async (req, res, next) => {
|
||||
const settings = getSettings();
|
||||
const provider = settings.oidc.providers.find(
|
||||
(p) => p.slug === req.params.slug
|
||||
);
|
||||
|
||||
if (!settings.main.oidcLogin || !provider) {
|
||||
return next({
|
||||
status: 403,
|
||||
message: 'OpenID Connect sign-in is disabled.',
|
||||
});
|
||||
}
|
||||
|
||||
const state = randomBytes(32).toString('hex');
|
||||
|
||||
let redirectUrl;
|
||||
try {
|
||||
redirectUrl = await getOpenIdRedirectUrl(req, provider, state);
|
||||
} catch (err) {
|
||||
logger.info('Failed OpenID Connect login attempt', {
|
||||
cause: 'Failed to fetch OpenID Connect redirect url',
|
||||
ip: req.ip,
|
||||
errorMessage: err.message,
|
||||
});
|
||||
return next({
|
||||
status: 500,
|
||||
message: 'Configuration error.',
|
||||
});
|
||||
}
|
||||
|
||||
res.cookie('oidc-state', state, {
|
||||
maxAge: 60000,
|
||||
httpOnly: true,
|
||||
secure: req.protocol === 'https',
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
redirectUrl,
|
||||
});
|
||||
});
|
||||
|
||||
authRoutes.get('/oidc/callback/:slug', async (req, res, next) => {
|
||||
const settings = getSettings();
|
||||
const provider = settings.oidc.providers.find(
|
||||
(p) => p.slug === req.params.slug
|
||||
);
|
||||
|
||||
if (!settings.main.oidcLogin || !provider) {
|
||||
return next({
|
||||
status: 403,
|
||||
message: 'OpenID Connect sign-in is disabled',
|
||||
});
|
||||
}
|
||||
|
||||
const requiredClaims = (provider.requiredClaims ?? '')
|
||||
.split(' ')
|
||||
.filter((s) => !!s);
|
||||
|
||||
const cookieState = req.cookies['oidc-state'];
|
||||
const url = new URL(req.url, `${req.protocol}://${req.hostname}`);
|
||||
const state = url.searchParams.get('state');
|
||||
|
||||
try {
|
||||
// Check that the request belongs to the correct state
|
||||
if (state && cookieState === state) {
|
||||
res.clearCookie('oidc-state');
|
||||
} else {
|
||||
logger.info('Failed OpenID Connect login attempt', {
|
||||
cause: 'Invalid state',
|
||||
ip: req.ip,
|
||||
state: state,
|
||||
cookieState: cookieState,
|
||||
});
|
||||
return next({
|
||||
status: 400,
|
||||
message: 'Authorization failed',
|
||||
});
|
||||
}
|
||||
|
||||
// Check that a code has been issued
|
||||
const code = url.searchParams.get('code');
|
||||
if (!code) {
|
||||
logger.info('Failed OpenID Connect login attempt', {
|
||||
cause: 'Invalid code',
|
||||
ip: req.ip,
|
||||
code: code,
|
||||
});
|
||||
return next({
|
||||
status: 400,
|
||||
message: 'Authorization failed',
|
||||
});
|
||||
}
|
||||
|
||||
const wellKnownInfo = await getOpenIdConfiguration(provider.issuerUrl);
|
||||
|
||||
// Fetch the token data
|
||||
const body = await fetchOpenIdTokenData(req, provider, wellKnownInfo, code);
|
||||
|
||||
// Validate that the token response is valid and not manipulated
|
||||
if ('error' in body) {
|
||||
logger.info('Failed OIDC login attempt', {
|
||||
cause: 'Invalid token response',
|
||||
ip: req.ip,
|
||||
body: body,
|
||||
});
|
||||
return next({
|
||||
status: 400,
|
||||
message: 'Authorization failed',
|
||||
});
|
||||
}
|
||||
|
||||
// Extract the ID token and access token
|
||||
const { id_token: idToken, access_token: accessToken } = body;
|
||||
|
||||
// Attempt to decode ID token jwt
|
||||
let decoded: IdTokenClaims;
|
||||
try {
|
||||
decoded = jwtDecode(idToken);
|
||||
} catch (err) {
|
||||
logger.info('Failed OIDC login attempt', {
|
||||
cause: 'Invalid jwt',
|
||||
ip: req.ip,
|
||||
idToken: idToken,
|
||||
err,
|
||||
});
|
||||
return next({
|
||||
status: 400,
|
||||
message: 'Authorization failed',
|
||||
});
|
||||
}
|
||||
|
||||
// Merge claims from JWT with data from userinfo endpoint
|
||||
const userInfo = await getOpenIdUserInfo(wellKnownInfo, accessToken);
|
||||
const fullUserInfo: FullUserInfo = { ...decoded, ...userInfo };
|
||||
|
||||
// Validate ID token jwt and user info
|
||||
try {
|
||||
const idTokenSchema = createIdTokenSchema({
|
||||
oidcClientId: provider.clientId,
|
||||
oidcDomain: provider.issuerUrl,
|
||||
requiredClaims,
|
||||
});
|
||||
await idTokenSchema.validate(fullUserInfo);
|
||||
} catch (err) {
|
||||
logger.info('Failed OIDC login attempt', {
|
||||
cause: 'Invalid jwt or missing claims',
|
||||
ip: req.ip,
|
||||
idToken: idToken,
|
||||
errorMessage: err.message,
|
||||
});
|
||||
return next({
|
||||
status: 403,
|
||||
message: 'Authorization failed',
|
||||
});
|
||||
}
|
||||
|
||||
// Validate that user meets required claims
|
||||
try {
|
||||
validateUserClaims(fullUserInfo, requiredClaims);
|
||||
} catch (error) {
|
||||
logger.info('Failed OIDC login attempt', {
|
||||
cause: 'Failed to validate required claims',
|
||||
error,
|
||||
ip: req.ip,
|
||||
requiredClaims: provider.requiredClaims,
|
||||
});
|
||||
return next({
|
||||
status: 403,
|
||||
message: 'Insufficient permissions',
|
||||
});
|
||||
}
|
||||
|
||||
// Map identifier to linked account
|
||||
const userRepository = getRepository(User);
|
||||
const linkedAccountsRepository = getRepository(LinkedAccount);
|
||||
|
||||
const linkedAccount = await linkedAccountsRepository.findOne({
|
||||
relations: {
|
||||
user: true,
|
||||
},
|
||||
where: {
|
||||
provider: provider.slug,
|
||||
sub: fullUserInfo.sub,
|
||||
},
|
||||
});
|
||||
let user = linkedAccount?.user;
|
||||
|
||||
// If there is already a user logged in, and no linked account, link the account.
|
||||
if (req.user != null && linkedAccount == null) {
|
||||
const linkedAccount = new LinkedAccount({
|
||||
user: req.user,
|
||||
provider: provider.slug,
|
||||
sub: fullUserInfo.sub,
|
||||
username: fullUserInfo.preferred_username ?? req.user.displayName,
|
||||
});
|
||||
|
||||
await linkedAccountsRepository.save(linkedAccount);
|
||||
return res
|
||||
.status(200)
|
||||
.json({ status: 'ok', to: '/profile/settings/linked-accounts' });
|
||||
}
|
||||
|
||||
// Create user if one doesn't already exist
|
||||
if (!user && fullUserInfo.email != null && provider.newUserLogin) {
|
||||
// Check if a user with this email already exists
|
||||
const existingUser = await userRepository.findOne({
|
||||
where: { email: fullUserInfo.email },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
// If a user with the email exists, throw a 409 Conflict error
|
||||
return next({
|
||||
status: 409,
|
||||
message: 'A user with this email address already exists.',
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(`Creating user for ${fullUserInfo.email}`, {
|
||||
ip: req.ip,
|
||||
email: fullUserInfo.email,
|
||||
});
|
||||
|
||||
const avatar =
|
||||
fullUserInfo.picture ??
|
||||
gravatarUrl(fullUserInfo.email, { default: 'mm', size: 200 });
|
||||
user = new User({
|
||||
avatar: avatar,
|
||||
username: fullUserInfo.preferred_username,
|
||||
email: fullUserInfo.email,
|
||||
permissions: settings.main.defaultPermissions,
|
||||
plexToken: '',
|
||||
userType: UserType.LOCAL,
|
||||
});
|
||||
await userRepository.save(user);
|
||||
|
||||
const linkedAccount = new LinkedAccount({
|
||||
user,
|
||||
provider: provider.slug,
|
||||
sub: fullUserInfo.sub,
|
||||
username: fullUserInfo.preferred_username ?? fullUserInfo.email,
|
||||
});
|
||||
await linkedAccountsRepository.save(linkedAccount);
|
||||
|
||||
user.linkedAccounts = [linkedAccount];
|
||||
await userRepository.save(user);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
logger.debug('Failed OIDC sign-up attempt', {
|
||||
cause: provider.newUserLogin
|
||||
? 'User did not have an account, and was missing an associated email address.'
|
||||
: 'User did not have an account, and new user login was disabled.',
|
||||
});
|
||||
return next({
|
||||
status: 400,
|
||||
message: provider.newUserLogin
|
||||
? 'Unable to create new user account (missing email address)'
|
||||
: 'Unable to create new user account (new user login is disabled)',
|
||||
});
|
||||
}
|
||||
|
||||
// Set logged in session and return
|
||||
if (req.session) {
|
||||
req.session.userId = user.id;
|
||||
}
|
||||
|
||||
// Success!
|
||||
return res.status(200).json({ status: 'ok', to: '/' });
|
||||
} catch (error) {
|
||||
logger.error('Failed OIDC login attempt', {
|
||||
cause: 'Unknown error',
|
||||
ip: req.ip,
|
||||
error,
|
||||
});
|
||||
return next({
|
||||
status: 500,
|
||||
message: 'An unknown error occurred',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
authRoutes.post('/logout', async (req, res, next) => {
|
||||
try {
|
||||
const userId = req.session?.userId;
|
||||
|
||||
@@ -109,6 +109,45 @@ settingsRoutes.post('/main/regenerate', async (req, res, next) => {
|
||||
return res.status(200).json(filteredMainSettings(req.user, main));
|
||||
});
|
||||
|
||||
settingsRoutes.get('/oidc', async (req, res) => {
|
||||
const settings = getSettings();
|
||||
|
||||
return res.status(200).json(settings.oidc);
|
||||
});
|
||||
|
||||
settingsRoutes.put('/oidc/:slug', async (req, res) => {
|
||||
const settings = getSettings();
|
||||
let provider = settings.oidc.providers.findIndex(
|
||||
(p) => p.slug === req.params.slug
|
||||
);
|
||||
|
||||
if (provider !== -1) {
|
||||
Object.assign(settings.oidc.providers[provider], req.body);
|
||||
} else {
|
||||
settings.oidc.providers.push({ slug: req.params.slug, ...req.body });
|
||||
provider = settings.oidc.providers.length - 1;
|
||||
}
|
||||
|
||||
await settings.save();
|
||||
|
||||
return res.status(200).json(settings.oidc.providers[provider]);
|
||||
});
|
||||
|
||||
settingsRoutes.delete('/oidc/:slug', async (req, res) => {
|
||||
const settings = getSettings();
|
||||
const provider = settings.oidc.providers.findIndex(
|
||||
(p) => p.slug === req.params.slug
|
||||
);
|
||||
|
||||
if (provider === -1)
|
||||
return res.status(404).json({ message: 'Provider not found' });
|
||||
|
||||
settings.oidc.providers.splice(provider, 1);
|
||||
await settings.save();
|
||||
|
||||
return res.status(200).json(settings.oidc);
|
||||
});
|
||||
|
||||
settingsRoutes.get('/plex', (_req, res) => {
|
||||
const settings = getSettings();
|
||||
|
||||
|
||||
@@ -4,10 +4,13 @@ import { ApiErrorCode } from '@server/constants/error';
|
||||
import { MediaServerType } from '@server/constants/server';
|
||||
import { UserType } from '@server/constants/user';
|
||||
import { getRepository } from '@server/datasource';
|
||||
import { LinkedAccount } from '@server/entity/LinkedAccount';
|
||||
import { User } from '@server/entity/User';
|
||||
import { UserSettings } from '@server/entity/UserSettings';
|
||||
import type {
|
||||
UserSettingsGeneralResponse,
|
||||
UserSettingsLinkedAccount,
|
||||
UserSettingsLinkedAccountResponse,
|
||||
UserSettingsNotificationsResponse,
|
||||
} from '@server/interfaces/api/userSettingsInterfaces';
|
||||
import { Permission } from '@server/lib/permissions';
|
||||
@@ -18,7 +21,7 @@ import { ApiError } from '@server/types/error';
|
||||
import { getHostname } from '@server/utils/getHostname';
|
||||
import { Router } from 'express';
|
||||
import net from 'net';
|
||||
import { Not } from 'typeorm';
|
||||
import { In, Not, type FindOptionsWhere } from 'typeorm';
|
||||
import { canMakePermissionsChange } from '.';
|
||||
|
||||
const isOwnProfile = (): Middleware => {
|
||||
@@ -546,6 +549,73 @@ userSettingsRoutes.delete<{ id: string }>(
|
||||
}
|
||||
);
|
||||
|
||||
userSettingsRoutes.get<{ id: string }, UserSettingsLinkedAccountResponse>(
|
||||
'/linked-accounts',
|
||||
isOwnProfileOrAdmin(),
|
||||
async (req, res) => {
|
||||
const settings = getSettings();
|
||||
if (!settings.main.oidcLogin) {
|
||||
// don't show any linked accounts if OIDC login is disabled
|
||||
return res.status(200).json([]);
|
||||
}
|
||||
|
||||
const activeProviders = settings.oidc.providers.map((p) => p.slug);
|
||||
const linkedAccountsRepository = getRepository(LinkedAccount);
|
||||
|
||||
const linkedAccounts = await linkedAccountsRepository.find({
|
||||
relations: {
|
||||
user: true,
|
||||
},
|
||||
where: {
|
||||
provider: In(activeProviders),
|
||||
user: {
|
||||
id: Number(req.params.id),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const linkedAccountInfo = linkedAccounts.map((acc) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const provider = settings.oidc.providers.find(
|
||||
(p) => p.slug === acc.provider
|
||||
)!;
|
||||
|
||||
return {
|
||||
id: acc.id,
|
||||
username: acc.username,
|
||||
provider: {
|
||||
slug: provider.slug,
|
||||
name: provider.name,
|
||||
logo: provider.logo,
|
||||
},
|
||||
} satisfies UserSettingsLinkedAccount;
|
||||
});
|
||||
|
||||
return res.status(200).json(linkedAccountInfo);
|
||||
}
|
||||
);
|
||||
|
||||
userSettingsRoutes.delete<{ id: string; acctId: string }>(
|
||||
'/linked-accounts/:acctId',
|
||||
isOwnProfileOrAdmin(),
|
||||
async (req, res) => {
|
||||
const linkedAccountsRepository = getRepository(LinkedAccount);
|
||||
const condition: FindOptionsWhere<LinkedAccount> = {
|
||||
id: Number(req.params.acctId),
|
||||
user: {
|
||||
id: Number(req.params.id),
|
||||
},
|
||||
};
|
||||
|
||||
if (await linkedAccountsRepository.exist({ where: condition })) {
|
||||
await linkedAccountsRepository.delete(condition);
|
||||
return res.status(204).send();
|
||||
} else {
|
||||
return res.status(404).send();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
userSettingsRoutes.get<{ id: string }, UserSettingsNotificationsResponse>(
|
||||
'/notifications',
|
||||
isOwnProfileOrAdmin(),
|
||||
|
||||
203
server/utils/oidc.ts
Normal file
203
server/utils/oidc.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import type {
|
||||
IdTokenClaims,
|
||||
OidcProviderMetadata,
|
||||
OidcStandardClaims,
|
||||
OidcTokenResponse,
|
||||
} from '@server/interfaces/api/oidcInterfaces';
|
||||
import type { OidcProvider } from '@server/lib/settings';
|
||||
import type { Request } from 'express';
|
||||
import * as yup from 'yup';
|
||||
|
||||
/** Fetch the issuer configuration from the OpenID Connect Discovery endpoint */
|
||||
export async function getOpenIdConfiguration(domain: string) {
|
||||
// remove trailing slash from url if it exists and add /.well-known/openid-configuration path
|
||||
const wellKnownUrl = new URL(
|
||||
domain.replace(/\/$/, '') + '/.well-known/openid-configuration'
|
||||
).toString();
|
||||
|
||||
const wellKnownInfo: OidcProviderMetadata = await fetch(wellKnownUrl, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}).then((r) => r.json());
|
||||
|
||||
return wellKnownInfo;
|
||||
}
|
||||
|
||||
function getOpenIdCallbackUrl(req: Request, provider: OidcProvider) {
|
||||
const callbackUrl = new URL(
|
||||
`/login`,
|
||||
`${req.protocol}://${req.headers.host}`
|
||||
);
|
||||
callbackUrl.searchParams.set('provider', provider.slug);
|
||||
callbackUrl.searchParams.set('callback', 'true');
|
||||
return callbackUrl.toString();
|
||||
}
|
||||
|
||||
/** Generate authentication request url */
|
||||
export async function getOpenIdRedirectUrl(
|
||||
req: Request,
|
||||
provider: OidcProvider,
|
||||
state: string
|
||||
) {
|
||||
const wellKnownInfo = await getOpenIdConfiguration(provider.issuerUrl);
|
||||
const url = new URL(wellKnownInfo.authorization_endpoint);
|
||||
url.searchParams.set('response_type', 'code');
|
||||
url.searchParams.set('client_id', provider.clientId);
|
||||
|
||||
url.searchParams.set('redirect_uri', getOpenIdCallbackUrl(req, provider));
|
||||
url.searchParams.set('scope', provider.scopes ?? 'openid profile email');
|
||||
url.searchParams.set('state', state);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** Exchange authorization code for token data */
|
||||
export async function fetchOpenIdTokenData(
|
||||
req: Request,
|
||||
provider: OidcProvider,
|
||||
wellKnownInfo: OidcProviderMetadata,
|
||||
code: string
|
||||
): Promise<OidcTokenResponse> {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('client_secret', provider.clientSecret);
|
||||
formData.append('grant_type', 'authorization_code');
|
||||
formData.append('redirect_uri', getOpenIdCallbackUrl(req, provider));
|
||||
formData.append('client_id', provider.clientId);
|
||||
formData.append('code', code);
|
||||
|
||||
return await fetch(wellKnownInfo.token_endpoint, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
}).then((r) => r.json());
|
||||
}
|
||||
|
||||
export async function getOpenIdUserInfo(
|
||||
wellKnownInfo: OidcProviderMetadata,
|
||||
authToken: string
|
||||
) {
|
||||
return fetch(wellKnownInfo.userinfo_endpoint, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
}).then((r) => r.json());
|
||||
}
|
||||
|
||||
class OidcAuthorizationError extends Error {}
|
||||
|
||||
class OidcMissingKeyError extends OidcAuthorizationError {
|
||||
constructor(public userInfo: FullUserInfo, public key: string) {
|
||||
super(`Key ${key} was missing on OIDC userinfo but was expected.`);
|
||||
}
|
||||
}
|
||||
|
||||
type PrimitiveString = 'string' | 'boolean';
|
||||
type TypeFromName<T extends PrimitiveString> = T extends 'string'
|
||||
? string
|
||||
: T extends 'boolean'
|
||||
? boolean
|
||||
: unknown;
|
||||
|
||||
export function tryGetUserInfoKey<T extends PrimitiveString>(
|
||||
userInfo: FullUserInfo,
|
||||
key: string,
|
||||
expectedType: T
|
||||
): TypeFromName<T> {
|
||||
if (!Object.hasOwn(userInfo, key) || typeof userInfo[key] !== expectedType) {
|
||||
throw new OidcMissingKeyError(userInfo, key);
|
||||
}
|
||||
|
||||
return userInfo[key] as TypeFromName<T>;
|
||||
}
|
||||
|
||||
export function validateUserClaims(
|
||||
userInfo: FullUserInfo,
|
||||
requiredClaims: string[]
|
||||
) {
|
||||
requiredClaims.some((claim) => {
|
||||
const value = tryGetUserInfoKey(userInfo, claim, 'boolean');
|
||||
if (!value)
|
||||
throw new OidcAuthorizationError('User was missing a required claim.');
|
||||
});
|
||||
}
|
||||
|
||||
/** Generates a schema to validate ID token JWT and userinfo claims */
|
||||
export const createIdTokenSchema = ({
|
||||
oidcDomain,
|
||||
oidcClientId,
|
||||
requiredClaims,
|
||||
}: {
|
||||
oidcDomain: string;
|
||||
oidcClientId: string;
|
||||
requiredClaims: string[];
|
||||
}) => {
|
||||
return yup.object().shape({
|
||||
iss: yup
|
||||
.string()
|
||||
.oneOf(
|
||||
[oidcDomain, `${oidcDomain}/`],
|
||||
`The token iss value doesn't match the oidc_DOMAIN (${oidcDomain})`
|
||||
)
|
||||
.required("The token didn't come with an iss value."),
|
||||
aud: yup.lazy((val) => {
|
||||
// single audience
|
||||
if (typeof val === 'string')
|
||||
return yup
|
||||
.string()
|
||||
.oneOf(
|
||||
[oidcClientId],
|
||||
`The token aud value doesn't match the oidc_CLIENT_ID (${oidcClientId})`
|
||||
)
|
||||
.required("The token didn't come with an aud value.");
|
||||
// several audiences
|
||||
if (typeof val === 'object' && Array.isArray(val))
|
||||
return yup
|
||||
.array()
|
||||
.of(yup.string())
|
||||
.test(
|
||||
'contains-client-id',
|
||||
`The token aud value doesn't contain the oidc_CLIENT_ID (${oidcClientId})`,
|
||||
(value) => !!(value && value.includes(oidcClientId))
|
||||
);
|
||||
// invalid type
|
||||
return yup
|
||||
.mixed()
|
||||
.typeError('The token aud value is not a string or array.');
|
||||
}),
|
||||
exp: yup
|
||||
.number()
|
||||
.required()
|
||||
.test(
|
||||
'is_before_date',
|
||||
'Token exp value is before current time.',
|
||||
(value) => {
|
||||
if (!value) return false;
|
||||
if (value < Math.ceil(Date.now() / 1000)) return false;
|
||||
return true;
|
||||
}
|
||||
),
|
||||
iat: yup
|
||||
.number()
|
||||
.required()
|
||||
.test(
|
||||
'is_before_one_day',
|
||||
'Token was issued before one day ago and is now invalid.',
|
||||
(value) => {
|
||||
if (!value) return false;
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 1);
|
||||
if (value < Math.ceil(Number(date) / 1000)) return false;
|
||||
return true;
|
||||
}
|
||||
),
|
||||
// TODO: only require this for new user login
|
||||
email: yup.string().required(),
|
||||
// ensure all required claims are present and are booleans
|
||||
...requiredClaims.reduce(
|
||||
(a, v) => ({ ...a, [v]: yup.boolean().required() }),
|
||||
{}
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
export type FullUserInfo = IdTokenClaims & OidcStandardClaims;
|
||||
@@ -31,7 +31,7 @@ type BaseProps<P> = {
|
||||
) => void;
|
||||
};
|
||||
|
||||
type ButtonProps<P extends React.ElementType> = {
|
||||
export type ButtonProps<P extends React.ElementType> = {
|
||||
as?: P;
|
||||
} & MergeElementProps<P, BaseProps<P>>;
|
||||
|
||||
|
||||
@@ -1,31 +1,34 @@
|
||||
import { Field } from 'formik';
|
||||
import { useId } from 'react';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
interface LabeledCheckboxProps {
|
||||
id: string;
|
||||
name: string;
|
||||
className?: string;
|
||||
label: string;
|
||||
description: string;
|
||||
onChange: () => void;
|
||||
onChange?: () => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
const LabeledCheckbox: React.FC<LabeledCheckboxProps> = ({
|
||||
id,
|
||||
name,
|
||||
className,
|
||||
label,
|
||||
description,
|
||||
onChange,
|
||||
children,
|
||||
}) => {
|
||||
const id = useId();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={twMerge('relative flex items-start', className)}>
|
||||
<div className="flex h-6 items-center">
|
||||
<Field type="checkbox" id={id} name={id} onChange={onChange} />
|
||||
<Field type="checkbox" id={id} name={name} onChange={onChange} />
|
||||
</div>
|
||||
<div className="ml-3 text-sm leading-6">
|
||||
<label htmlFor="localLogin" className="block">
|
||||
<label htmlFor={id} className="block">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-white">{label}</span>
|
||||
<span className="font-normal text-gray-400">{description}</span>
|
||||
|
||||
35
src/components/Login/LoginButton.tsx
Normal file
35
src/components/Login/LoginButton.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import Button, { type ButtonProps } from '@app/components/Common/Button';
|
||||
import { SmallLoadingSpinner } from '@app/components/Common/LoadingSpinner';
|
||||
import { type PropsWithChildren } from 'react';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export type LoginButtonProps = ButtonProps<'button'> &
|
||||
PropsWithChildren<{
|
||||
loading?: boolean;
|
||||
}>;
|
||||
|
||||
export default function LoginButton({
|
||||
loading,
|
||||
className,
|
||||
children,
|
||||
...buttonProps
|
||||
}: LoginButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
className={twMerge(
|
||||
'relative flex-grow bg-transparent disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
disabled={loading}
|
||||
{...buttonProps}
|
||||
>
|
||||
{loading && (
|
||||
<div className="absolute right-0 mr-4 h-4 w-4">
|
||||
<SmallLoadingSpinner />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
109
src/components/Login/OidcLoginButton.tsx
Normal file
109
src/components/Login/OidcLoginButton.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import defineMessages from '@app/utils/defineMessages';
|
||||
import type { PublicOidcProvider } from '@server/lib/settings';
|
||||
import axios, { isAxiosError } from 'axios';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useIntl } from 'react-intl';
|
||||
import LoginButton from './LoginButton';
|
||||
|
||||
const messages = defineMessages('components.Login', {
|
||||
oidcLoginError: 'An error occurred while logging in with {provider}.',
|
||||
});
|
||||
|
||||
async function processCallback(params: URLSearchParams, provider: string) {
|
||||
const url = new URL(
|
||||
`/api/v1/auth/oidc/callback/${encodeURIComponent(provider)}`,
|
||||
window.location.origin
|
||||
);
|
||||
url.search = params.toString();
|
||||
|
||||
try {
|
||||
const res = await axios.get(url.toString());
|
||||
|
||||
return {
|
||||
type: 'success',
|
||||
message: res.data,
|
||||
};
|
||||
} catch (e) {
|
||||
if (isAxiosError(e) && e.response?.data?.message) {
|
||||
return { type: 'error', message: e.response.data.message };
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'error',
|
||||
message: e.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type OidcLoginButtonProps = {
|
||||
provider: PublicOidcProvider;
|
||||
onError?: (message: string) => void;
|
||||
};
|
||||
|
||||
export default function OidcLoginButton({
|
||||
provider,
|
||||
onError,
|
||||
}: OidcLoginButtonProps) {
|
||||
const intl = useIntl();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const redirectToLogin = useCallback(async () => {
|
||||
try {
|
||||
const res = await axios.get<{ redirectUrl: string }>(
|
||||
`/api/v1/auth/oidc/login/${provider.slug}`
|
||||
);
|
||||
window.location.href = res.data.redirectUrl;
|
||||
} catch (e) {
|
||||
setLoading(false);
|
||||
onError?.(
|
||||
intl.formatMessage(messages.oidcLoginError, {
|
||||
provider: provider.name,
|
||||
})
|
||||
);
|
||||
}
|
||||
}, [provider, intl, onError]);
|
||||
|
||||
const handleCallback = useCallback(async () => {
|
||||
const result = await processCallback(searchParams, provider.slug);
|
||||
if (result.type === 'success') {
|
||||
// redirect to homepage
|
||||
router.push(result.message?.to ?? '/');
|
||||
} else {
|
||||
setLoading(false);
|
||||
onError?.(
|
||||
intl.formatMessage(messages.oidcLoginError, {
|
||||
provider: provider.name,
|
||||
})
|
||||
);
|
||||
}
|
||||
}, [provider, searchParams, intl, onError, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
const isCallback = searchParams.get('callback') === 'true';
|
||||
const providerSlug = searchParams.get('provider');
|
||||
|
||||
if (providerSlug === provider.slug) {
|
||||
setLoading(true);
|
||||
if (isCallback) handleCallback();
|
||||
else redirectToLogin();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<LoginButton loading={loading} onClick={() => redirectToLogin()}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={provider.logo || '/images/openid.svg'}
|
||||
alt={provider.name}
|
||||
className="mr-2 max-h-5 w-5"
|
||||
/>
|
||||
<span>{provider.name}</span>
|
||||
</LoginButton>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import PlexIcon from '@app/assets/services/plex.svg';
|
||||
import Button from '@app/components/Common/Button';
|
||||
import { SmallLoadingSpinner } from '@app/components/Common/LoadingSpinner';
|
||||
import usePlexLogin from '@app/hooks/usePlexLogin';
|
||||
import defineMessages from '@app/utils/defineMessages';
|
||||
import { FormattedMessage } from 'react-intl';
|
||||
import LoginButton from './LoginButton';
|
||||
|
||||
const messages = defineMessages('components.Login', {
|
||||
loginwithapp: 'Login with {appName}',
|
||||
@@ -25,18 +24,12 @@ const PlexLoginButton = ({
|
||||
const { loading, login } = usePlexLogin({ onAuthToken, onError });
|
||||
|
||||
return (
|
||||
<Button
|
||||
className="relative flex-1 border-[#cc7b19] bg-[rgba(204,123,25,0.3)] hover:border-[#cc7b19] hover:bg-[rgba(204,123,25,0.7)] disabled:opacity-50"
|
||||
<LoginButton
|
||||
className="border-[#cc7b19] bg-[rgba(204,123,25,0.3)] hover:border-[#cc7b19] hover:bg-[rgba(204,123,25,0.7)]"
|
||||
onClick={login}
|
||||
disabled={loading || isProcessing}
|
||||
loading={loading || isProcessing}
|
||||
data-testid="plex-login-button"
|
||||
>
|
||||
{loading && (
|
||||
<div className="absolute right-0 mr-4 h-4 w-4">
|
||||
<SmallLoadingSpinner />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{large ? (
|
||||
<FormattedMessage
|
||||
{...messages.loginwithapp}
|
||||
@@ -55,7 +48,7 @@ const PlexLoginButton = ({
|
||||
) : (
|
||||
<PlexIcon className="w-8" />
|
||||
)}
|
||||
</Button>
|
||||
</LoginButton>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import EmbyLogo from '@app/assets/services/emby-icon-only.svg';
|
||||
import JellyfinLogo from '@app/assets/services/jellyfin-icon.svg';
|
||||
import PlexLogo from '@app/assets/services/plex.svg';
|
||||
import Button from '@app/components/Common/Button';
|
||||
import ImageFader from '@app/components/Common/ImageFader';
|
||||
import PageTitle from '@app/components/Common/PageTitle';
|
||||
import LanguagePicker from '@app/components/Layout/LanguagePicker';
|
||||
import JellyfinLogin from '@app/components/Login/JellyfinLogin';
|
||||
import LocalLogin from '@app/components/Login/LocalLogin';
|
||||
import OidcLoginButton from '@app/components/Login/OidcLoginButton';
|
||||
import PlexLoginButton from '@app/components/Login/PlexLoginButton';
|
||||
import useSettings from '@app/hooks/useSettings';
|
||||
import { useUser } from '@app/hooks/useUser';
|
||||
@@ -21,6 +21,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { useIntl } from 'react-intl';
|
||||
import { CSSTransition, SwitchTransition } from 'react-transition-group';
|
||||
import useSWR from 'swr';
|
||||
import LoginButton from './LoginButton';
|
||||
|
||||
const messages = defineMessages('components.Login', {
|
||||
signin: 'Sign In',
|
||||
@@ -121,10 +122,9 @@ const Login = () => {
|
||||
) : (
|
||||
settings.currentSettings.localLogin &&
|
||||
(mediaServerLogin ? (
|
||||
<Button
|
||||
<LoginButton
|
||||
key="jellyseerr"
|
||||
data-testid="jellyseerr-login-button"
|
||||
className="flex-1 bg-transparent"
|
||||
onClick={() => setMediaServerLogin(false)}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
@@ -134,19 +134,25 @@ const Login = () => {
|
||||
className="mr-2 h-5"
|
||||
/>
|
||||
<span>{settings.currentSettings.applicationTitle}</span>
|
||||
</Button>
|
||||
</LoginButton>
|
||||
) : (
|
||||
<Button
|
||||
<LoginButton
|
||||
key="mediaserver"
|
||||
data-testid="mediaserver-login-button"
|
||||
className="flex-1 bg-transparent"
|
||||
onClick={() => setMediaServerLogin(true)}
|
||||
>
|
||||
<MediaServerLogo />
|
||||
<span>{mediaServerName}</span>
|
||||
</Button>
|
||||
</LoginButton>
|
||||
))
|
||||
)),
|
||||
...settings.currentSettings.openIdProviders.map((provider) => (
|
||||
<OidcLoginButton
|
||||
key={provider.slug}
|
||||
provider={provider}
|
||||
onError={setError}
|
||||
/>
|
||||
)),
|
||||
].filter((o): o is JSX.Element => !!o);
|
||||
|
||||
return (
|
||||
@@ -197,46 +203,50 @@ const Login = () => {
|
||||
</div>
|
||||
</Transition>
|
||||
<div className="px-10 py-8">
|
||||
<SwitchTransition mode="out-in">
|
||||
<CSSTransition
|
||||
key={mediaServerLogin ? 'ms' : 'local'}
|
||||
nodeRef={loginRef}
|
||||
addEndListener={(done) => {
|
||||
loginRef.current?.addEventListener(
|
||||
'transitionend',
|
||||
done,
|
||||
false
|
||||
);
|
||||
}}
|
||||
onEntered={() => {
|
||||
document
|
||||
.querySelector<HTMLInputElement>('#email, #username')
|
||||
?.focus();
|
||||
}}
|
||||
classNames={{
|
||||
appear: 'opacity-0',
|
||||
appearActive: 'transition-opacity duration-500 opacity-100',
|
||||
enter: 'opacity-0',
|
||||
enterActive: 'transition-opacity duration-500 opacity-100',
|
||||
exitActive: 'transition-opacity duration-0 opacity-0',
|
||||
}}
|
||||
>
|
||||
<div ref={loginRef} className="button-container">
|
||||
{isJellyfin &&
|
||||
(mediaServerLogin ||
|
||||
!settings.currentSettings.localLogin) ? (
|
||||
<JellyfinLogin
|
||||
serverType={settings.currentSettings.mediaServerType}
|
||||
revalidate={revalidate}
|
||||
/>
|
||||
) : (
|
||||
settings.currentSettings.localLogin && (
|
||||
<LocalLogin revalidate={revalidate} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</CSSTransition>
|
||||
</SwitchTransition>
|
||||
{loginFormVisible && (
|
||||
<SwitchTransition mode="out-in">
|
||||
<CSSTransition
|
||||
key={mediaServerLogin ? 'ms' : 'local'}
|
||||
nodeRef={loginRef}
|
||||
addEndListener={(done) => {
|
||||
loginRef.current?.addEventListener(
|
||||
'transitionend',
|
||||
done,
|
||||
false
|
||||
);
|
||||
}}
|
||||
onEntered={() => {
|
||||
document
|
||||
.querySelector<HTMLInputElement>('#email, #username')
|
||||
?.focus();
|
||||
}}
|
||||
classNames={{
|
||||
appear: 'opacity-0',
|
||||
appearActive:
|
||||
'transition-opacity duration-500 opacity-100',
|
||||
enter: 'opacity-0',
|
||||
enterActive:
|
||||
'transition-opacity duration-500 opacity-100',
|
||||
exitActive: 'transition-opacity duration-0 opacity-0',
|
||||
}}
|
||||
>
|
||||
<div ref={loginRef} className="button-container">
|
||||
{isJellyfin &&
|
||||
(mediaServerLogin ||
|
||||
!settings.currentSettings.localLogin) ? (
|
||||
<JellyfinLogin
|
||||
serverType={settings.currentSettings.mediaServerType}
|
||||
revalidate={revalidate}
|
||||
/>
|
||||
) : (
|
||||
settings.currentSettings.localLogin && (
|
||||
<LocalLogin revalidate={revalidate} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</CSSTransition>
|
||||
</SwitchTransition>
|
||||
)}
|
||||
|
||||
{additionalLoginOptions.length > 0 &&
|
||||
(loginFormVisible ? (
|
||||
|
||||
366
src/components/Settings/EditOidcModal/index.tsx
Normal file
366
src/components/Settings/EditOidcModal/index.tsx
Normal file
@@ -0,0 +1,366 @@
|
||||
import Accordion from '@app/components/Common/Accordion';
|
||||
import Modal from '@app/components/Common/Modal';
|
||||
import SensitiveInput from '@app/components/Common/SensitiveInput';
|
||||
import globalMessages from '@app/i18n/globalMessages';
|
||||
import defineMessages from '@app/utils/defineMessages';
|
||||
import { Transition } from '@headlessui/react';
|
||||
import { ChevronRightIcon } from '@heroicons/react/20/solid';
|
||||
import { MagnifyingGlassIcon } from '@heroicons/react/24/solid';
|
||||
import type { OidcProvider } from '@server/lib/settings';
|
||||
import axios from 'axios';
|
||||
import { Field, Formik, useFormikContext, type FieldAttributes } from 'formik';
|
||||
import { useEffect } from 'react';
|
||||
import { useIntl } from 'react-intl';
|
||||
import { useToasts } from 'react-toast-notifications';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
import * as Yup from 'yup';
|
||||
|
||||
const messages = defineMessages('settings.settings.SettingsOidc', {
|
||||
required: '{field} is required',
|
||||
url: '{field} must be a valid URL',
|
||||
addoidc: 'Add New OpenID Connect Provider',
|
||||
editoidc: 'Edit {name}',
|
||||
oidcDomain: 'Issuer URL',
|
||||
oidcDomainTip:
|
||||
"The base URL of the identity provider's OpenID Connect endpoint",
|
||||
oidcSlug: 'Provider Slug',
|
||||
oidcSlugTip: 'Unique identifier for the provider',
|
||||
oidcName: 'Provider Name',
|
||||
oidcNameTip: 'Name of the provider which appears on the login screen',
|
||||
oidcClientId: 'Client ID',
|
||||
oidcClientIdTip: 'The Client ID assigned to Jellyseerr',
|
||||
oidcClientSecret: 'Client Secret',
|
||||
oidcClientSecretTip: 'The Client Secret assigned to Jellyseerr',
|
||||
oidcLogo: 'Logo',
|
||||
oidcLogoTip:
|
||||
'The logo to display for the provider. Should be a URL or base64 encoded image',
|
||||
oidcScopes: 'Scopes',
|
||||
oidcScopesTip: 'Space-separated list of scopes to request from the provider',
|
||||
oidcRequiredClaims: 'Required Claims',
|
||||
oidcRequiredClaimsTip:
|
||||
'Space-separated list of boolean claims that are required to log in',
|
||||
oidcNewUserLogin: 'Allow New Users',
|
||||
oidcNewUserLoginTip:
|
||||
'Create accounts for new users logging in with this provider',
|
||||
saveSuccess: 'OpenID Connect provider saved successfully!',
|
||||
saveError: 'Failed to save OpenID Connect provider configuration',
|
||||
});
|
||||
|
||||
interface EditOidcModalProps {
|
||||
show: boolean;
|
||||
provider?: OidcProvider;
|
||||
onClose: () => void;
|
||||
onOk: () => void;
|
||||
}
|
||||
|
||||
function SlugField(props: FieldAttributes<unknown> & { readOnly?: boolean }) {
|
||||
const {
|
||||
values: { name },
|
||||
setFieldValue,
|
||||
} = useFormikContext<Partial<OidcProvider>>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.readOnly)
|
||||
setFieldValue(props.name, name?.toLowerCase().replace(/\s/g, '-'));
|
||||
}, [props.name, props.readOnly, name, setFieldValue]);
|
||||
|
||||
return <Field {...props} />;
|
||||
}
|
||||
|
||||
export default function EditOidcModal(props: EditOidcModalProps) {
|
||||
const intl = useIntl();
|
||||
const { addToast } = useToasts();
|
||||
|
||||
const errorMessage = (
|
||||
field: keyof typeof messages,
|
||||
message: keyof typeof messages = 'required'
|
||||
) =>
|
||||
intl.formatMessage(messages[message], {
|
||||
field: intl.formatMessage(messages[field]),
|
||||
});
|
||||
const oidcSettingsSchema = Yup.object().shape({
|
||||
slug: Yup.string().required(errorMessage('oidcSlug')),
|
||||
name: Yup.string().required(errorMessage('oidcName')),
|
||||
issuerUrl: Yup.string()
|
||||
.url(errorMessage('oidcDomain', 'url'))
|
||||
.required(errorMessage('oidcDomain')),
|
||||
clientId: Yup.string().required(errorMessage('oidcClientId')),
|
||||
clientSecret: Yup.string().required(errorMessage('oidcClientSecret')),
|
||||
logo: Yup.string(),
|
||||
requiredClaims: Yup.string(),
|
||||
scopes: Yup.string(),
|
||||
newUserLogin: Yup.boolean(),
|
||||
});
|
||||
|
||||
const onSubmit = async ({ slug, ...provider }: OidcProvider) => {
|
||||
try {
|
||||
await axios.put(`/api/v1/settings/oidc/${slug}`, provider);
|
||||
|
||||
addToast(intl.formatMessage(messages.saveSuccess), {
|
||||
appearance: 'success',
|
||||
autoDismiss: true,
|
||||
});
|
||||
|
||||
props.onOk();
|
||||
} catch (e) {
|
||||
addToast(intl.formatMessage(messages.saveError), {
|
||||
appearance: 'error',
|
||||
autoDismiss: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Transition show={props.show}>
|
||||
<Formik
|
||||
initialValues={{
|
||||
slug: props.provider?.slug ?? '',
|
||||
name: props.provider?.name ?? '',
|
||||
issuerUrl: props.provider?.issuerUrl ?? '',
|
||||
clientId: props.provider?.clientId ?? '',
|
||||
clientSecret: props.provider?.clientSecret ?? '',
|
||||
logo: props.provider?.logo,
|
||||
requiredClaims: props.provider?.requiredClaims,
|
||||
scopes: props.provider?.scopes,
|
||||
newUserLogin: props.provider?.newUserLogin,
|
||||
}}
|
||||
validationSchema={oidcSettingsSchema}
|
||||
onSubmit={onSubmit}
|
||||
enableReinitialize
|
||||
>
|
||||
{({ handleSubmit, isValid, errors, touched }) => (
|
||||
<Modal
|
||||
onCancel={props.onClose}
|
||||
cancelButtonProps={{ type: 'button' }}
|
||||
okButtonType="primary"
|
||||
okButtonProps={{ type: 'button' }}
|
||||
okDisabled={!isValid}
|
||||
onOk={() => handleSubmit()}
|
||||
okText={intl.formatMessage(globalMessages.save)}
|
||||
title={
|
||||
props.provider
|
||||
? intl.formatMessage(messages.editoidc, {
|
||||
name: props.provider.name,
|
||||
})
|
||||
: intl.formatMessage(messages.addoidc)
|
||||
}
|
||||
>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcName" className="text-label">
|
||||
{intl.formatMessage(messages.oidcName)}
|
||||
<span className="label-required">*</span>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcNameTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<Field id="oidcName" name="name" type="text" />
|
||||
{errors.name &&
|
||||
touched.name &&
|
||||
typeof errors.name === 'string' && (
|
||||
<div className="error">{errors.name}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcLogo" className="text-label">
|
||||
{intl.formatMessage(messages.oidcLogo)}
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcLogoTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<div className="relative">
|
||||
<Field
|
||||
id="oidcLogo"
|
||||
name="logo"
|
||||
type="text"
|
||||
className="pr-10"
|
||||
/>
|
||||
<a
|
||||
className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 transition-colors hover:text-gray-200"
|
||||
href="https://selfh.st/icons"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
>
|
||||
<MagnifyingGlassIcon className="h-4 w-4" />
|
||||
</a>
|
||||
</div>
|
||||
{errors.logo &&
|
||||
touched.logo &&
|
||||
typeof errors.logo === 'string' && (
|
||||
<div className="error">{errors.logo}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcDomain" className="text-label">
|
||||
{intl.formatMessage(messages.oidcDomain)}
|
||||
<span className="label-required">*</span>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcDomainTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<Field id="oidcDomain" name="issuerUrl" type="text" />
|
||||
{errors.issuerUrl &&
|
||||
touched.issuerUrl &&
|
||||
typeof errors.issuerUrl === 'string' && (
|
||||
<div className="error">{errors.issuerUrl}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcClientId" className="text-label">
|
||||
{intl.formatMessage(messages.oidcClientId)}
|
||||
<span className="label-required">*</span>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcClientIdTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<Field id="oidcClientId" name="clientId" type="text" />
|
||||
{errors.clientId &&
|
||||
touched.clientId &&
|
||||
typeof errors.clientId === 'string' && (
|
||||
<div className="error">{errors.clientId}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcClientSecret" className="text-label">
|
||||
{intl.formatMessage(messages.oidcClientSecret)}
|
||||
<span className="label-required">*</span>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcClientSecretTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<div className="flex">
|
||||
<SensitiveInput
|
||||
id="oidcClientSecret"
|
||||
name="clientSecret"
|
||||
as="field"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
{errors.clientSecret &&
|
||||
touched.clientSecret &&
|
||||
typeof errors.clientSecret === 'string' && (
|
||||
<div className="error">{errors.clientSecret}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advanced Settings */}
|
||||
<Accordion>
|
||||
{({ openIndexes, AccordionContent, handleClick }) => (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleClick(0)}
|
||||
className="flex w-full items-center gap-0.5 py-4 font-bold text-gray-400"
|
||||
>
|
||||
<ChevronRightIcon
|
||||
width={18}
|
||||
className={twMerge(
|
||||
'transition-transform',
|
||||
openIndexes.includes(0) ? 'rotate-90' : ''
|
||||
)}
|
||||
/>
|
||||
Advanced Settings
|
||||
</button>
|
||||
<AccordionContent isOpen={openIndexes.includes(0)}>
|
||||
<div className="form-row mt-0">
|
||||
<label htmlFor="oidcSlug" className="text-label">
|
||||
{intl.formatMessage(messages.oidcSlug)}
|
||||
<span className="label-required">*</span>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcSlugTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<SlugField
|
||||
id="oidcSlug"
|
||||
name="slug"
|
||||
type="text"
|
||||
readOnly={props.provider != null}
|
||||
disabled={props.provider != null}
|
||||
className={props.provider != null ? 'opacity-50' : ''}
|
||||
/>
|
||||
{errors.slug &&
|
||||
touched.slug &&
|
||||
typeof errors.slug === 'string' && (
|
||||
<div className="error">{errors.slug}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcScopes" className="text-label">
|
||||
{intl.formatMessage(messages.oidcScopes)}
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcScopesTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<Field id="oidcScopes" name="scopes" type="text" />
|
||||
{errors.scopes &&
|
||||
touched.scopes &&
|
||||
typeof errors.scopes === 'string' && (
|
||||
<div className="error">{errors.scopes}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label
|
||||
htmlFor="oidcRequiredClaims"
|
||||
className="text-label"
|
||||
>
|
||||
{intl.formatMessage(messages.oidcRequiredClaims)}
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcRequiredClaimsTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<Field
|
||||
id="oidcRequiredClaims"
|
||||
name="requiredClaims"
|
||||
type="text"
|
||||
/>
|
||||
{errors.requiredClaims &&
|
||||
touched.requiredClaims &&
|
||||
typeof errors.requiredClaims === 'string' && (
|
||||
<div className="error">{errors.requiredClaims}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="oidcNewUserLogin" className="text-label">
|
||||
{intl.formatMessage(messages.oidcNewUserLogin)}
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.oidcNewUserLoginTip)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input-area">
|
||||
<Field
|
||||
id="oidcNewUserLogin"
|
||||
name="newUserLogin"
|
||||
type="checkbox"
|
||||
/>
|
||||
{errors.newUserLogin &&
|
||||
touched.newUserLogin &&
|
||||
typeof errors.newUserLogin === 'string' && (
|
||||
<div className="error">{errors.newUserLogin}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</>
|
||||
)}
|
||||
</Accordion>
|
||||
</Modal>
|
||||
)}
|
||||
</Formik>
|
||||
</Transition>
|
||||
);
|
||||
}
|
||||
164
src/components/Settings/SettingsOidc/index.tsx
Normal file
164
src/components/Settings/SettingsOidc/index.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import Button from '@app/components/Common/Button';
|
||||
import ConfirmButton from '@app/components/Common/ConfirmButton';
|
||||
import Modal from '@app/components/Common/Modal';
|
||||
import EditOidcModal from '@app/components/Settings/EditOidcModal';
|
||||
import globalMessages from '@app/i18n/globalMessages';
|
||||
import defineMessages from '@app/utils/defineMessages';
|
||||
import { Transition } from '@headlessui/react';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
import { PencilIcon, TrashIcon } from '@heroicons/react/24/solid';
|
||||
import type { OidcProvider, OidcSettings } from '@server/lib/settings';
|
||||
import axios from 'axios';
|
||||
import { useState } from 'react';
|
||||
import { useIntl } from 'react-intl';
|
||||
import { useToasts } from 'react-toast-notifications';
|
||||
import useSWR from 'swr';
|
||||
|
||||
const messages = defineMessages('components.Settings.SettingsOidc', {
|
||||
configureoidc: 'Configure OpenID Connect',
|
||||
addOidcProvider: 'Add OpenID Connect Provider',
|
||||
oidcMatchUsername: 'Allow {mediaServerName} Usernames',
|
||||
oidcMatchUsernameTip:
|
||||
'Match OIDC users with their {mediaServerName} accounts by username',
|
||||
oidcAutomaticLogin: 'Automatic Login',
|
||||
oidcAutomaticLoginTip:
|
||||
'Automatically navigate to the OIDC login and logout pages. This functionality ' +
|
||||
'only supported when OIDC is the exclusive login method.',
|
||||
deleteError: 'Failed to delete OpenID Connect provider',
|
||||
});
|
||||
|
||||
interface SettingsOidcProps {
|
||||
show: boolean;
|
||||
onOk?: () => void;
|
||||
}
|
||||
|
||||
export default function SettingsOidc(props: SettingsOidcProps) {
|
||||
const { addToast } = useToasts();
|
||||
const intl = useIntl();
|
||||
const [editOidcModal, setEditOidcModal] = useState<{
|
||||
open: boolean;
|
||||
provider?: OidcProvider;
|
||||
}>({
|
||||
open: false,
|
||||
provider: undefined,
|
||||
});
|
||||
const { data, mutate: revalidate } = useSWR<OidcSettings>(
|
||||
'/api/v1/settings/oidc'
|
||||
);
|
||||
|
||||
async function onDelete(provider: OidcProvider) {
|
||||
try {
|
||||
const response = await axios.delete<OidcSettings>(
|
||||
`/api/v1/settings/oidc/${provider.slug}`
|
||||
);
|
||||
revalidate(response.data);
|
||||
} catch (e) {
|
||||
addToast(intl.formatMessage(messages.deleteError), {
|
||||
autoDismiss: true,
|
||||
appearance: 'error',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Transition show={props.show}>
|
||||
<Modal
|
||||
okText={intl.formatMessage(globalMessages.close)}
|
||||
onOk={props.onOk}
|
||||
okButtonProps={{ type: 'button' }}
|
||||
title={intl.formatMessage(messages.configureoidc)}
|
||||
backgroundClickable={false}
|
||||
>
|
||||
<ul className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
{data?.providers.map((provider) => (
|
||||
<li
|
||||
className="col-span-1 flex flex-col justify-between rounded-lg bg-gray-700 shadow ring-1 ring-gray-500"
|
||||
key={provider.slug}
|
||||
>
|
||||
<div className="jusfity-between flex w-full items-center space-x-6 p-6">
|
||||
<div className="flex-1 truncate">
|
||||
<div className="mb-2 flex items-center space-x-2">
|
||||
<h3 className="truncate text-lg font-bold leading-5 text-white">
|
||||
{provider.name}
|
||||
</h3>
|
||||
</div>
|
||||
<p className="mt-1 truncate text-sm leading-5 text-gray-300">
|
||||
<span className="mr-2 font-bold">Issuer URL</span>
|
||||
{provider.issuerUrl}
|
||||
</p>
|
||||
<p className="mt-1 truncate text-sm leading-5 text-gray-300">
|
||||
<span className="mr-2 font-bold">Client ID</span>
|
||||
{provider.clientId}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={provider.logo || '/images/openid.svg'}
|
||||
alt={provider.name}
|
||||
className="h-10 w-10 flex-shrink-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-500">
|
||||
<div className="-mt-px flex">
|
||||
<div className="flex w-0 flex-1 border-r border-gray-500">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setEditOidcModal({ open: true, provider })
|
||||
}
|
||||
className="focus:ring-blue relative -mr-px inline-flex w-0 flex-1 items-center justify-center rounded-bl-lg border border-transparent py-4 text-sm font-medium leading-5 text-gray-200 transition duration-150 ease-in-out hover:text-white focus:z-10 focus:border-gray-500 focus:outline-none"
|
||||
>
|
||||
<PencilIcon className="mr-2 h-5 w-5" />
|
||||
<span>{intl.formatMessage(globalMessages.edit)}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="-ml-px flex w-0 flex-1">
|
||||
<ConfirmButton
|
||||
onClick={() => onDelete(provider)}
|
||||
className="focus:ring-blue relative inline-flex w-0 flex-1 items-center justify-center rounded-none rounded-br-lg border border-transparent py-4 text-sm font-medium leading-5 text-gray-200 transition duration-150 ease-in-out hover:text-white focus:z-10 focus:border-gray-500 focus:outline-none"
|
||||
confirmText={intl.formatMessage(
|
||||
globalMessages.areyousure
|
||||
)}
|
||||
>
|
||||
<TrashIcon className="mr-2 h-5 w-5" />
|
||||
<span>{intl.formatMessage(globalMessages.delete)}</span>
|
||||
</ConfirmButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
|
||||
<li className="col-span-1 h-32 rounded-lg border-2 border-dashed border-gray-400 shadow sm:h-44">
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
buttonType="ghost"
|
||||
className="mt-3 mb-3"
|
||||
onClick={() => setEditOidcModal({ open: true })}
|
||||
>
|
||||
<PlusIcon />
|
||||
<span>{intl.formatMessage(messages.addOidcProvider)}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</Modal>
|
||||
</Transition>
|
||||
|
||||
<EditOidcModal
|
||||
show={editOidcModal.open}
|
||||
provider={editOidcModal.provider}
|
||||
onClose={() => setEditOidcModal((prev) => ({ ...prev, open: false }))}
|
||||
onOk={() => {
|
||||
revalidate();
|
||||
// preserve the provider so that it doesn't disappear while the dialog is closing
|
||||
setEditOidcModal((prev) => ({ ...prev, open: false }));
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,14 +4,16 @@ import LoadingSpinner from '@app/components/Common/LoadingSpinner';
|
||||
import PageTitle from '@app/components/Common/PageTitle';
|
||||
import PermissionEdit from '@app/components/PermissionEdit';
|
||||
import QuotaSelector from '@app/components/QuotaSelector';
|
||||
import SettingsOidc from '@app/components/Settings/SettingsOidc';
|
||||
import useSettings from '@app/hooks/useSettings';
|
||||
import globalMessages from '@app/i18n/globalMessages';
|
||||
import defineMessages from '@app/utils/defineMessages';
|
||||
import { ArrowDownOnSquareIcon } from '@heroicons/react/24/outline';
|
||||
import { ArrowDownOnSquareIcon, CogIcon } from '@heroicons/react/24/outline';
|
||||
import { MediaServerType } from '@server/constants/server';
|
||||
import type { MainSettings } from '@server/lib/settings';
|
||||
import axios from 'axios';
|
||||
import { Field, Form, Formik } from 'formik';
|
||||
import { useState } from 'react';
|
||||
import { useIntl } from 'react-intl';
|
||||
import { useToasts } from 'react-toast-notifications';
|
||||
import useSWR, { mutate } from 'swr';
|
||||
@@ -31,6 +33,9 @@ const messages = defineMessages('components.Settings.SettingsUsers', {
|
||||
mediaServerLogin: 'Enable {mediaServerName} Sign-In',
|
||||
mediaServerLoginTip:
|
||||
'Allow users to sign in using their {mediaServerName} account',
|
||||
oidcLogin: 'Enable OpenID Connect Sign-In',
|
||||
oidcLoginTip:
|
||||
'Allow users to sign in using OpenID Connect identity providers',
|
||||
atLeastOneAuth: 'At least one authentication method must be selected.',
|
||||
newPlexLogin: 'Enable New {mediaServerName} Sign-In',
|
||||
newPlexLoginTip:
|
||||
@@ -50,23 +55,25 @@ const SettingsUsers = () => {
|
||||
mutate: revalidate,
|
||||
} = useSWR<MainSettings>('/api/v1/settings/main');
|
||||
const settings = useSettings();
|
||||
const [showOidcDialog, setShowOidcDialog] = useState(false);
|
||||
|
||||
const schema = yup
|
||||
.object()
|
||||
.shape({
|
||||
localLogin: yup.boolean(),
|
||||
mediaServerLogin: yup.boolean(),
|
||||
oidcLogin: yup.boolean(),
|
||||
})
|
||||
.test({
|
||||
name: 'atLeastOneAuth',
|
||||
test: function (values) {
|
||||
const isValid = ['localLogin', 'mediaServerLogin'].some(
|
||||
const isValid = ['localLogin', 'mediaServerLogin', 'oidcLogin'].some(
|
||||
(field) => !!values[field]
|
||||
);
|
||||
|
||||
if (isValid) return true;
|
||||
return this.createError({
|
||||
path: 'localLogin | mediaServerLogin',
|
||||
path: 'localLogin | mediaServerLogin | oidcLogin',
|
||||
message: intl.formatMessage(messages.atLeastOneAuth),
|
||||
});
|
||||
},
|
||||
@@ -106,6 +113,7 @@ const SettingsUsers = () => {
|
||||
initialValues={{
|
||||
localLogin: data?.localLogin,
|
||||
mediaServerLogin: data?.mediaServerLogin,
|
||||
oidcLogin: data?.oidcLogin,
|
||||
newPlexLogin: data?.newPlexLogin,
|
||||
movieQuotaLimit: data?.defaultQuotas.movie.quotaLimit ?? 0,
|
||||
movieQuotaDays: data?.defaultQuotas.movie.quotaDays ?? 7,
|
||||
@@ -120,6 +128,7 @@ const SettingsUsers = () => {
|
||||
await axios.post('/api/v1/settings/main', {
|
||||
localLogin: values.localLogin,
|
||||
mediaServerLogin: values.mediaServerLogin,
|
||||
oidcLogin: values.oidcLogin,
|
||||
newPlexLogin: values.newPlexLogin,
|
||||
defaultQuotas: {
|
||||
movie: {
|
||||
@@ -163,16 +172,21 @@ const SettingsUsers = () => {
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.loginMethodsTip)}
|
||||
</span>
|
||||
{'localLogin | mediaServerLogin' in errors && (
|
||||
{'localLogin | mediaServerLogin | oidcLogin' in
|
||||
errors && (
|
||||
<span className="error">
|
||||
{errors['localLogin | mediaServerLogin'] as string}
|
||||
{
|
||||
errors[
|
||||
'localLogin | mediaServerLogin | oidcLogin'
|
||||
] as string
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<div className="form-input-area max-w-lg">
|
||||
<LabeledCheckbox
|
||||
id="localLogin"
|
||||
name="localLogin"
|
||||
label={intl.formatMessage(messages.localLogin)}
|
||||
description={intl.formatMessage(
|
||||
messages.localLoginTip,
|
||||
@@ -183,7 +197,7 @@ const SettingsUsers = () => {
|
||||
}
|
||||
/>
|
||||
<LabeledCheckbox
|
||||
id="mediaServerLogin"
|
||||
name="mediaServerLogin"
|
||||
className="mt-4"
|
||||
label={intl.formatMessage(
|
||||
messages.mediaServerLogin,
|
||||
@@ -200,10 +214,41 @@ const SettingsUsers = () => {
|
||||
)
|
||||
}
|
||||
/>
|
||||
<div className="mt-4 flex justify-between">
|
||||
<LabeledCheckbox
|
||||
name="oidcLogin"
|
||||
label={intl.formatMessage(
|
||||
messages.oidcLogin,
|
||||
mediaServerFormatValues
|
||||
)}
|
||||
description={intl.formatMessage(
|
||||
messages.oidcLoginTip,
|
||||
mediaServerFormatValues
|
||||
)}
|
||||
onChange={() => {
|
||||
const newValue = !values.oidcLogin;
|
||||
setFieldValue('oidcLogin', newValue);
|
||||
if (newValue) setShowOidcDialog(true);
|
||||
}}
|
||||
/>
|
||||
{values.oidcLogin && (
|
||||
<CogIcon
|
||||
className="w-8 cursor-pointer text-gray-400"
|
||||
onClick={() => setShowOidcDialog(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{values.oidcLogin && (
|
||||
<SettingsOidc
|
||||
show={showOidcDialog}
|
||||
onOk={() => setShowOidcDialog(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="form-row">
|
||||
<label htmlFor="newPlexLogin" className="checkbox-label">
|
||||
{intl.formatMessage(
|
||||
|
||||
@@ -12,6 +12,10 @@ import defineMessages from '@app/utils/defineMessages';
|
||||
import PlexOAuth from '@app/utils/plex';
|
||||
import { TrashIcon } from '@heroicons/react/24/solid';
|
||||
import { MediaServerType } from '@server/constants/server';
|
||||
import type {
|
||||
UserSettingsLinkedAccount,
|
||||
UserSettingsLinkedAccountResponse,
|
||||
} from '@server/interfaces/api/userSettingsInterfaces';
|
||||
import axios from 'axios';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useMemo, useState } from 'react';
|
||||
@@ -42,12 +46,20 @@ enum LinkedAccountType {
|
||||
Plex = 'Plex',
|
||||
Jellyfin = 'Jellyfin',
|
||||
Emby = 'Emby',
|
||||
OpenIdConnect = 'oidc',
|
||||
}
|
||||
|
||||
type LinkedAccount = {
|
||||
type: LinkedAccountType;
|
||||
username: string;
|
||||
};
|
||||
type LinkedAccount =
|
||||
| {
|
||||
type:
|
||||
| LinkedAccountType.Plex
|
||||
| LinkedAccountType.Emby
|
||||
| LinkedAccountType.Jellyfin;
|
||||
username: string;
|
||||
}
|
||||
| ({
|
||||
type: LinkedAccountType.OpenIdConnect;
|
||||
} & UserSettingsLinkedAccount);
|
||||
|
||||
const UserLinkedAccountsSettings = () => {
|
||||
const intl = useIntl();
|
||||
@@ -62,13 +74,21 @@ const UserLinkedAccountsSettings = () => {
|
||||
const { data: passwordInfo } = useSWR<{ hasPassword: boolean }>(
|
||||
user ? `/api/v1/user/${user?.id}/settings/password` : null
|
||||
);
|
||||
const { data: linkedOidcAccounts, mutate: revalidateLinkedAccounts } =
|
||||
useSWR<UserSettingsLinkedAccountResponse>(
|
||||
user ? `/api/v1/user/${user?.id}/settings/linked-accounts` : null
|
||||
);
|
||||
const [showJellyfinModal, setShowJellyfinModal] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const applicationName = settings.currentSettings.applicationTitle;
|
||||
|
||||
const accounts: LinkedAccount[] = useMemo(() => {
|
||||
const accounts: LinkedAccount[] = [];
|
||||
const accounts: LinkedAccount[] =
|
||||
linkedOidcAccounts?.map((a) => ({
|
||||
type: LinkedAccountType.OpenIdConnect,
|
||||
...a,
|
||||
})) ?? [];
|
||||
if (!user) return accounts;
|
||||
if (user.userType === UserType.PLEX && user.plexUsername)
|
||||
accounts.push({
|
||||
@@ -86,7 +106,7 @@ const UserLinkedAccountsSettings = () => {
|
||||
username: user.jellyfinUsername,
|
||||
});
|
||||
return accounts;
|
||||
}, [user]);
|
||||
}, [user, linkedOidcAccounts]);
|
||||
|
||||
const linkPlexAccount = async () => {
|
||||
setError(null);
|
||||
@@ -136,6 +156,24 @@ const UserLinkedAccountsSettings = () => {
|
||||
settings.currentSettings.mediaServerType !== MediaServerType.EMBY ||
|
||||
accounts.some((a) => a.type === LinkedAccountType.Emby),
|
||||
},
|
||||
...settings.currentSettings.openIdProviders.map((p) => ({
|
||||
name: p.name,
|
||||
action: async () => {
|
||||
try {
|
||||
const res = await axios.get<{ redirectUrl: string }>(
|
||||
`/api/v1/auth/oidc/login/${p.slug}`
|
||||
);
|
||||
window.location.href = res.data.redirectUrl;
|
||||
} catch (e) {
|
||||
setError(intl.formatMessage(messages.errorUnknown));
|
||||
}
|
||||
},
|
||||
hide: accounts.some(
|
||||
(a) =>
|
||||
a.type === LinkedAccountType.OpenIdConnect &&
|
||||
a.provider.slug === p.slug
|
||||
),
|
||||
})),
|
||||
].filter((l) => !l.hide);
|
||||
|
||||
const deleteRequest = async (account: string) => {
|
||||
@@ -148,6 +186,7 @@ const UserLinkedAccountsSettings = () => {
|
||||
}
|
||||
|
||||
await revalidateUser();
|
||||
await revalidateLinkedAccounts();
|
||||
};
|
||||
|
||||
if (
|
||||
@@ -196,7 +235,7 @@ const UserLinkedAccountsSettings = () => {
|
||||
<div>
|
||||
<Dropdown text="Link Account" buttonType="ghost">
|
||||
{linkable.map(({ name, action }) => (
|
||||
<Dropdown.Item key={name} onClick={action}>
|
||||
<Dropdown.Item key={name} onClick={action} buttonType="ghost">
|
||||
{name}
|
||||
</Dropdown.Item>
|
||||
))}
|
||||
@@ -219,24 +258,37 @@ const UserLinkedAccountsSettings = () => {
|
||||
</div>
|
||||
) : acct.type === LinkedAccountType.Emby ? (
|
||||
<EmbyLogo />
|
||||
) : (
|
||||
) : acct.type === LinkedAccountType.Jellyfin ? (
|
||||
<JellyfinLogo />
|
||||
)}
|
||||
) : acct.type === LinkedAccountType.OpenIdConnect ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={acct.provider.logo ?? '/images/openid.svg'}
|
||||
alt={acct.provider.name}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div>
|
||||
<div className="truncate text-sm font-bold text-gray-300">
|
||||
{acct.type}
|
||||
{acct.type === LinkedAccountType.OpenIdConnect
|
||||
? acct.provider.name
|
||||
: acct.type}
|
||||
</div>
|
||||
<div className="text-xl font-semibold text-white">
|
||||
{acct.username}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-grow" />
|
||||
{enableMediaServerUnlink && (
|
||||
{(acct.type === LinkedAccountType.OpenIdConnect ||
|
||||
enableMediaServerUnlink) && (
|
||||
<ConfirmButton
|
||||
onClick={() => {
|
||||
deleteRequest(
|
||||
acct.type === LinkedAccountType.Plex ? 'plex' : 'jellyfin'
|
||||
acct.type === LinkedAccountType.OpenIdConnect
|
||||
? String(acct.id)
|
||||
: acct.type === LinkedAccountType.Plex
|
||||
? 'plex'
|
||||
: 'jellyfin'
|
||||
);
|
||||
}}
|
||||
confirmText={intl.formatMessage(globalMessages.areyousure)}
|
||||
|
||||
@@ -8,7 +8,7 @@ export interface SettingsContextProps {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
const defaultSettings = {
|
||||
const defaultSettings: PublicSettingsResponse = {
|
||||
initialized: false,
|
||||
applicationTitle: 'Jellyseerr',
|
||||
applicationUrl: '',
|
||||
@@ -31,6 +31,7 @@ const defaultSettings = {
|
||||
emailEnabled: false,
|
||||
newPlexLogin: true,
|
||||
youtubeUrl: '',
|
||||
openIdProviders: [],
|
||||
};
|
||||
|
||||
export const SettingsContext = React.createContext<SettingsContextProps>({
|
||||
|
||||
@@ -253,6 +253,7 @@
|
||||
"components.Login.loginerror": "Something went wrong while trying to sign in.",
|
||||
"components.Login.loginwithapp": "Login with {appName}",
|
||||
"components.Login.noadminerror": "No admin user found on the server.",
|
||||
"components.Login.oidcLoginError": "An error occurred while logging in with {provider}.",
|
||||
"components.Login.orsigninwith": "Or sign in with",
|
||||
"components.Login.password": "Password",
|
||||
"components.Login.port": "Port",
|
||||
@@ -1033,6 +1034,8 @@
|
||||
"components.Settings.SettingsUsers.movieRequestLimitLabel": "Global Movie Request Limit",
|
||||
"components.Settings.SettingsUsers.newPlexLogin": "Enable New {mediaServerName} Sign-In",
|
||||
"components.Settings.SettingsUsers.newPlexLoginTip": "Allow {mediaServerName} users to sign in without first being imported",
|
||||
"components.Settings.SettingsUsers.oidcLogin": "Enable OpenID Connect Sign-In",
|
||||
"components.Settings.SettingsUsers.oidcLoginTip": "Allow users to sign in using OpenID Connect identity providers",
|
||||
"components.Settings.SettingsUsers.toastSettingsFailure": "Something went wrong while saving settings.",
|
||||
"components.Settings.SettingsUsers.toastSettingsSuccess": "User settings saved successfully!",
|
||||
"components.Settings.SettingsUsers.tvRequestLimitLabel": "Global Series Request Limit",
|
||||
@@ -1600,5 +1603,29 @@
|
||||
"pages.pagenotfound": "Page Not Found",
|
||||
"pages.returnHome": "Return Home",
|
||||
"pages.serviceunavailable": "Service Unavailable",
|
||||
"pages.somethingwentwrong": "Something Went Wrong"
|
||||
"pages.somethingwentwrong": "Something Went Wrong",
|
||||
"settings.settings.SettingsOidc.addoidc": "Add New OpenID Connect Provider",
|
||||
"settings.settings.SettingsOidc.editoidc": "Edit {name}",
|
||||
"settings.settings.SettingsOidc.oidcClientId": "Client ID",
|
||||
"settings.settings.SettingsOidc.oidcClientIdTip": "The Client ID assigned to Jellyseerr",
|
||||
"settings.settings.SettingsOidc.oidcClientSecret": "Client Secret",
|
||||
"settings.settings.SettingsOidc.oidcClientSecretTip": "The Client Secret assigned to Jellyseerr",
|
||||
"settings.settings.SettingsOidc.oidcDomain": "Issuer URL",
|
||||
"settings.settings.SettingsOidc.oidcDomainTip": "The base URL of the identity provider's OpenID Connect endpoint",
|
||||
"settings.settings.SettingsOidc.oidcLogo": "Logo",
|
||||
"settings.settings.SettingsOidc.oidcLogoTip": "The logo to display for the provider. Should be a URL or base64 encoded image",
|
||||
"settings.settings.SettingsOidc.oidcName": "Provider Name",
|
||||
"settings.settings.SettingsOidc.oidcNameTip": "Name of the provider which appears on the login screen",
|
||||
"settings.settings.SettingsOidc.oidcNewUserLogin": "Allow New Users",
|
||||
"settings.settings.SettingsOidc.oidcNewUserLoginTip": "Create accounts for new users logging in with this provider",
|
||||
"settings.settings.SettingsOidc.oidcRequiredClaims": "Required Claims",
|
||||
"settings.settings.SettingsOidc.oidcRequiredClaimsTip": "Space-separated list of boolean claims that are required to log in",
|
||||
"settings.settings.SettingsOidc.oidcScopes": "Scopes",
|
||||
"settings.settings.SettingsOidc.oidcScopesTip": "Space-separated list of scopes to request from the provider",
|
||||
"settings.settings.SettingsOidc.oidcSlug": "Provider Slug",
|
||||
"settings.settings.SettingsOidc.oidcSlugTip": "Unique identifier for the provider",
|
||||
"settings.settings.SettingsOidc.required": "{field} is required",
|
||||
"settings.settings.SettingsOidc.saveError": "Failed to save OpenID Connect provider configuration",
|
||||
"settings.settings.SettingsOidc.saveSuccess": "OpenID Connect provider saved successfully!",
|
||||
"settings.settings.SettingsOidc.url": "{field} must be a valid URL"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@ CoreApp.getInitialProps = async (initialProps) => {
|
||||
series4kEnabled: false,
|
||||
localLogin: true,
|
||||
mediaServerLogin: true,
|
||||
openIdProviders: [],
|
||||
discoverRegion: '',
|
||||
streamingRegion: '',
|
||||
originalLanguage: '',
|
||||
@@ -286,7 +287,10 @@ CoreApp.getInitialProps = async (initialProps) => {
|
||||
);
|
||||
user = response.data;
|
||||
|
||||
if (router.pathname.match(/(setup|login)/)) {
|
||||
if (
|
||||
router.pathname.match(/(setup|login)/) &&
|
||||
!router.query.callback === true
|
||||
) {
|
||||
ctx.res.writeHead(307, {
|
||||
Location: '/',
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user