diff --git a/docs/extending-overseerr/reverse-proxy.md b/docs/extending-overseerr/reverse-proxy.md index 84752f7c2..ec456fdbc 100644 --- a/docs/extending-overseerr/reverse-proxy.md +++ b/docs/extending-overseerr/reverse-proxy.md @@ -141,7 +141,7 @@ location ^~ /overseerr { sub_filter '\/_next' '\/$app\/_next'; sub_filter '/_next' '/$app/_next'; sub_filter '/api/v1' '/$app/api/v1'; - sub_filter '/login/plex/loading' '/$app/login/plex/loading'; + sub_filter '/login/popup/loading' '/$app/login/popup/loading'; sub_filter '/images/' '/$app/images/'; sub_filter '/android-' '/$app/android-'; sub_filter '/apple-' '/$app/apple-'; diff --git a/docs/using-overseerr/settings/README.md b/docs/using-overseerr/settings/README.md index 477129fc9..798bee17b 100644 --- a/docs/using-overseerr/settings/README.md +++ b/docs/using-overseerr/settings/README.md @@ -80,6 +80,68 @@ When disabled, Plex OAuth becomes the only sign-in option, and any "local users" This setting is **enabled** by default. +### Enable Media Server Sign-In + +When enabled, users will be able to sign in on the login screen using their Plex / Jellyfin accounts. + +When disabled, local sign-in will be the only option. + +This setting is **enabled** by default. + +### Enable OIDC Sign-In + +When enabled, allows users to sign in to local accounts using an OIDC identity provider, which requires additional configuration. + +For this setting to function properly, the OIDC Issuer URL, Provider Name, Client ID, and Client Secret must all be properly set. + +This setting is **disabled** by default. + +### OIDC Settings + +#### Issuer URL + +Sets the base URL of the identity provider's OpenID Connect endpoint. A valid URL for this setting should have a discovery endpoint at `/.well-known/openid-configuration` as outlined in the [OpenID Connect Discovery specification](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig). + +#### Provider Name + +Sets the name that should be shown for the OIDC login option on the login screen. + +For example, setting the Provider Name option to "My Incredible Login Page" would make a button with the text "Sign in with My Incredible Login Page" appear on the login page. + +#### Client ID + +Sets the client ID Jellyseerr should use when communicating with the configured identity provider. + +#### Client Secret + +Sets the client secret Jellyseerr should use when communicating with the configured identity provider. + +#### Scopes + +Sets the scopes that should be requested from the identity provider when logging in, as described in the [OpenID Connect specification](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims). This is an advanced setting, and the default value (`email openid profile`) should be sufficient for most configurations. + +#### Identification Claims + +Sets the string-typed claims that should be used to identify a user. These claims are matched to the user's unique identifier (email). This is an advanced setting, and the default value (`email`) should be sufficient for most configurations. + +#### Required Claims + +Sets the boolean-typed claims that should be required for a user to successfully log in. This is an advanced setting, and the default value (`email_verified`) should be sufficient for most configurations. If requiring a verified email address is not desired, it is possible to leave this field blank. + +#### Allow Plex / Jellyfin Usernames + +When enabled, a user's identification claims are matched not only against their email, but against their Plex / Jellyfin username. This is an advanced setting, and enabling it will likely result in reduced security due to the ease of changing / spoofing usernames. + +This setting may be helpful, however, for scenarios when the OpenID connect provider and Plex / Jellyfin's usernames are equivalent for all users. It may be helpful to add `preferred_username` or another of the [standard OpenID Connect claims](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) to the [Identification Claims](#identification-claims) setting to enable matching Plex / Jellyfin usernames to the usernames obtained from the identity provider. + +This setting is **disabled** by default. + +#### Automatic Login + +When enabled, OpenID Connect authentication will replace the built-in authentication mechanism. The login page will automatically redirect to the OpenID Connect identity provider, and logging out will trigger an OpenID Connect logout flow. This setting may only be enabled if OIDC Sign-In is the only enabled authentication mechanism. + +This setting is **disabled** by default. + ### Enable New Plex Sign-In When enabled, users with access to your Plex server will be able to sign in to Overseerr 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. diff --git a/overseerr-api.yml b/overseerr-api.yml index 3cb42284c..a40ea1ff3 100644 --- a/overseerr-api.yml +++ b/overseerr-api.yml @@ -132,6 +132,36 @@ components: type: string originalLanguage: type: string + OidcSettings: + type: object + properties: + providerName: + type: string + example: Keycloak + providerUrl: + type: string + example: https://auth.example.com + clientId: + type: string + example: your-client-id + clientSecret: + type: string + example: your-client-secret + userIdentifier: + type: string + example: email + requiredClaims: + type: string + example: email_verified + scopes: + type: string + example: id email + matchJellyfinUsername: + type: boolean + example: false + automaticLogin: + type: boolean + example: false MainSettings: type: object properties: @@ -162,6 +192,14 @@ components: localLogin: type: boolean example: true + mediaServerLogin: + type: boolean + example: true + oidcLogin: + type: boolean + example: true + oidc: + $ref: '#/components/schemas/OidcSettings' mediaServerType: type: number example: 1 @@ -3699,6 +3737,79 @@ paths: type: string required: - password + /auth/oidc-login: + 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 + responses: + '302': + description: Redirect to the authentication url for the OpenID Connect provider + headers: + Location: + schema: + 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 + Set-Cookie: + schema: + type: string + example: 'oidc-state=123456789; HttpOnly; max-age=60000; Secure' + /auth/oidc-callback: + 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 + parameters: + - 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' + tags: + - auth + 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/oidc-logout: + get: + security: [] + summary: Redirect to the OpenID Connect provider logout page + description: Determines the logout redirect URL for to the OpenID Connect provider, and redirects the user to it. + tags: + - auth + responses: + '302': + description: Redirect to the logout url for the OpenID Connect provider + headers: + Location: + schema: + type: string + example: https://example.com/auth/oidc/invalidate_session /user: get: summary: Get all users diff --git a/package.json b/package.json index 97c025503..c26b1842f 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "formik": "2.2.9", "gravatar-url": "3.1.0", "intl": "1.2.5", + "jwt-decode": "^3.1.2", "lodash": "4.17.21", "next": "12.3.4", "node-cache": "5.1.2", diff --git a/server/entity/User.ts b/server/entity/User.ts index e4c8314c3..2cf06c58a 100644 --- a/server/entity/User.ts +++ b/server/entity/User.ts @@ -24,6 +24,7 @@ import { PrimaryGeneratedColumn, RelationCount, UpdateDateColumn, + type FindOperator, } from 'typeorm'; import Issue from './Issue'; import { MediaRequest } from './MediaRequest'; @@ -51,7 +52,12 @@ export class User { unique: true, transformer: { from: (value: string): string => (value ?? '').toLowerCase(), - to: (value: string): string => (value ?? '').toLowerCase(), + to: ( + value: string | FindOperator + ): string | FindOperator => { + if (typeof value === 'string') return (value ?? '').toLowerCase(); + return value; + }, }, }) public email: string; diff --git a/server/interfaces/api/oidcInterfaces.ts b/server/interfaces/api/oidcInterfaces.ts new file mode 100644 index 000000000..68d444b56 --- /dev/null +++ b/server/interfaces/api/oidcInterfaces.ts @@ -0,0 +1,239 @@ +/** + * @internal + */ +type Mandatory = Required> & Omit; + +/** + * 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, + Mandatory { + [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; diff --git a/server/interfaces/api/settingsInterfaces.ts b/server/interfaces/api/settingsInterfaces.ts index 1bf40cdbc..f87370e94 100644 --- a/server/interfaces/api/settingsInterfaces.ts +++ b/server/interfaces/api/settingsInterfaces.ts @@ -30,6 +30,10 @@ export interface PublicSettingsResponse { applicationUrl: string; hideAvailable: boolean; localLogin: boolean; + mediaServerLogin: boolean; + oidcLogin: boolean; + oidcProviderName: string; + oidcAutomaticLogin: boolean; movie4kEnabled: boolean; series4kEnabled: boolean; region: string; diff --git a/server/lib/settings.ts b/server/lib/settings.ts index 63f952363..063b29e66 100644 --- a/server/lib/settings.ts +++ b/server/lib/settings.ts @@ -107,7 +107,20 @@ export interface MainSettings { }; hideAvailable: boolean; localLogin: boolean; + mediaServerLogin: boolean; + oidcLogin: boolean; newPlexLogin: boolean; + oidc: { + providerName: string; + providerUrl: string; + clientId: string; + clientSecret: string; + userIdentifier: string; + requiredClaims: string; + scopes: string; + matchJellyfinUsername: boolean; + automaticLogin: boolean; + }; region: string; originalLanguage: string; trustProxy: boolean; @@ -125,6 +138,10 @@ interface FullPublicSettings extends PublicSettings { applicationUrl: string; hideAvailable: boolean; localLogin: boolean; + mediaServerLogin: boolean; + oidcLogin: boolean; + oidcProviderName: string; + oidcAutomaticLogin: boolean; movie4kEnabled: boolean; series4kEnabled: boolean; region: string; @@ -314,7 +331,20 @@ class Settings { }, hideAvailable: false, localLogin: true, + mediaServerLogin: true, newPlexLogin: true, + oidcLogin: false, + oidc: { + providerName: 'OpenID Connect', + providerUrl: '', + clientId: '', + clientSecret: '', + userIdentifier: 'email', + requiredClaims: 'email_verified', + scopes: 'email openid profile', + matchJellyfinUsername: false, + automaticLogin: false, + }, region: '', originalLanguage: '', trustProxy: false, @@ -537,7 +567,10 @@ class Settings { applicationUrl: this.data.main.applicationUrl, hideAvailable: this.data.main.hideAvailable, localLogin: this.data.main.localLogin, - jellyfinForgotPasswordUrl: this.data.jellyfin.jellyfinForgotPasswordUrl, + mediaServerLogin: this.data.main.mediaServerLogin, + oidcLogin: this.data.main.oidcLogin, + oidcProviderName: this.data.main.oidc.providerName, + oidcAutomaticLogin: this.data.main.oidc.automaticLogin, movie4kEnabled: this.data.radarr.some( (radarr) => radarr.is4k && radarr.isDefault ), @@ -549,6 +582,7 @@ class Settings { mediaServerType: this.main.mediaServerType, jellyfinHost: this.jellyfin.hostname, jellyfinExternalHost: this.jellyfin.externalHostname, + jellyfinForgotPasswordUrl: this.data.jellyfin.jellyfinForgotPasswordUrl, partialRequestsEnabled: this.data.main.partialRequestsEnabled, cacheImages: this.data.main.cacheImages, vapidPublic: this.vapidPublic, diff --git a/server/routes/auth.ts b/server/routes/auth.ts index 82c34b153..6aee1c19a 100644 --- a/server/routes/auth.ts +++ b/server/routes/auth.ts @@ -5,15 +5,29 @@ import { MediaServerType } from '@server/constants/server'; import { UserType } from '@server/constants/user'; import { getRepository } from '@server/datasource'; 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'; import logger from '@server/logger'; import { isAuthenticated } from '@server/middleware/auth'; import { ApiError } from '@server/types/error'; +import { + createIdTokenSchema, + fetchOIDCTokenData, + getOIDCRedirectUrl, + getOIDCUserInfo, + getOIDCWellknownConfiguration, + tryGetUserIdentifiers, + validateUserClaims, + type FullUserInfo, +} from '@server/utils/oidc'; +import { randomBytes } from 'crypto'; import * as EmailValidator from 'email-validator'; import { Router } from 'express'; import gravatarUrl from 'gravatar-url'; +import decodeJwt from 'jwt-decode'; +import { In } from 'typeorm'; const authRoutes = Router(); @@ -715,4 +729,269 @@ authRoutes.post('/reset-password/:guid', async (req, res, next) => { return res.status(200).json({ status: 'ok' }); }); +authRoutes.get('/oidc-login', async (req, res, next) => { + const settings = getSettings(); + + if (!settings.main.oidcLogin) { + return next({ + status: 403, + message: 'OpenID Connect sign-in is disabled.', + }); + } + + const state = randomBytes(32).toString('hex'); + let redirectUrl; + + try { + redirectUrl = await getOIDCRedirectUrl(req, state); + } catch (err) { + logger.info('Failed OIDC login attempt', { + cause: 'Failed to fetch OIDC 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.redirect(redirectUrl); +}); + +authRoutes.get('/oidc-callback', async (req, res, next) => { + const settings = getSettings(); + const { oidcLogin, oidc } = settings.main; + + if (!oidcLogin) { + return next({ + status: 403, + message: 'OpenID Connect sign-in is disabled.', + }); + } + + const identifierClaims = oidc.userIdentifier.split(' ').filter((s) => !!s); + const requiredClaims = oidc.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 OIDC 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 OIDC login attempt', { + cause: 'Invalid code', + ip: req.ip, + code: code, + }); + return next({ + status: 400, + message: 'Authorization failed.', + }); + } + + const wellKnownInfo = await getOIDCWellknownConfiguration(oidc.providerUrl); + + // Fetch the token data + const body = await fetchOIDCTokenData(req, 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 = decodeJwt(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 getOIDCUserInfo(wellKnownInfo, accessToken); + const fullUserInfo: FullUserInfo = { ...decoded, ...userInfo }; + + // Validate ID token jwt and user info + try { + const idTokenSchema = createIdTokenSchema({ + oidcClientId: oidc.clientId, + oidcDomain: oidc.providerUrl, + identifierClaims, + 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 user identifier + let identifiers: string[]; + try { + identifiers = tryGetUserIdentifiers(fullUserInfo, identifierClaims); + } catch { + logger.info('Failed OIDC login attempt', { + cause: 'User identifier not found in userinfo payload.', + user: fullUserInfo, + identifier: oidc.userIdentifier, + }); + return next({ + status: 500, + message: 'Configuration error.', + }); + } + + // Check that email is verified + try { + validateUserClaims(fullUserInfo, requiredClaims); + } catch (error) { + logger.info('Failed OIDC login attempt', { + cause: 'Failed to validate required claims', + error, + ip: req.ip, + identifiers, + requiredClaims: oidc.requiredClaims, + }); + return next({ + status: 403, + message: 'Insufficient permissions.', + }); + } + + // Map oidc identifier to user email + const userRepository = getRepository(User); + let user = await userRepository.findOne({ + where: { + email: In(identifiers), + }, + }); + + // Map user identification claim to media server username + if (!user && oidc.matchJellyfinUsername) { + user = await userRepository.findOne({ + where: [ + { plexUsername: In(identifiers) }, + { jellyfinUsername: In(identifiers) }, + ], + }); + } + + // Create user if one doesn't already exist + if (!user && fullUserInfo.email != null) { + 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); + } else if (!user) { + logger.debug('Failed OIDC sign-up attempt', { + cause: + 'User did not have an account, and was missing an associated email address.', + }); + return next({ + status: 400, + message: 'Unable to create new user account. Missing email address.', + }); + } + + // Set logged in session and return + if (req.session) { + req.session.userId = user.id; + } + + // Success! + return res.status(200).json({ status: 'ok' }); + } catch (error) { + logger.error('Failed OIDC login attempt', { + cause: 'Unknown error', + ip: req.ip, + errorMessage: error.message, + }); + return next({ + status: 500, + message: 'An unknown error occurred.', + }); + } +}); + +authRoutes.get('/oidc-logout', async (req, res, next) => { + const settings = getSettings(); + + if (!settings.main.oidcLogin || !settings.main.oidc.automaticLogin) { + return next({ + status: 403, + message: 'OpenID Connect sign-in is disabled.', + }); + } + + const oidcEndpoints = await getOIDCWellknownConfiguration( + settings.main.oidc.providerUrl + ); + + return res.redirect(oidcEndpoints.end_session_endpoint); +}); + export default authRoutes; diff --git a/server/utils/oidc.ts b/server/utils/oidc.ts new file mode 100644 index 000000000..a3940e0dd --- /dev/null +++ b/server/utils/oidc.ts @@ -0,0 +1,230 @@ +import type { + IdTokenClaims, + OidcProviderMetadata, + OidcStandardClaims, + OidcTokenResponse, +} from '@server/interfaces/api/oidcInterfaces'; +import { getSettings } from '@server/lib/settings'; +import axios from 'axios'; +import type { Request } from 'express'; +import * as yup from 'yup'; + +/** Fetch the oidc configuration blob */ +export async function getOIDCWellknownConfiguration(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 axios + .get(wellKnownUrl, { + headers: { + 'Content-Type': 'application/json', + }, + }) + .then((r) => r.data); + + return wellKnownInfo; +} + +/** Generate authentication request url */ +export async function getOIDCRedirectUrl(req: Request, state: string) { + const settings = getSettings(); + const { oidc } = settings.main; + + const wellKnownInfo = await getOIDCWellknownConfiguration(oidc.providerUrl); + const url = new URL(wellKnownInfo.authorization_endpoint); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('client_id', oidc.clientId); + + const callbackUrl = new URL( + '/login/oidc/callback', + `${req.protocol}://${req.headers.host}` + ).toString(); + url.searchParams.set('redirect_uri', callbackUrl); + url.searchParams.set('scope', 'openid profile email'); + url.searchParams.set('state', state); + return url.toString(); +} + +/** Exchange authorization code for token data */ +export async function fetchOIDCTokenData( + req: Request, + wellKnownInfo: OidcProviderMetadata, + code: string +): Promise { + const settings = getSettings(); + const { oidc } = settings.main; + + const callbackUrl = new URL( + '/login/oidc/callback', + `${req.protocol}://${req.headers.host}` + ); + + const formData = new URLSearchParams(); + formData.append('client_secret', oidc.clientSecret); + formData.append('grant_type', 'authorization_code'); + formData.append('redirect_uri', callbackUrl.toString()); + formData.append('client_id', oidc.clientId); + formData.append('code', code); + + return await axios + .post(wellKnownInfo.token_endpoint, formData) + .then((r) => r.data); +} + +export async function getOIDCUserInfo( + wellKnownInfo: OidcProviderMetadata, + authToken: string +) { + const userInfo = await axios + .get(wellKnownInfo.userinfo_endpoint, { + headers: { + Authorization: `Bearer ${authToken}`, + Accept: 'application/json', + }, + }) + .then((r) => r.data); + + return userInfo; +} + +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.`); + } +} + +export function tryGetUserIdentifiers( + userInfo: FullUserInfo, + identifierKeys: string[] +): string[] { + return identifierKeys.map((userIdentifier) => { + if ( + !Object.hasOwn(userInfo, userIdentifier) || + typeof userInfo[userIdentifier] !== 'string' + ) { + throw new OidcMissingKeyError(userInfo, userIdentifier); + } + + return userInfo[userIdentifier] as string; + }); +} + +type PrimitiveString = 'string' | 'boolean'; +type TypeFromName = T extends 'string' + ? string + : T extends 'boolean' + ? boolean + : unknown; + +export function tryGetUserInfoKey( + userInfo: FullUserInfo, + key: string, + expectedType: T +): TypeFromName { + if (!Object.hasOwn(userInfo, key) || typeof userInfo[key] !== expectedType) { + throw new OidcMissingKeyError(userInfo, key); + } + + return userInfo[key] as TypeFromName; +} + +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, + identifierClaims, + requiredClaims, +}: { + oidcDomain: string; + oidcClientId: string; + identifierClaims: 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; + } + ), + // ensure all identifier claims are present and are strings + ...identifierClaims.reduce( + (a, v) => ({ ...a, [v]: 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; diff --git a/src/components/Common/Modal/index.tsx b/src/components/Common/Modal/index.tsx index 464ba6341..233851986 100644 --- a/src/components/Common/Modal/index.tsx +++ b/src/components/Common/Modal/index.tsx @@ -11,6 +11,8 @@ import React, { Fragment, useRef } from 'react'; import ReactDOM from 'react-dom'; import { useIntl } from 'react-intl'; +type ButtonAction = 'button' | 'submit' | 'reset'; + interface ModalProps { title?: string; subTitle?: string; @@ -24,11 +26,15 @@ interface ModalProps { tertiaryText?: string; okDisabled?: boolean; cancelButtonType?: ButtonType; + cancelButtonAction?: ButtonAction; okButtonType?: ButtonType; + okButtonAction?: ButtonAction; secondaryButtonType?: ButtonType; + secondaryButtonAction?: ButtonAction; secondaryDisabled?: boolean; tertiaryDisabled?: boolean; tertiaryButtonType?: ButtonType; + tertiaryButtonAction?: ButtonAction; disableScrollLock?: boolean; backgroundClickable?: boolean; loading?: boolean; @@ -47,15 +53,19 @@ const Modal = React.forwardRef( okText, okDisabled = false, cancelButtonType = 'default', + cancelButtonAction = 'submit', okButtonType = 'primary', + okButtonAction = 'submit', children, disableScrollLock, backgroundClickable = true, secondaryButtonType = 'default', + secondaryButtonAction = 'submit', secondaryDisabled = false, onSecondary, secondaryText, tertiaryButtonType = 'default', + tertiaryButtonAction = 'submit', tertiaryDisabled = false, tertiaryText, loading = false, @@ -180,6 +190,7 @@ const Modal = React.forwardRef( {typeof onOk === 'function' && ( + + ); +}; + +export default OidcLogin; diff --git a/src/components/Login/PlexLogin.tsx b/src/components/Login/PlexLogin.tsx new file mode 100644 index 000000000..59bdae182 --- /dev/null +++ b/src/components/Login/PlexLogin.tsx @@ -0,0 +1,91 @@ +import globalMessages from '@app/i18n/globalMessages'; +import PlexOAuth from '@app/utils/plex'; +import { ArrowLeftOnRectangleIcon } from '@heroicons/react/24/outline'; +import axios from 'axios'; +import type React from 'react'; +import { useEffect, useState } from 'react'; +import { defineMessages, useIntl } from 'react-intl'; + +const messages = defineMessages({ + signinwithplex: 'Sign in with Plex', + signingin: 'Signing in…', +}); + +const plexOAuth = new PlexOAuth(); + +interface PlexLoginProps { + onAuthenticated: () => void; + isProcessing?: boolean; + setProcessing?: (state: boolean) => void; + onError?: (message: string) => void; +} + +const PlexLogin: React.FC = ({ + onAuthenticated, + onError, + isProcessing, + setProcessing, +}) => { + const intl = useIntl(); + const [loading, setLoading] = useState(false); + const [authToken, setAuthToken] = useState(undefined); + + // Effect that is triggered when the `authToken` comes back from the Plex OAuth + // We take the token and attempt to sign in. If we get a success message, we will + // ask swr to revalidate the user which _should_ come back with a valid user. + useEffect(() => { + const login = async () => { + if (setProcessing) setProcessing(true); + try { + const response = await axios.post('/api/v1/auth/plex', { authToken }); + + if (response.data?.id) { + onAuthenticated(); + } + } catch (e) { + if (onError) onError(e.response.data.message); + setAuthToken(undefined); + if (setProcessing) setProcessing(false); + } + }; + if (authToken) { + login(); + } + }, [authToken, onAuthenticated, onError, setProcessing]); + + const getPlexLogin = async () => { + setLoading(true); + try { + const authToken = await plexOAuth.login(); + setLoading(false); + setAuthToken(authToken); + } catch (e) { + if (onError) onError(e.message); + setLoading(false); + } + }; + return ( + + + + ); +}; + +export default PlexLogin; diff --git a/src/components/Login/index.tsx b/src/components/Login/index.tsx index da4344efe..882b8ac60 100644 --- a/src/components/Login/index.tsx +++ b/src/components/Login/index.tsx @@ -1,63 +1,41 @@ import Accordion from '@app/components/Common/Accordion'; import ImageFader from '@app/components/Common/ImageFader'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import PageTitle from '@app/components/Common/PageTitle'; import LanguagePicker from '@app/components/Layout/LanguagePicker'; -import LocalLogin from '@app/components/Login/LocalLogin'; -import PlexLoginButton from '@app/components/PlexLoginButton'; +import ErrorCallout from '@app/components/Login/ErrorCallout'; import useSettings from '@app/hooks/useSettings'; import { useUser } from '@app/hooks/useUser'; -import { Transition } from '@headlessui/react'; -import { XCircleIcon } from '@heroicons/react/24/solid'; import { MediaServerType } from '@server/constants/server'; -import axios from 'axios'; import getConfig from 'next/config'; import { useRouter } from 'next/dist/client/router'; import { useEffect, useState } from 'react'; import { defineMessages, useIntl } from 'react-intl'; import useSWR from 'swr'; import JellyfinLogin from './JellyfinLogin'; +import LocalLogin from './LocalLogin'; +import OidcLogin from './OidcLogin'; +import PlexLogin from './PlexLogin'; const messages = defineMessages({ signin: 'Sign In', signinheader: 'Sign in to continue', - signinwithplex: 'Use your Plex account', - signinwithjellyfin: 'Use your {mediaServerName} account', - signinwithoverseerr: 'Use your {applicationTitle} account', + useplexaccount: 'Use your Plex account', + usejellyfinaccount: 'Use your {mediaServerName} account', + useoverseeerraccount: 'Use your {applicationTitle} account', + useoidcaccount: 'Use your {OIDCProvider} account', + authprocessing: 'Authentication in progress...', }); const Login = () => { const intl = useIntl(); const [error, setError] = useState(''); const [isProcessing, setProcessing] = useState(false); - const [authToken, setAuthToken] = useState(undefined); const { user, revalidate } = useUser(); const router = useRouter(); const settings = useSettings(); const { publicRuntimeConfig } = getConfig(); - // Effect that is triggered when the `authToken` comes back from the Plex OAuth - // We take the token and attempt to sign in. If we get a success message, we will - // ask swr to revalidate the user which _should_ come back with a valid user. - useEffect(() => { - const login = async () => { - setProcessing(true); - try { - const response = await axios.post('/api/v1/auth/plex', { authToken }); - - if (response.data?.id) { - revalidate(); - } - } catch (e) { - setError(e.response.data.message); - setAuthToken(undefined); - setProcessing(false); - } - }; - if (authToken) { - login(); - } - }, [authToken, revalidate]); - // Effect that is triggered whenever `useUser`'s user changes. If we get a new // valid user, we redirect the user to the home page as the login was successful. useEffect(() => { @@ -72,6 +50,57 @@ const Login = () => { revalidateOnFocus: false, }); + const loginSections = [ + { + // Media Server Login + title: + settings.currentSettings.mediaServerType == MediaServerType.PLEX + ? intl.formatMessage(messages.useplexaccount) + : intl.formatMessage(messages.usejellyfinaccount, { + mediaServerName: + publicRuntimeConfig.JELLYFIN_TYPE == 'emby' + ? 'Emby' + : 'Jellyfin', + }), + enabled: settings.currentSettings.mediaServerLogin, + content: + settings.currentSettings.mediaServerType == MediaServerType.PLEX ? ( + setError(err)} + /> + ) : ( + + ), + }, + { + // Local Login + title: intl.formatMessage(messages.useoverseeerraccount, { + applicationTitle: settings.currentSettings.applicationTitle, + }), + enabled: settings.currentSettings.localLogin, + content: , + }, + { + // OIDC Login + title: intl.formatMessage(messages.useoidcaccount, { + OIDCProvider: settings.currentSettings.oidcProviderName, + }), + enabled: settings.currentSettings.oidcLogin, + content: ( + + ), + }, + ]; + return (
@@ -93,94 +122,43 @@ const Login = () => {
<> - -
-
-
- -
-
-

- {error} -

-
-
+ + {isProcessing ? ( +
+

+ {intl.formatMessage(messages.authprocessing)} +

+
- - - {({ openIndexes, handleClick, AccordionContent }) => ( - <> - - -
- {settings.currentSettings.mediaServerType == - MediaServerType.PLEX ? ( - setAuthToken(authToken)} - /> - ) : ( - - )} -
-
- {settings.currentSettings.localLogin && ( -
- - -
- + ) : ( + + {({ openIndexes, handleClick, AccordionContent }) => ( + <> + {loginSections + .filter((section) => section.enabled) + .map((section, i) => ( +
+ + +
{section.content}
+
- -
- )} - - )} - + ))} + + )} + + )}
diff --git a/src/components/PlexLoginButton/index.tsx b/src/components/PlexLoginButton/index.tsx deleted file mode 100644 index 363231733..000000000 --- a/src/components/PlexLoginButton/index.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import globalMessages from '@app/i18n/globalMessages'; -import PlexOAuth from '@app/utils/plex'; -import { ArrowLeftOnRectangleIcon } from '@heroicons/react/24/outline'; -import { useState } from 'react'; -import { defineMessages, useIntl } from 'react-intl'; - -const messages = defineMessages({ - signinwithplex: 'Sign In', - signingin: 'Signing In…', -}); - -const plexOAuth = new PlexOAuth(); - -interface PlexLoginButtonProps { - onAuthToken: (authToken: string) => void; - isProcessing?: boolean; - onError?: (message: string) => void; -} - -const PlexLoginButton = ({ - onAuthToken, - onError, - isProcessing, -}: PlexLoginButtonProps) => { - const intl = useIntl(); - const [loading, setLoading] = useState(false); - - const getPlexLogin = async () => { - setLoading(true); - try { - const authToken = await plexOAuth.login(); - setLoading(false); - onAuthToken(authToken); - } catch (e) { - if (onError) { - onError(e.message); - } - setLoading(false); - } - }; - return ( - - - - ); -}; - -export default PlexLoginButton; diff --git a/src/components/Settings/OidcModal/index.tsx b/src/components/Settings/OidcModal/index.tsx new file mode 100644 index 000000000..c135c8c5b --- /dev/null +++ b/src/components/Settings/OidcModal/index.tsx @@ -0,0 +1,370 @@ +import Accordion from '@app/components/Common/Accordion'; +import Modal from '@app/components/Common/Modal'; +import globalMessages from '@app/i18n/globalMessages'; +import { Transition } from '@headlessui/react'; +import { ChevronDownIcon } from '@heroicons/react/24/solid'; +import type { MainSettings } from '@server/lib/settings'; +import { + ErrorMessage, + Field, + type FormikErrors, + type FormikHelpers, +} from 'formik'; +import { + defineMessages, + useIntl, + type IntlShape, + type MessageDescriptor, +} from 'react-intl'; +import * as yup from 'yup'; + +const messages = defineMessages({ + configureoidc: 'Configure OpenID Connect', + oidcDomain: 'Issuer URL', + oidcDomainTip: "The base URL of the identity provider's OIDC endpoint", + oidcName: 'Provider Name', + oidcNameTip: 'Name of the OIDC Provider which appears on the login screen', + oidcClientId: 'Client ID', + oidcClientIdTip: 'The OIDC Client ID assigned to Jellyseerr', + oidcClientSecret: 'Client Secret', + oidcClientSecretTip: 'The OIDC Client Secret assigned to Jellyseerr', + oidcScopes: 'Scopes', + oidcScopesTip: 'The scopes to request from the identity provider.', + oidcIdentificationClaims: 'Identification Claims', + oidcIdentificationClaimsTip: + 'OIDC claims to use as unique identifiers for the given user. Will be matched ' + + "against the user's email and, optionally, their media server username.", + oidcRequiredClaims: 'Required Claims', + oidcRequiredClaimsTip: 'Claims that are required for a user to log in.', + 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.', +}); + +type OidcSettings = MainSettings['oidc']; + +interface OidcModalProps { + values: Partial; + errors?: FormikErrors; + setFieldValue: FormikHelpers['setFieldValue']; + mediaServerName: string; + onClose?: () => void; + onOk?: () => void; +} + +export const oidcSettingsSchema = (intl: IntlShape) => { + const requiredMessage = (message: MessageDescriptor) => + intl.formatMessage(globalMessages.fieldRequired, { + fieldName: intl.formatMessage(message), + }); + + return yup.object().shape({ + providerName: yup.string().required(requiredMessage(messages.oidcName)), + providerUrl: yup + .string() + .required(requiredMessage(messages.oidcDomain)) + .url('Issuer URL must be a valid URL.') + .test({ + message: 'Issuer URL may not have search parameters.', + test: (val) => { + if (!val) return false; + try { + const url = new URL(val); + return url.search === ''; + } catch { + return false; + } + }, + }) + .test({ + message: 'Issuer URL protocol must be http / https.', + test: (val) => { + if (!val) return false; + try { + const url = new URL(val); + return ['http:', 'https:'].includes(url.protocol); + } catch { + return false; + } + }, + }), + clientId: yup.string().required(requiredMessage(messages.oidcClientId)), + clientSecret: yup + .string() + .required(requiredMessage(messages.oidcClientSecret)), + scopes: yup.string().required(requiredMessage(messages.oidcScopes)), + userIdentifier: yup + .string() + .required(requiredMessage(messages.oidcIdentificationClaims)), + requiredClaims: yup.string(), + matchJellyfinUsername: yup.boolean(), + automaticLogin: yup.boolean(), + }); +}; + +const OidcModal = ({ + onClose, + onOk, + values, + errors, + setFieldValue, + mediaServerName, +}: OidcModalProps) => { + const intl = useIntl(); + + const canClose = (errors: OidcModalProps['errors']) => { + if (errors == null) return true; + return Object.keys(errors).length === 0; + }; + + return ( + + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ + {({ openIndexes, handleClick, AccordionContent }) => ( + <> + + +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ { + setFieldValue( + 'oidc.matchJellyfinUsername', + !values.matchJellyfinUsername + ); + }} + /> +
+
+
+ +
+ { + setFieldValue( + 'oidc.automaticLogin', + !values.automaticLogin + ); + }} + /> +
+
+
+
+ + )} +
+
+
+
+ ); +}; + +export default OidcModal; diff --git a/src/components/Settings/SettingsUsers/index.tsx b/src/components/Settings/SettingsUsers/index.tsx index ff6126c5e..bb96ff28c 100644 --- a/src/components/Settings/SettingsUsers/index.tsx +++ b/src/components/Settings/SettingsUsers/index.tsx @@ -1,19 +1,27 @@ import Button from '@app/components/Common/Button'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import PageTitle from '@app/components/Common/PageTitle'; +import FormErrorNotification from '@app/components/FormErrorNotification'; +import LabeledCheckbox from '@app/components/LabeledCheckbox'; import PermissionEdit from '@app/components/PermissionEdit'; import QuotaSelector from '@app/components/QuotaSelector'; +import OidcModal, { + oidcSettingsSchema, +} from '@app/components/Settings/OidcModal'; import useSettings from '@app/hooks/useSettings'; import globalMessages from '@app/i18n/globalMessages'; import { ArrowDownOnSquareIcon } from '@heroicons/react/24/outline'; +import { CogIcon } from '@heroicons/react/24/solid'; import { MediaServerType } from '@server/constants/server'; import type { MainSettings } from '@server/lib/settings'; import axios from 'axios'; import { Field, Form, Formik } from 'formik'; import getConfig from 'next/config'; -import { defineMessages, useIntl } from 'react-intl'; +import { useState } from 'react'; +import { defineMessages, useIntl, type IntlShape } from 'react-intl'; import { useToasts } from 'react-toast-notifications'; import useSWR, { mutate } from 'swr'; +import * as yup from 'yup'; const messages = defineMessages({ users: 'Users', @@ -21,18 +29,69 @@ const messages = defineMessages({ userSettingsDescription: 'Configure global and default user settings.', toastSettingsSuccess: 'User settings saved successfully!', toastSettingsFailure: 'Something went wrong while saving settings.', + loginMethods: 'Login Methods', + loginMethodsTip: 'Configure login methods for users.', localLogin: 'Enable Local Sign-In', localLoginTip: 'Allow users to sign in using their email address and password, instead of {mediaServerName} OAuth', newPlexLogin: 'Enable New {mediaServerName} Sign-In', newPlexLoginTip: 'Allow {mediaServerName} users to sign in without first being imported', + mediaServerLogin: 'Enable {mediaServerName} Sign-In', + mediaServerLoginTip: + 'Allow users to sign in using their {mediaServerName} account', + oidcLogin: 'Enable OIDC Sign-In', + oidcLoginTip: 'Allow users to sign in using an OIDC identity provider', movieRequestLimitLabel: 'Global Movie Request Limit', tvRequestLimitLabel: 'Global Series Request Limit', defaultPermissions: 'Default Permissions', defaultPermissionsTip: 'Initial permissions assigned to new users', }); +const createValidationSchema = (intl: IntlShape) => { + return yup + .object() + .shape({ + localLogin: yup.boolean(), + mediaServerLogin: yup.boolean(), + oidcLogin: yup.boolean(), + oidc: yup.object().when('oidcLogin', { + is: true, + then: oidcSettingsSchema(intl), + }), + }) + .test({ + name: 'atLeastOneAuth', + test: function (values) { + const isValid = ['localLogin', 'mediaServerLogin', 'oidcLogin'].some( + (field) => !!values[field] + ); + + if (isValid) return true; + return this.createError({ + path: 'localLogin | mediaServerLogin | oidcLogin', + message: 'At least one authentication method must be selected.', + }); + }, + }) + .test({ + name: 'automaticLoginExclusive', + test: function (values) { + const isValid = + !values.oidcLogin || + !values.oidc.automaticLogin || + !['localLogin', 'mediaServerLogin'].some((field) => !!values[field]); + + if (isValid) return true; + return this.createError({ + path: 'localLogin | mediaServerLogin | oidcLogin', + message: + 'Only OIDC login may be enabled when automatic login is enabled.', + }); + }, + }); +}; + const SettingsUsers = () => { const { addToast } = useToasts(); const intl = useIntl(); @@ -43,11 +102,20 @@ const SettingsUsers = () => { } = useSWR('/api/v1/settings/main'); const settings = useSettings(); const { publicRuntimeConfig } = getConfig(); + // [showDialog, isFirstOpen] + const [showOidcDialog, setShowOidcDialog] = useState(false); if (!data && !error) { return ; } + const mediaServerName = + publicRuntimeConfig.JELLYFIN_TYPE == 'emby' + ? 'Emby' + : settings.currentSettings.mediaServerType === MediaServerType.PLEX + ? 'Plex' + : 'Jellyfin'; + return ( <> { initialValues={{ localLogin: data?.localLogin, newPlexLogin: data?.newPlexLogin, + mediaServerLogin: data?.mediaServerLogin, + oidcLogin: data?.oidcLogin, + oidc: data?.oidc ?? {}, movieQuotaLimit: data?.defaultQuotas.movie.quotaLimit ?? 0, movieQuotaDays: data?.defaultQuotas.movie.quotaDays ?? 7, tvQuotaLimit: data?.defaultQuotas.tv.quotaLimit ?? 0, tvQuotaDays: data?.defaultQuotas.tv.quotaDays ?? 7, defaultPermissions: data?.defaultPermissions ?? 0, }} + validationSchema={() => createValidationSchema(intl)} enableReinitialize onSubmit={async (values) => { try { await axios.post('/api/v1/settings/main', { localLogin: values.localLogin, newPlexLogin: values.newPlexLogin, + mediaServerLogin: values.mediaServerLogin, + oidcLogin: values.oidcLogin, + oidc: values.oidc, defaultQuotas: { movie: { quotaLimit: values.movieQuotaLimit, @@ -107,56 +182,105 @@ const SettingsUsers = () => { } }} > - {({ isSubmitting, values, setFieldValue }) => { + {({ isSubmitting, values, setFieldValue, isValid, errors }) => { return ( -
-