📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
OpenID Connect support for Swetrix Community Edition
Blue Mouse6009184c7dc4
diff --git a/backend/Dockerfile b/backend/Dockerfileindex 0be91a2d2..592fc509f 100644--- a/backend/Dockerfile+++ b/backend/Dockerfile@@ -25,11 +25,25 @@ ENV REDIS_HOST=localhost \CLICKHOUSE_PORT=8123 \CLICKHOUSE_DATABASE=analytics+# Authentication mode settings+ENV OIDC_ENABLED=false \+ OIDC_ONLY_AUTH=false+# Application configsENV [email protected] \PASSWORD=12345678 \IS_PRIMARY_NODE=true+# OIDC Configuration (optional)+ENV OIDC_ISSUER='' \+ OIDC_CLIENT_ID='' \+ OIDC_CLIENT_SECRET='' \+ OIDC_CALLBACK_URL='' \+ OIDC_AUTH_URL='' \+ OIDC_TOKEN_URL='' \+ OIDC_USERINFO_URL='' \+ OIDC_SCOPE='openid email profile'+# Install and configure timezoneRUN apk add --no-cache tzdata && \cp /usr/share/zoneinfo/$TZ /etc/localtime && \diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.tsindex 3de52a9de..a700a6fdf 100644--- a/backend/apps/community/src/auth/auth.controller.ts+++ b/backend/apps/community/src/auth/auth.controller.ts@@ -12,16 +12,26 @@ import {HttpStatus,UnauthorizedException,Headers,+ Res,+ BadRequestException,} from '@nestjs/common'import { ApiTags, ApiOperation, ApiOkResponse } from '@nestjs/swagger'import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'+import { Response } from 'express'import { checkRateLimit, getIPFromHeaders } from '../common/utils'import { generateSelfhostedUser } from '../user/entities/user.entity'import { AuthService } from './auth.service'import { Public, CurrentUserId, CurrentUser } from './decorators'-import { LoginResponseDto, LoginRequestDto } from './dtos'+import {+ LoginResponseDto,+ LoginRequestDto,+ OIDCInitiateDto,+ OIDCProcessTokenDto,+ OIDCGetJWTByHashDto,+} from './dtos'import { JwtAccessTokenGuard, JwtRefreshTokenGuard } from './guards'+import { OIDC_ENABLED, OIDC_ONLY_AUTH } from '../common/constants'@ApiTags('Auth')@Controller({ path: 'auth', version: '1' })@@ -52,6 +62,11 @@ export class AuthController {@Headers() headers: unknown,@Ip() reqIP: string,): Promise<LoginResponseDto> {+ // If OIDC-only mode is enabled, disable traditional login+ if (OIDC_ONLY_AUTH) {+ throw new ConflictException(i18n.t('auth.oidcOnlyMode'))+ }+const ip = getIPFromHeaders(headers) || reqIP || ''await checkRateLimit(ip, 'login', 10, 1800)@@ -136,4 +151,69 @@ export class AuthController {await this.authService.logout(user.id, refreshToken)}++ @ApiOperation({ summary: 'Initiate OIDC authentication' })+ @ApiOkResponse({+ description: 'OIDC authentication initiated',+ })+ @Public()+ @Post('oidc/initiate')+ @HttpCode(HttpStatus.OK)+ async initiateOidc(+ @Body() body: OIDCInitiateDto,+ @Headers() headers: unknown,+ @Ip() reqIP: string,+ ) {+ if (!OIDC_ENABLED) {+ throw new BadRequestException('OIDC authentication is not enabled')+ }++ const ip = getIPFromHeaders(headers) || reqIP || ''+ await checkRateLimit(ip, 'oidc-initiate', 15, 1800)++ return this.authService.generateOidcAuthUrl(body.redirectUrl)+ }++ @ApiOperation({ summary: 'OIDC callback handler' })+ @ApiOkResponse({+ description: 'OIDC authentication completed',+ })+ @Public()+ @Post('oidc/process-token')+ @HttpCode(HttpStatus.CREATED)+ async oidcProcessToken(+ @Body() body: OIDCProcessTokenDto,+ @Headers() headers: unknown,+ @Ip() reqIP: string,+ @Res() res: Response,+ ) {+ if (!OIDC_ENABLED) {+ return res+ .status(HttpStatus.CONFLICT)+ .json({ error: 'OIDC authentication is not enabled' })+ }++ const ip = getIPFromHeaders(headers) || reqIP || ''+ await checkRateLimit(ip, 'oidc-process-token', 15, 1800)++ const { code, hash } = body++ try {+ await this.authService.processOidcToken(code, hash)+ } catch (reason) {+ console.error('[ERROR] OIDC Callback Error:', reason)+ return res+ .status(HttpStatus.BAD_REQUEST)+ .json({ error: 'Authentication failed' })+ }+ }++ @ApiOperation({ summary: 'Get JWT access tokens by OIDC initiated hash' })+ @Post('oidc/hash')+ @Public()+ async getJWTByHash(@Body() body: OIDCGetJWTByHashDto): Promise<any> {+ const { hash } = body++ return this.authService.authenticateOidc(hash)+ }}diff --git a/backend/apps/community/src/auth/auth.service.ts b/backend/apps/community/src/auth/auth.service.tsindex b0842aa7e..2718768f4 100644--- a/backend/apps/community/src/auth/auth.service.ts+++ b/backend/apps/community/src/auth/auth.service.ts@@ -1,8 +1,14 @@-import { Injectable } from '@nestjs/common'+import {+ BadRequestException,+ ConflictException,+ Injectable,+ InternalServerErrorException,+} from '@nestjs/common'import { ConfigService } from '@nestjs/config'import { JwtService } from '@nestjs/jwt'import { genSalt, hash } from 'bcrypt'import _isEmpty from 'lodash/isEmpty'+import { v4 as uuidv4 } from 'uuid'import {saveRefreshTokenClickhouse,@@ -16,9 +22,16 @@ import {JWT_ACCESS_TOKEN_LIFETIME,JWT_REFRESH_TOKEN_LIFETIME,SELFHOSTED_API_KEY,+ SELFHOSTED_UUID,+ REDIS_OIDC_SESSION_KEY,+ redis,} from '../common/constants'import { getSelfhostedUser, SelfhostedUser } from '../user/entities/user.entity'+const REDIS_OIDC_SESSION_TIMEOUT = 60 * 5 // 5 minutes+const getOIDCRedisKey = (uuid: string) => `${REDIS_OIDC_SESSION_KEY}:${uuid}`+const generateOIDCState = () => `openid-connect:${uuidv4()}`+@Injectable()export class AuthService {constructor(@@ -116,4 +129,138 @@ export class AuthService {isApiKeyValid(apiKey: string): boolean {return apiKey === SELFHOSTED_API_KEY}++ getOidcConfig() {+ return {+ issuer: this.configService.get('OIDC_ISSUER'),+ authorizationURL: this.configService.get('OIDC_AUTH_URL'),+ tokenURL: this.configService.get('OIDC_TOKEN_URL'),+ userInfoURL: this.configService.get('OIDC_USERINFO_URL'),+ clientID: this.configService.get('OIDC_CLIENT_ID'),+ clientSecret: this.configService.get('OIDC_CLIENT_SECRET'),+ callbackURL: this.configService.get('OIDC_CALLBACK_URL'),+ scope: this.configService.get('OIDC_SCOPE') || 'openid email profile',+ }+ }++ async generateOidcAuthUrl(redirectUrl?: string) {+ const uuid = generateOIDCState()++ await redis.set(getOIDCRedisKey(uuid), '', 'EX', REDIS_OIDC_SESSION_TIMEOUT)++ const config = this.getOidcConfig()+ const auth_url = `${config.authorizationURL}?client_id=${config.clientID}&response_type=code&scope=${encodeURIComponent(config.scope)}&redirect_uri=${encodeURIComponent(config.callbackURL)}&state=${uuid}`++ return {+ auth_url,+ uuid,+ expires_in: REDIS_OIDC_SESSION_TIMEOUT * 1000, // milliseconds+ }+ }++ async processOidcToken(code: string, state: string) {+ const config = this.getOidcConfig()++ console.log('processing oidc token')+ console.log('code:', code)+ console.log('state:', state)++ const tokenResponse = await fetch(config.tokenURL, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Accept: 'application/json',+ },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ client_id: config.clientID,+ client_secret: config.clientSecret,+ code,+ redirect_uri: config.callbackURL,+ }).toString(),+ })++ const tokenData = await tokenResponse.json()++ console.log('tokenData:', tokenData)++ const userInfoResponse = await fetch(config.userInfoURL, {+ headers: {+ Authorization: `Bearer ${tokenData.access_token}`,+ },+ })++ const userInfo = await userInfoResponse.json()++ console.log('userInfo:', userInfo)++ const dataToStore = JSON.stringify({ id: SELFHOSTED_UUID })++ await redis.set(+ getOIDCRedisKey(state),+ dataToStore,+ 'EX',+ REDIS_OIDC_SESSION_TIMEOUT,+ )+ }++ async processHash(state: string) {+ if (!state) {+ throw new BadRequestException('Missing state parameter')+ }++ const oidcRedisKey = getOIDCRedisKey(state)+ const exists = await redis.exists(oidcRedisKey)++ if (!exists) {+ throw new BadRequestException(+ 'No authentication session opened for the provided state',+ )+ }++ const data = await redis.get(oidcRedisKey)++ if (!data) {+ throw new ConflictException(+ 'Authentication session is opened but no data found',+ )+ }++ let payload++ try {+ payload = JSON.parse(data)+ } catch (reason) {+ console.error(+ `[ERROR][AuthService -> authenticateGoogle -> JSON.parse]: ${reason} - ${data}`,+ )+ throw new InternalServerErrorException(+ 'Session related data is corrupted',+ )+ }++ await redis.del(oidcRedisKey)++ return payload+ }++ async authenticateOidc(state: string) {+ const { id } = await this.processHash(state)++ try {+ if (id !== SELFHOSTED_UUID) {+ throw new BadRequestException('Invalid user ID')+ }++ const tokens = await this.generateJwtTokens(id, true)++ return {+ ...tokens,+ user: getSelfhostedUser(),+ }+ } catch (error) {+ console.error(`[ERROR][AuthService -> authenticateOidc]: ${error}`)+ throw new InternalServerErrorException(error)+ }+ }}diff --git a/backend/apps/community/src/auth/dtos/index.ts b/backend/apps/community/src/auth/dtos/index.tsindex 84f02512a..e0e1003d5 100644--- a/backend/apps/community/src/auth/dtos/index.ts+++ b/backend/apps/community/src/auth/dtos/index.ts@@ -1 +1,2 @@export * from './login.dto'+export * from './oidc-auth.dto'diff --git a/backend/apps/community/src/auth/dtos/oidc-auth.dto.ts b/backend/apps/community/src/auth/dtos/oidc-auth.dto.tsnew file mode 100644index 000000000..4daf8ff12--- /dev/null+++ b/backend/apps/community/src/auth/dtos/oidc-auth.dto.ts@@ -0,0 +1,42 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsString, IsOptional, IsUrl } from 'class-validator'++export class OIDCInitiateDto {+ @ApiProperty({+ description: 'Redirect URL after successful authentication',+ required: false,+ })+ @IsUrl()+ @IsOptional()+ redirectUrl?: string++ @ApiProperty({+ description:+ "Provider name (not used, but it's here for compatibility with the Cloud Version. On Community Edition it's always set to openid-connect)",+ required: false,+ })+ @IsString()+ @IsOptional()+ provider?: string+}++export class OIDCProcessTokenDto {+ @ApiProperty({ description: 'Code from the OIDC callback' })+ @IsString()+ code: string++ @ApiProperty({+ description: 'State from the OIDC callback (to get JWT tokens)',+ })+ @IsString()+ hash: string+}++export class OIDCGetJWTByHashDto {+ @ApiProperty({+ description: 'OIDC session identifier',+ example: '123e4567-e89b-12d3-a456-426614174000',+ })+ @IsString()+ hash: string+}diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.tsindex 6f3a57c8a..951ede643 100644--- a/backend/apps/community/src/common/constants.ts+++ b/backend/apps/community/src/common/constants.ts@@ -37,6 +37,10 @@ const SELFHOSTED_GEOIP_DB_PATH = process.env.IP_GEOLOCATION_DB_PATHconst UUIDV5_NAMESPACE = '912c64c1-73fd-42b6-859f-785f839a9f68'const DEFAULT_SELFHOSTED_UUID = 'deadbeef-dead-beef-dead-beefdeadbeef'+// OIDC configuration+const OIDC_ENABLED = process.env.OIDC_ENABLED === 'true'+const OIDC_ONLY_AUTH = process.env.OIDC_ONLY_AUTH === 'true'+const SELFHOSTED_UUID = getSelfhostedUUID()const ORIGINS_REGEX =@@ -52,6 +56,7 @@ const getRedisProjectKey = (pid: string) => `pid_${pid}`const REDIS_SESSION_SALT_KEY = 'log_salt' // is updated every 24 hoursconst REDIS_USERS_COUNT_KEY = 'stats:users_count'const REDIS_PROJECTS_COUNT_KEY = 'stats:projects_count'+const REDIS_OIDC_SESSION_KEY = 'oidc:session'// 3600 sec -> 1 hourconst redisProjectCacheTimeout = 3600@@ -138,4 +143,7 @@ export {PID_REGEX,ALL_COLUMNS,SELFHOSTED_GEOIP_DB_PATH,+ OIDC_ENABLED,+ OIDC_ONLY_AUTH,+ REDIS_OIDC_SESSION_KEY,}diff --git a/backend/apps/community/src/i18n/en/auth.json b/backend/apps/community/src/i18n/en/auth.jsonindex 5f090f3b4..a90d2c2a9 100644--- a/backend/apps/community/src/i18n/en/auth.json+++ b/backend/apps/community/src/i18n/en/auth.json@@ -9,5 +9,6 @@"maxEmailRequestsReached": "Maximum number of email requests reached.","emailAlreadyTaken": "Email already taken.","invalidChangeEmailToken": "Invalid change email token.",- "invalidRefreshToken": "Invalid refresh token."+ "invalidRefreshToken": "Invalid refresh token.",+ "oidcOnlyMode": "OIDC-only mode is enabled. Please use OIDC to login."}diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 2856d21a5..f986eff9c 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -59,6 +59,7 @@"passport": "^0.7.0","passport-headerapikey": "^1.2.2","passport-jwt": "^4.0.1",+ "passport-openidconnect": "^0.1.2","php-serialize": "^5.1.3","puppeteer": "^24.6.1","randomstring": "^1.3.1",@@ -10002,6 +10003,12 @@"url": "https://github.com/fb55/nth-check?sponsor=1"}},+ "node_modules/oauth": {+ "version": "0.10.2",+ "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.10.2.tgz",+ "integrity": "sha512-JtFnB+8nxDEXgNyniwz573xxbKSOu3R8D40xQKqcjwJ2CDkYqUDI53o6IuzDJBx60Z8VKCm271+t8iFjakrl8Q==",+ "license": "MIT"+ },"node_modules/object-assign": {"version": "4.1.1","resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",@@ -10443,6 +10450,23 @@"passport-strategy": "^1.0.0"}},+ "node_modules/passport-openidconnect": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/passport-openidconnect/-/passport-openidconnect-0.1.2.tgz",+ "integrity": "sha512-JX3rTyW+KFZ/E9OF/IpXJPbyLO9vGzcmXB5FgSP2jfL3LGKJPdV7zUE8rWeKeeI/iueQggOeFa3onrCmhxXZTg==",+ "license": "MIT",+ "dependencies": {+ "oauth": "0.10.x",+ "passport-strategy": "1.x.x"+ },+ "engines": {+ "node": ">= 0.6.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/jaredhanson"+ }+ },"node_modules/passport-strategy": {"version": "1.0.0","resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz",diff --git a/backend/package.json b/backend/package.jsonindex 434f52086..a6c7eca67 100644--- a/backend/package.json+++ b/backend/package.json@@ -78,6 +78,7 @@"passport": "^0.7.0","passport-headerapikey": "^1.2.2","passport-jwt": "^4.0.1",+ "passport-openidconnect": "^0.1.2","php-serialize": "^5.1.3","puppeteer": "^24.6.1","randomstring": "^1.3.1",diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 878dd9498..e0a25e86d 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -6,7 +6,7 @@ import _map from 'lodash/map'import { DEFAULT_ALERTS_TAKE, API_URL } from '~/lib/constants'import { Alerts } from '~/lib/models/Alerts'-import { Auth } from '~/lib/models/Auth'+import { Auth, SSOProvider } from '~/lib/models/Auth'import { Metainfo } from '~/lib/models/Metainfo'import { Role } from '~/lib/models/Organisation'import { Project, Overall, LiveStats, Funnel, Extension } from '~/lib/models/Project'@@ -1227,11 +1227,21 @@ export const confirmTransferProject = (uuid: string) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const generateSSOAuthURL = (provider: string) =>- api- .post('v1/auth/sso/generate', {- provider,- })+export const generateSSOAuthURL = async (provider: SSOProvider, redirectUrl?: string) => {+ const payload = {+ provider,+ redirectUrl,+ }++ let authInitiateRequest++ if (provider === 'openid-connect') {+ authInitiateRequest = api.post('v1/auth/oidc/initiate', payload)+ } else {+ authInitiateRequest = api.post('v1/auth/sso/generate', payload)+ }++ return authInitiateRequest.then((response,@@ -1244,10 +1254,18 @@ export const generateSSOAuthURL = (provider: string) =>.catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+}-export const getJWTBySSOHash = (hash: string, provider: string, refCode?: string) =>- api- .post('v1/auth/sso/hash', { hash, provider, refCode })+export const getJWTBySSOHash = async (hash: string, provider: SSOProvider, refCode?: string) => {+ let axiosPost++ if (provider === 'openid-connect') {+ axiosPost = api.post('v1/auth/oidc/hash', { hash })+ } else {+ axiosPost = api.post('v1/auth/sso/hash', { hash, provider, refCode })+ }++ return axiosPost.then((response,@@ -1261,6 +1279,15 @@ export const getJWTBySSOHash = (hash: string, provider: string, refCode?: string.catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+}++export const processSSOTokenCommunityEdition = (code: string, hash: string) =>+ api+ .post('v1/auth/oidc/process-token', { code, hash })+ .then((response): unknown => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })export const linkBySSOHash = (hash: string, provider: string) =>apidiff --git a/web/app/components/OIDCAuth.tsx b/web/app/components/OIDCAuth.tsxnew file mode 100644index 000000000..5f962d551--- /dev/null+++ b/web/app/components/OIDCAuth.tsx@@ -0,0 +1,33 @@+import cx from 'clsx'+import { KeyRoundIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'++import Button from '~/ui/Button'++interface OIDCAuthProps {+ onClick: () => void+ className?: string+ disabled?: boolean+}++const OIDCAuth = ({ onClick, className, disabled }: OIDCAuthProps) => {+ const { t } = useTranslation()++ return (+ <Button+ className={cx(+ className,+ 'flex w-full items-center justify-center border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700',+ )}+ onClick={onClick}+ secondary+ regular+ disabled={disabled}+ >+ <KeyRoundIcon className='mr-2 size-5' />+ {t('auth.common.oidc')}+ </Button>+ )+}++export default OIDCAuthdiff --git a/web/app/lib/models/Auth.ts b/web/app/lib/models/Auth.tsindex 9a75e524c..72780b239 100644--- a/web/app/lib/models/Auth.ts+++ b/web/app/lib/models/Auth.ts@@ -7,4 +7,4 @@ export interface Auth {totalMonthlyEvents: number}-export type SSOProvider = 'google' | 'github'+export type SSOProvider = 'google' | 'github' | 'openid-connect'diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsxindex aa223a1b8..4e846d29b 100644--- a/web/app/pages/Auth/Signin/Signin.tsx+++ b/web/app/pages/Auth/Signin/Signin.tsx@@ -1,3 +1,4 @@+import clsx from 'clsx'import _isEmpty from 'lodash/isEmpty'import _isString from 'lodash/isString'import _keys from 'lodash/keys'@@ -10,6 +11,7 @@ import { toast } from 'sonner'import { generateSSOAuthURL, getJWTBySSOHash, login, submit2FA } from '~/api'import GithubAuth from '~/components/GithubAuth'import GoogleAuth from '~/components/GoogleAuth'+import OIDCAuth from '~/components/OIDCAuth'import { withAuthentication, auth } from '~/hoc/protected'import { isSelfhosted, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'import { SSOProvider } from '~/lib/models/Auth'@@ -328,24 +330,28 @@ const Signin = () => {</Button></form>- {!isSelfhosted ? (- <div>- <div className='relative mt-10'>- <div className='absolute inset-0 flex items-center' aria-hidden='true'>- <div className='w-full border-t border-gray-200 dark:border-gray-600' />- </div>- <div className='relative flex justify-center text-sm leading-6 font-medium'>- <span className='bg-white px-6 text-gray-900 dark:bg-slate-800/20 dark:text-gray-50'>- {t('auth.common.orContinueWith')}- </span>- </div>+ <div>+ <div className='relative mt-10'>+ <div className='absolute inset-0 flex items-center' aria-hidden='true'>+ <div className='w-full border-t border-gray-200 dark:border-gray-600' /></div>- <div className='mt-6 grid grid-cols-2 gap-4'>- <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />- <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />+ <div className='relative flex justify-center text-sm leading-6 font-medium'>+ <span className='bg-white px-6 text-gray-900 dark:bg-slate-800/20 dark:text-gray-50'>+ {t('auth.common.orContinueWith')}+ </span></div></div>- ) : null}+ <div className={clsx('mt-6 grid gap-4', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>+ {isSelfhosted ? (+ <OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />+ ) : (+ <>+ <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />+ <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />+ </>+ )}+ </div>+ </div></div>{!isSelfhosted ? (diff --git a/web/app/pages/Auth/Socialised/index.tsx b/web/app/pages/Auth/Socialised/index.tsxindex ebf0dd0e2..d9c33f900 100644--- a/web/app/pages/Auth/Socialised/index.tsx+++ b/web/app/pages/Auth/Socialised/index.tsx@@ -5,8 +5,8 @@ import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { Link } from 'react-router'-import { processSSOToken } from '~/api'-import { SSO_PROVIDERS } from '~/lib/constants'+import { processSSOToken, processSSOTokenCommunityEdition } from '~/api'+import { isSelfhosted, SSO_PROVIDERS } from '~/lib/constants'import Loader from '~/ui/Loader'import routes from '~/utils/routes'@@ -20,34 +20,34 @@ const Socialised = () => {const _location = _replace(window.location.href, `${routes.socialised}#`, `${routes.socialised}?`)const { searchParams } = new URL(_location)- const hash = searchParams.get('state')+ const state = searchParams.get('state')const accessToken = searchParams.get('access_token')const code = searchParams.get('code')- const provider = _split(hash, ':')[0]+ const provider = _split(state, ':')[0]const processCode = async () => {- if (!hash || !provider) {+ if (!state || !provider) {setIsError(true)return}- let _token+ let _codeif (provider === SSO_PROVIDERS.GOOGLE) {- _token = accessToken+ _code = accessToken}if (provider === SSO_PROVIDERS.GITHUB) {- _token = code+ _code = code}- if (!_token) {+ if (!_code) {setIsError(true)return}try {- await processSSOToken(_token, hash)+ await processSSOToken(_code, state)} catch (reason) {setIsError(true)console.error(`[ERROR] Error while processing Google code: ${reason}`)@@ -56,8 +56,29 @@ const Socialised = () => {}}+ const processCodeCommunityEdition = async () => {+ if (!state || !code) {+ setIsError(true)+ return+ }++ try {+ await processSSOTokenCommunityEdition(code, state)+ } catch (reason) {+ setIsError(true)+ console.error(`[ERROR] Error while processing OIDC code: ${reason}`)+ } finally {+ setLoading(false)+ }+ }+setLoading(true)- processCode()++ if (isSelfhosted) {+ processCodeCommunityEdition()+ } else {+ processCode()+ }}, [])if (loading) {diff --git a/web/app/styles/tailwind.css b/web/app/styles/tailwind.cssindex 994eda6cf..722ee9e55 100644--- a/web/app/styles/tailwind.css+++ b/web/app/styles/tailwind.css@@ -16,7 +16,7 @@/* Minimum Heights */--min-height-page: calc(100vh - 74px);- --min-height-min-footer: calc(100vh - 148px);+ --min-height-min-footer: calc(100vh - 157px);}/* Custom Animations */diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 663b912ff..c94f337f2 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -498,8 +498,10 @@"addedOn": "Added on","continueWithGoogle": "Continue with Google","continueWithGithub": "Continue with Github",+ "continueWithOIDC": "Continue with OpenID Connect","google": "Google","github": "Github",+ "oidc": "OpenID Connect","orContinueWith": "Or continue with"}},