Skip to content

Commit

Permalink
revert #4206
Browse files Browse the repository at this point in the history
  • Loading branch information
mariusandra committed Oct 5, 2021
1 parent 45fbb68 commit 709201e
Show file tree
Hide file tree
Showing 13 changed files with 12 additions and 206 deletions.
28 changes: 0 additions & 28 deletions frontend/src/layout/navigation/Navigation.scss
Original file line number Diff line number Diff line change
Expand Up @@ -286,34 +286,6 @@
height: 22px;
}
}

.global-environment-switch {
display: flex;
align-items: center;
label {
font-weight: bold;
color: $success;
padding-right: 4px;
a {
color: $text_muted;
}

svg {
margin-right: 4px;
}

&.test {
color: $warning;
}
}
.ant-switch:not(.ant-switch-checked) {
background-color: $warning;
}

.ant-switch.ant-switch-checked {
background-color: $success;
}
}
}

.navigation-spacer {
Expand Down
36 changes: 4 additions & 32 deletions frontend/src/layout/navigation/TopNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { userLogic } from 'scenes/userLogic'
import { Badge } from 'lib/components/Badge'
import { ChangelogModal } from '~/layout/ChangelogModal'
import { router } from 'kea-router'
import { Button, Card, Dropdown, Switch } from 'antd'
import { Button, Card, Dropdown } from 'antd'
import {
ProjectOutlined,
DownOutlined,
Expand Down Expand Up @@ -35,12 +35,11 @@ import { AvailableFeature, TeamBasicType, UserType } from '~/types'
import { CreateInviteModalWithButton } from 'scenes/organization/Settings/CreateInviteModal'
import { preflightLogic } from 'scenes/PreflightCheck/logic'
import { billingLogic } from 'scenes/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { Environments, FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { OrganizationMembershipLevel } from 'lib/constants'
import { ProfilePicture } from 'lib/components/ProfilePicture'
import { Tooltip } from 'lib/components/Tooltip'
import { teamLogic } from '../../scenes/teamLogic'
import { organizationLogic } from '../../scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { organizationLogic } from 'scenes/organizationLogic'

export function WhoAmI({ user }: { user: UserType }): JSX.Element {
return (
Expand Down Expand Up @@ -106,7 +105,6 @@ export function TopNavigation(): JSX.Element {
setMenuCollapsed,
setChangelogModalOpen,
setInviteMembersModalOpen,
setFilteredEnvironment,
setProjectModalShown,
setOrganizationModalShown,
} = useActions(navigationLogic)
Expand All @@ -116,7 +114,6 @@ export function TopNavigation(): JSX.Element {
updateAvailable,
changelogModalOpen,
inviteMembersModalOpen,
filteredEnvironment,
projectModalShown,
organizationModalShown,
} = useValues(navigationLogic)
Expand All @@ -129,7 +126,6 @@ export function TopNavigation(): JSX.Element {
const { guardAvailableFeature } = useActions(sceneLogic)
const { sceneConfig } = useValues(sceneLogic)
const { showPalette } = useActions(commandPaletteLogic)
const { featureFlags } = useValues(featureFlagLogic)

const isCurrentProjectRestricted = currentTeam && !currentTeam.effective_membership_level
const isProjectCreationForbidden =
Expand Down Expand Up @@ -356,30 +352,6 @@ export function TopNavigation(): JSX.Element {
</div>
{user && (
<>
{featureFlags[FEATURE_FLAGS.TEST_ENVIRONMENT] && (
<div className="global-environment-switch">
<label
htmlFor="global-environment-switch"
className={filteredEnvironment === Environments.TEST ? 'test' : ''}
>
<Tooltip title="Toggle to view only test or production data everywhere. Click to learn more.">
<a href="https://posthog.com/docs" target="_blank" rel="noopener">
<InfoCircleOutlined />
</a>
</Tooltip>
{filteredEnvironment === Environments.PRODUCTION ? 'Production' : 'Test'}
</label>
<Switch
// @ts-expect-error - below works even if it's not defined as a prop
id="global-environment-switch"
checked={filteredEnvironment === Environments.PRODUCTION}
defaultChecked={filteredEnvironment === Environments.PRODUCTION}
onChange={(val) =>
setFilteredEnvironment(val ? Environments.PRODUCTION : Environments.TEST)
}
/>
</div>
)}
<Dropdown
overlay={whoAmIDropdown}
overlayClassName="navigation-top-dropdown-overlay"
Expand Down
27 changes: 0 additions & 27 deletions frontend/src/layout/navigation/navigationLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import { organizationLogic } from 'scenes/organizationLogic'
import dayjs from 'dayjs'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { preflightLogic } from 'scenes/PreflightCheck/logic'
import { Environments, ENVIRONMENT_LOCAL_STORAGE_KEY, FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'

type WarningType =
| 'welcome'
Expand All @@ -29,7 +27,6 @@ export const navigationLogic = kea<navigationLogicType<WarningType>>({
setPinnedDashboardsVisible: (visible: boolean) => ({ visible }),
setInviteMembersModalOpen: (isOpen: boolean) => ({ isOpen }),
setHotkeyNavigationEngaged: (hotkeyNavigationEngaged: boolean) => ({ hotkeyNavigationEngaged }),
setFilteredEnvironment: (environment: string, pageLoad: boolean = false) => ({ environment, pageLoad }),
setProjectModalShown: (isShown: boolean) => ({ isShown }),
setOrganizationModalShown: (isShown: boolean) => ({ isShown }),
},
Expand Down Expand Up @@ -70,12 +67,6 @@ export const navigationLogic = kea<navigationLogicType<WarningType>>({
setHotkeyNavigationEngaged: (_, { hotkeyNavigationEngaged }) => hotkeyNavigationEngaged,
},
],
filteredEnvironment: [
Environments.PRODUCTION.toString(),
{
setFilteredEnvironment: (_, { environment }) => environment,
},
],
projectModalShown: [
false,
{
Expand Down Expand Up @@ -185,27 +176,9 @@ export const navigationLogic = kea<navigationLogicType<WarningType>>({
actions.setHotkeyNavigationEngaged(false)
}
},
setFilteredEnvironment: ({ pageLoad, environment }) => {
const localStorageValue = window.localStorage.getItem(ENVIRONMENT_LOCAL_STORAGE_KEY)
const isLocalStorageValueEmpty = localStorageValue === null
const shouldWriteToLocalStorage = (pageLoad === true && isLocalStorageValueEmpty) || pageLoad === false
if (shouldWriteToLocalStorage) {
window.localStorage.setItem(ENVIRONMENT_LOCAL_STORAGE_KEY, environment)
}
const shouldReload = pageLoad === false && localStorageValue !== environment
if (shouldReload) {
location.reload()
}
},
}),
events: ({ actions }) => ({
afterMount: () => {
const notSharedDashboard = location.pathname.indexOf('shared_dashboard') > -1 ? false : true
if (notSharedDashboard && featureFlagLogic.values.featureFlags[FEATURE_FLAGS.TEST_ENVIRONMENT]) {
const localStorageValue =
window.localStorage.getItem(ENVIRONMENT_LOCAL_STORAGE_KEY) || Environments.PRODUCTION
actions.setFilteredEnvironment(localStorageValue, true)
}
actions.loadLatestVersion()
},
}),
Expand Down
56 changes: 3 additions & 53 deletions frontend/src/lib/api.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { fromParamsGivenUrl, toParams } from 'lib/utils'
import { Environments, ENVIRONMENT_LOCAL_STORAGE_KEY } from 'lib/constants'
import posthog from 'posthog-js'

export function getCookie(name) {
Expand Down Expand Up @@ -28,8 +26,9 @@ async function getJSONOrThrow(response) {

class Api {
async get(url, signal = undefined) {
// TODO: how to put behind a feature flag
url = maybeAddEnvironmentProperty(url)
if (url.indexOf('http') !== 0) {
url = '/' + url + (url.indexOf('?') === -1 && url[url.length - 1] !== '/' ? '/' : '')
}

let response
const startTime = new Date().getTime()
Expand Down Expand Up @@ -115,55 +114,6 @@ class Api {
}
}

function isWhitelisted(url) {
const WHITELIST = ['api']

for (let i = 0; i < WHITELIST.length; i++) {
const urlWithSlash = '/' + url
const startsWith = url.indexOf(WHITELIST[i]) === 0 || urlWithSlash.indexOf(WHITELIST[i]) === 0
if (startsWith) {
return true
}
}

return false
}

function maybeAddEnvironmentProperty(url) {
const localStorageEnvironmentValue = window.localStorage.getItem(ENVIRONMENT_LOCAL_STORAGE_KEY)
const isWhitelistedUrl = isWhitelisted(url)
const shouldAddEnvironmentValue = localStorageEnvironmentValue && isWhitelistedUrl

if (shouldAddEnvironmentValue) {
let urlObject = url.indexOf('http') === 0 ? new URL(url) : new URL(url, window.location.origin)

let params = fromParamsGivenUrl(urlObject.search)

const environmentProperty =
localStorageEnvironmentValue === Environments.PRODUCTION
? { key: '$environment', operator: 'is_not', value: ['test'] }
: { key: '$environment', operator: 'exact', value: ['test'] }

if (params.properties) {
let parsedProperties = JSON.parse(params.properties)
parsedProperties = Array.isArray(parsedProperties)
? [...parsedProperties, environmentProperty]
: [parsedProperties, environmentProperty]
params.properties = JSON.stringify(parsedProperties)
} else {
params.properties = JSON.stringify([environmentProperty])
}

return url.indexOf('http') === 0
? urlObject.origin + urlObject.pathname + '?' + toParams(params)
: urlObject.pathname + '?' + toParams(params)
} else if (url.indexOf('http') !== 0) {
return '/' + url + (url.indexOf('?') === -1 && url[url.length - 1] !== '/' ? '/' : '')
} else {
return url
}
}

function reportError(method, url, response, startTime) {
const duration = new Date().getTime() - startTime
const pathname = new URL(url, location.origin).pathname
Expand Down
7 changes: 0 additions & 7 deletions frontend/src/lib/components/PropertyKeyInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -375,13 +375,6 @@ export const keyMapping: KeyMappingInterface = {
examples: ['16ff262c4301e5-0aa346c03894bc-39667c0e-1aeaa0-16ff262c431767'],
hide: true,
},
$environment: {
label: 'Environment',
description: 'Environment used to filter results on all queries when enabled.',
examples: ['test', 'production'],
hide: true,
},

// GeoIP
$geoip_city_name: {
label: 'City Name',
Expand Down
8 changes: 0 additions & 8 deletions frontend/src/lib/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,6 @@ export const WEBHOOK_SERVICES: Record<string, string> = {
}

export const FEATURE_FLAGS = {
TEST_ENVIRONMENT: 'test-environment-3149',
PAPERCUPS_ENABLED: 'papercups-enabled',
INGESTION_GRID: 'ingestion-grid-exp-3',
PROJECT_HOME: 'project-home-exp-5',
Expand All @@ -252,13 +251,6 @@ export const FEATURE_FLAGS = {
CLOUD_ANNOUNCEMENT: 'cloud-announcement',
}

export const ENVIRONMENT_LOCAL_STORAGE_KEY = '$environment'

export enum Environments {
PRODUCTION = 'production',
TEST = 'test',
}

export const ENTITY_MATCH_TYPE = 'entities'
export const PROPERTY_MATCH_TYPE = 'properties'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { FilterType } from '~/types'
import { SettingOutlined } from '@ant-design/icons'
import { teamLogic } from 'scenes/teamLogic'
import { Tooltip } from 'lib/components/Tooltip'
//import { featureFlagLogic } from 'lib/logic/featureFlagLogic'

export function TestAccountFilter({
filters,
Expand All @@ -17,9 +16,7 @@ export function TestAccountFilter({
}): JSX.Element | null {
const { currentTeam } = useValues(teamLogic)
const hasFilters = (currentTeam?.test_account_filters || []).length > 0
//const { featureFlags } = useValues(featureFlagLogic)

//return featureFlags[FEATURE_FLAGS.TEST_ENVIRONMENT] ? null : (
return (
<Tooltip
title={
Expand Down
7 changes: 1 addition & 6 deletions posthog/api/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

from posthog.api.utils import get_token
from posthog.celery import app as celery_app
from posthog.constants import ENVIRONMENT_TEST
from posthog.exceptions import RequestParsingError, generate_exception_response
from posthog.helpers.session_recording import preprocess_session_recording_events
from posthog.models import Team, User
Expand Down Expand Up @@ -136,7 +135,7 @@ def get_event(request):

sent_at = _get_sent_at(data, request)

token, is_test_environment = get_token(data, request)
token = get_token(data, request)

if not token:
return cors_response(
Expand Down Expand Up @@ -243,10 +242,6 @@ def get_event(request):
if not event.get("properties"):
event["properties"] = {}

# Support test_[apiKey] for users with multiple environments
if event["properties"].get("$environment") is None and is_test_environment:
event["properties"]["$environment"] = ENVIRONMENT_TEST

_ensure_web_feature_flags_in_properties(event, team, distinct_id)

statsd.incr("posthog_cloud_plugin_server_ingestion")
Expand Down
2 changes: 1 addition & 1 deletion posthog/api/decide.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def get_decide(request: HttpRequest):
generate_exception_response("decide", f"Malformed request data: {error}", code="malformed_data"),
)

token, _ = get_token(data, request)
token = get_token(data, request)
team = Team.objects.get_team_from_token(token)
if team is None and token:
project_id = _get_project_id(data, request)
Expand Down
2 changes: 1 addition & 1 deletion posthog/api/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def get_serializer_context(self) -> Dict[str, Any]:

def _get_team_from_request(self) -> Optional["Team"]:
team_found = None
token, _ = get_token(None, self.request)
token = get_token(None, self.request)

if token:
team = Team.objects.get_team_from_token(token)
Expand Down
35 changes: 0 additions & 35 deletions posthog/api/test/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from freezegun import freeze_time
from rest_framework import status

from posthog.constants import ENVIRONMENT_TEST
from posthog.models import PersonalAPIKey
from posthog.models.feature_flag import FeatureFlag
from posthog.test.base import BaseTest
Expand Down Expand Up @@ -86,40 +85,6 @@ def test_capture_event(self, patch_process_event_with_plugins):
},
)

@patch("posthog.models.team.TEAM_CACHE", {})
@patch("posthog.api.capture.celery_app.send_task")
def test_test_api_key(self, patch_process_event_with_plugins):
api_token = "test_" + self.team.api_token
data: Dict[str, Any] = {
"event": "$autocapture",
"properties": {
"distinct_id": 2,
"token": api_token,
"$elements": [
{"tag_name": "a", "nth_child": 1, "nth_of_type": 2, "attr__class": "btn btn-sm",},
{"tag_name": "div", "nth_child": 1, "nth_of_type": 2, "$el_text": "💻",},
],
},
}
now = timezone.now()
with freeze_time(now):
with self.assertNumQueries(1):
response = self.client.get("/e/?data=%s" % quote(self._to_json(data)), HTTP_ORIGIN="https://localhost",)
self.assertEqual(response.get("access-control-allow-origin"), "https://localhost")
arguments = self._to_arguments(patch_process_event_with_plugins)
arguments.pop("now") # can't compare fakedate
arguments.pop("sent_at") # can't compare fakedate
self.assertDictEqual(
arguments,
{
"distinct_id": "2",
"ip": "127.0.0.1",
"site_url": "http://testserver",
"data": {**data, "properties": {**data["properties"], "$environment": ENVIRONMENT_TEST}},
"team_id": self.team.pk,
},
)

@patch("posthog.models.team.TEAM_CACHE", {})
@patch("posthog.api.capture.celery_app.send_task")
def test_personal_api_key(self, patch_process_event_with_plugins):
Expand Down
Loading

0 comments on commit 709201e

Please sign in to comment.