Skip to content

Commit

Permalink
Merge branch 'master' into person-hacktivity-node
Browse files Browse the repository at this point in the history
  • Loading branch information
Twixes committed Oct 26, 2023
2 parents ca61e19 + d6d259a commit 4127132
Show file tree
Hide file tree
Showing 1,189 changed files with 71,667 additions and 10,625 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MAPLIBRE_STYLE_URL=https://api.example.com/style.json?key=mykey
20 changes: 18 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ module.exports = {
react: {
version: 'detect',
},
'import/resolver': {
node: {
paths: ['eslint-rules'], // Add the directory containing your custom rules
extensions: ['.js', '.jsx', '.ts', '.tsx'], // Ensure ESLint resolves both JS and TS files
},
},
},
extends: [
'eslint:recommended',
Expand All @@ -37,7 +43,7 @@ module.exports = {
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: ['prettier', 'react', 'cypress', '@typescript-eslint', 'no-only-tests', 'jest', 'compat'],
plugins: ['prettier', 'react', 'cypress', '@typescript-eslint', 'no-only-tests', 'jest', 'compat', 'posthog'],
rules: {
'no-console': ['error', { allow: ['warn', 'error'] }],
'no-debugger': 'error',
Expand Down Expand Up @@ -91,7 +97,7 @@ module.exports = {
],
},
],
'react/forbid-elements': [
'posthog/warn-elements': [
1,
{
forbid: [
Expand Down Expand Up @@ -236,6 +242,16 @@ module.exports = {
'@typescript-eslint/no-var-requires': 'off',
},
},
{
files: 'eslint-rules/**/*',
extends: ['eslint:recommended'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
},
env: {
node: true,
},
},
],
reportUnusedDisableDirectives: true,
}
20 changes: 0 additions & 20 deletions .storybook/decorators/with3000.tsx

This file was deleted.

8 changes: 4 additions & 4 deletions .storybook/decorators/withFeatureFlags.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useFeatureFlags } from '~/mocks/browser'
import type { DecoratorFn } from '@storybook/react'
import { setFeatureFlags } from '~/mocks/browser'
import type { Decorator } from '@storybook/react'

/** Global story decorator that allows setting feature flags.
*
Expand All @@ -13,9 +13,9 @@ import type { DecoratorFn } from '@storybook/react'
* } as ComponentMeta<typeof MyComponent>
* ```
*/
export const withFeatureFlags: DecoratorFn = (Story, { parameters }) => {
export const withFeatureFlags: Decorator = (Story, { parameters }) => {
if (parameters.featureFlags) {
useFeatureFlags(parameters.featureFlags)
setFeatureFlags(parameters.featureFlags)
}

return <Story />
Expand Down
4 changes: 2 additions & 2 deletions .storybook/decorators/withKea/withKea.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { DecoratorFn } from '@storybook/react'
import type { Decorator } from '@storybook/react'
import { useAvailableFeatures } from '~/mocks/features'

import { KeaStory } from './kea-story'

export const withKea: DecoratorFn = (Story) => {
export const withKea: Decorator = (Story) => {
// Reset enabled enterprise features. Overwrite this line within your stories.
useAvailableFeatures([])
return (
Expand Down
4 changes: 2 additions & 2 deletions .storybook/decorators/withMockDate.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DecoratorFn } from '@storybook/react'
import type { Decorator } from '@storybook/react'
import MockDate from 'mockdate'

/** Global story decorator that allows mocking of dates.
Expand All @@ -13,7 +13,7 @@ import MockDate from 'mockdate'
* } as ComponentMeta<typeof MyComponent>
* ```
*/
export const withMockDate: DecoratorFn = (Story, { parameters }) => {
export const withMockDate: Decorator = (Story, { parameters }) => {
if (parameters.mockDate) {
MockDate.set(parameters.mockDate)
} else {
Expand Down
4 changes: 2 additions & 2 deletions .storybook/decorators/withSnapshotsDisabled.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { DecoratorFn } from '@storybook/react'
import { Decorator } from '@storybook/react'
import { inStorybookTestRunner } from 'lib/utils'

/** Workaround for https://github.com/storybookjs/test-runner/issues/74 */
// TODO: Smoke-test all the stories by removing this decorator, once all the stories pass
export const withSnapshotsDisabled: DecoratorFn = (Story, { parameters }) => {
export const withSnapshotsDisabled: Decorator = (Story, { parameters }) => {
if (parameters?.testOptions?.skip && inStorybookTestRunner()) {
return <>Disabled for Test Runner</>
}
Expand Down
44 changes: 44 additions & 0 deletions .storybook/decorators/withTheme.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { Decorator } from '@storybook/react'

import { FEATURE_FLAGS } from 'lib/constants'

/** Global story decorator that is used by the theming control to
* switch between themes.
*/
export const withTheme: Decorator = (Story, context) => {
const theme = context.globals.theme

// set the body class
const actualClassState = document.body.classList.contains('posthog-3000')
const desiredClassState = theme !== 'legacy'

if (actualClassState !== desiredClassState) {
if (desiredClassState) {
document.body.classList.add('posthog-3000')
} else {
document.body.classList.remove('posthog-3000')
}
}

// set the feature flag
const actualFeatureFlagState = window.POSTHOG_APP_CONTEXT!.persisted_feature_flags?.includes(
FEATURE_FLAGS.POSTHOG_3000
)
const desiredFeatureFlagState = theme !== 'legacy'

if (actualFeatureFlagState !== desiredFeatureFlagState) {
const currentFlags = window.POSTHOG_APP_CONTEXT!.persisted_feature_flags || []
if (desiredFeatureFlagState) {
window.POSTHOG_APP_CONTEXT!.persisted_feature_flags = [...currentFlags, FEATURE_FLAGS.POSTHOG_3000]
} else {
window.POSTHOG_APP_CONTEXT!.persisted_feature_flags = currentFlags.filter(
(f) => f !== FEATURE_FLAGS.POSTHOG_3000
)
}
}

// set the theme
document.body.setAttribute('theme', theme === 'dark' ? 'dark' : 'light')

return <Story />
}
19 changes: 19 additions & 0 deletions .storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { withMockDate } from './decorators/withMockDate'
import { defaultMocks } from '~/mocks/handlers'
import { withSnapshotsDisabled } from './decorators/withSnapshotsDisabled'
import { withFeatureFlags } from './decorators/withFeatureFlags'
import { withTheme } from './decorators/withTheme'

const setupMsw = () => {
// Make sure the msw worker is started
Expand Down Expand Up @@ -86,6 +87,8 @@ export const decorators: Meta['decorators'] = [
withMockDate,
// Allow us to easily set feature flags in stories.
withFeatureFlags,
// Set theme from global context
withTheme,
]

const preview: Preview = {
Expand All @@ -110,6 +113,22 @@ const preview: Preview = {
),
},
},
globalTypes: {
theme: {
description: '',
defaultValue: 'legacy',
toolbar: {
title: 'Theme',
items: [
{ value: 'legacy', icon: 'faceneutral', title: 'Legacy' },
{ value: 'light', icon: 'sun', title: 'Light' },
{ value: 'dark', icon: 'moon', title: 'Dark' },
],
// change the title based on the selected value
dynamicTitle: true,
},
},
},
}

export default preview
12 changes: 12 additions & 0 deletions docker-compose.base.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,18 @@ services:
command: ./bin/start-backend & ./bin/start-frontend
restart: on-failure

capture:
image: ghcr.io/posthog/capture:main
restart: on-failure
environment:
ADDRESS: '0.0.0.0:3000'
KAFKA_TOPIC: 'events_plugin_ingestion'
KAFKA_HOSTS: 'kafka:9092'
REDIS_URL: 'redis://redis:6379/'
depends_on:
- redis
- kafka

plugins:
command: ./bin/plugin-server --no-restart-loop
restart: on-failure
Expand Down
9 changes: 9 additions & 0 deletions docker-compose.dev-full.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ services:
environment:
- DEBUG=1

capture:
extends:
file: docker-compose.base.yml
service: capture
ports:
- 3000:3000
environment:
- DEBUG=1

plugins:
extends:
file: docker-compose.base.yml
Expand Down
11 changes: 11 additions & 0 deletions docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ services:
- '1080:1080'
- '1025:1025'

# Optional capture
capture:
profiles: ['capture-rs']
extends:
file: docker-compose.base.yml
service: capture
ports:
- 3000:3000
environment:
- DEBUG=1

# Temporal containers
elasticsearch:
extends:
Expand Down
25 changes: 19 additions & 6 deletions ee/api/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

@api_view(["GET"])
def saml_metadata_view(request, *args, **kwargs):

if (
not request.user.organization_memberships.get(organization=request.user.organization).level
>= OrganizationMembership.Level.ADMIN
Expand All @@ -46,7 +45,6 @@ class MultitenantSAMLAuth(SAMLAuth):
"""

def get_idp(self, organization_domain_or_id: Union["OrganizationDomain", str]):

try:
organization_domain = (
organization_domain_or_id
Expand All @@ -57,7 +55,10 @@ def get_idp(self, organization_domain_or_id: Union["OrganizationDomain", str]):
raise AuthFailed("saml", "Authentication request is invalid. Invalid RelayState.")

if not organization_domain.organization.is_feature_available(AvailableFeature.SAML):
raise AuthFailed("saml", "Your organization does not have the required license to use SAML.")
raise AuthFailed(
"saml",
"Your organization does not have the required license to use SAML.",
)

return SAMLIdentityProvider(
str(organization_domain.id),
Expand Down Expand Up @@ -88,7 +89,12 @@ def auth_url(self):
# name, since we multiple IdPs share the same auth_complete URL.
return auth.login(return_to=str(instance.id))

def _get_attr(self, response_attributes: Dict[str, Any], attribute_names: List[str], optional: bool = False) -> str:
def _get_attr(
self,
response_attributes: Dict[str, Any],
attribute_names: List[str],
optional: bool = False,
) -> str:
"""
Fetches a specific attribute from the SAML response, attempting with multiple different attribute names.
We attempt multiple attribute names to make it easier for admins to configure SAML (less configuration to set).
Expand All @@ -114,7 +120,9 @@ def get_user_details(self, response):
attributes = response["attributes"]
return {
"fullname": self._get_attr(
attributes, ["full_name", "FULL_NAME", "fullName", OID_COMMON_NAME], optional=True
attributes,
["full_name", "FULL_NAME", "fullName", OID_COMMON_NAME],
optional=True,
),
"first_name": self._get_attr(
attributes,
Expand All @@ -140,7 +148,12 @@ def get_user_details(self, response):
),
"email": self._get_attr(
attributes,
["email", "EMAIL", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", OID_MAIL],
[
"email",
"EMAIL",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
OID_MAIL,
],
),
}

Expand Down
9 changes: 7 additions & 2 deletions ee/api/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ def patch(self, request: Request, *args: Any, **kwargs: Any) -> Response:
BillingManager(license).update_billing(org, {"custom_limits_usd": custom_limits_usd})

if distinct_id:
posthoganalytics.capture(distinct_id, "billing limits updated", properties={**custom_limits_usd})
posthoganalytics.capture(
distinct_id,
"billing limits updated",
properties={**custom_limits_usd},
)
posthoganalytics.group_identify(
"organization",
str(org.id),
Expand Down Expand Up @@ -143,7 +147,8 @@ def license(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
license = License(key=serializer.validated_data["license"])

res = requests.get(
f"{BILLING_SERVICE_URL}/api/billing", headers=BillingManager(license).get_auth_headers(organization)
f"{BILLING_SERVICE_URL}/api/billing",
headers=BillingManager(license).get_auth_headers(organization),
)

if res.status_code != 200:
Expand Down
6 changes: 5 additions & 1 deletion ee/api/dashboard_collaborator.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ class DashboardCollaboratorViewSet(
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
permission_classes = [IsAuthenticated, TeamMemberAccessPermission, CanEditDashboardCollaborator]
permission_classes = [
IsAuthenticated,
TeamMemberAccessPermission,
CanEditDashboardCollaborator,
]
pagination_class = None
queryset = DashboardPrivilege.objects.select_related("dashboard").filter(user__is_active=True)
lookup_field = "user__uuid"
Expand Down
6 changes: 5 additions & 1 deletion ee/api/ee_event_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
from ee.models.event_definition import EnterpriseEventDefinition
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin
from posthog.models.activity_logging.activity_log import dict_changes_between, log_activity, Detail
from posthog.models.activity_logging.activity_log import (
dict_changes_between,
log_activity,
Detail,
)


class EnterpriseEventDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
Expand Down
6 changes: 5 additions & 1 deletion ee/api/ee_property_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin
from posthog.models import PropertyDefinition
from posthog.models.activity_logging.activity_log import dict_changes_between, log_activity, Detail
from posthog.models.activity_logging.activity_log import (
dict_changes_between,
log_activity,
Detail,
)


class EnterprisePropertyDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
Expand Down
Loading

0 comments on commit 4127132

Please sign in to comment.