0
0
mirror of https://github.com/PostHog/posthog.git synced 2024-11-28 09:16:49 +01:00
posthog/ee/models/license.py

120 lines
4.0 KiB
Python
Raw Normal View History

from typing import Optional
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import Q
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
from django.utils import timezone
from rest_framework import exceptions, status
from posthog.constants import AvailableFeature
from posthog.models.utils import sane_repr
from posthog.tasks.tasks import sync_all_organization_available_product_features
class LicenseError(exceptions.APIException):
"""
Exception raised for licensing errors.
"""
default_type = "license_error"
default_code = "license_error"
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "There was a problem with your current license."
def __init__(self, code, detail):
self.code = code
self.detail = exceptions._get_error_details(detail, code)
class LicenseManager(models.Manager):
def first_valid(self) -> Optional["License"]:
"""Return the highest valid license or cloud licenses if any"""
valid_licenses = list(self.filter(Q(valid_until__gte=timezone.now()) | Q(plan="cloud")))
if not valid_licenses:
return None
return max(
valid_licenses,
key=lambda license: License.PLAN_TO_SORTING_VALUE.get(license.plan, 0),
)
class License(models.Model):
objects: LicenseManager = LicenseManager()
Personal API keys and Zapier integration (#1281) * Add missing migration * Add generate_random_token() model util * Move PublicTokenAuthentication to utils * Make use of generate_random_token * Add User.personal_access_token field * Add PersonalAccessTokenAuthentication * Fix PublicTokenAuthentication * Fix migration and auth import * Add personal_access_token to user API * Update Setup.js * Support trailing slash in API * Improve PAT auth quality * Add django-rest-hooks requirement * Update settings.py for rest_hooks * Fix django-rest-hooks requirement * Bring back API routes with no double trailing slash * Rename posthog.api.team to team_user * Add API TODO * Ad PAT auth with X-PAT HTTP header * Replace User.personal_access_token with PersonalAPIKey model * Fix PersonalAPIKey max_lengths * Describe posthog.models.utils.generate_random_token better * Add personal_api_key to API * Add authenticate_header to PersonalAPIKeyAuthentication * Add hook API endpoint * Use django.utils.timezone in place of datetime.datetime * Add Personal API Keys to Setup * Sort personal_api_keys in ORM * Add Action.on_perform() * Remove requirements.txt comment * Add a * Add REST hook tasks * Optimize PersonalAPIKeyAuthentication query * Add a trailing slash version of /e endpoint * Add team field to PersonalAPIKey model * Add personal API key support to capture endpoint, get_cached_from_token * Reject personal API keys from inactive users * Add extra_properties_json field to /capture * Improve PAK auth header regex * Use custom hook model * Deliver hooks * Handle action.on_perform * Consolidate userLogic in userLogic.tsx * Update PersonalAPIKeys.js * Make PersonalAPIKey foreign keys read-only * Update requirements/dev.txt * Make PersonalAPIKeys TSX * Fix conflict * Fix migration * Fix minor mishaps * Update and fix tests * Use CharField of random 32 bits as hook.id * Fix conflicting migrations * Fix ValidationError in HookSerializer.validate_event * Use query param in /api/event/actions ID filtering * Rename endpoint `hook` to `hooks` * Satisfy mypy * Add tests * Use DRF serialization in action_defined and annotation_created triggers * Update migration leafs * Make mypy ignore rest_hooks * Update Django signal receiver names * Update TS dependencies * Revert "Update TS dependencies" This reverts commit 7fc26fefcdc16e630e1c8fd2c510fd323d97169f. * Add field user to Hook model * Update migration leafs * Fix circular import * Fix some code * Install git before running pip install in Dockerfiles * Improve personal API keys UI * Satisfy mypy * Reword key label placeholder * Add personal API key support to /api/user/* Unfortunately these endpoints are still limited by CSRF protections at the moment, so not accessible outside PostHog itself. * Improve PersonalAPIKeyAuthentication and add CsrfOrKeyViewMiddleware * Run collectstatic before test * Don't install dev dependencies in CI * Update dependency installation order in CI * Fix bug and describe PersonalAPIKeyAuthentication * Fix CI issues * Fix typing issues * Fix more typing issues * Use /api/personal_api_keys to list keys * Move REST hooks (and therefore Zapier) to ee/ * Refactor personal API logic with kea-loaders * Add "More about API authentication in PostHog docs." * Update PersonalAPIKeys.tsx * Use TestMixin * Fix "Authentication" that should've been "Authorization" * Add option to skip self.client.force_login in API tests * Include team_id and user_id in personal API key serialization * Update test_hooks.py * Add personal API key tests * Remove leftover * Make ee.settings override posthog.settings * Don't directly import from models * Remove unused imports * Fix mypy issues * Fix HOOK_DELIVERER * Use decorator for /api/user PAK auth * Don't fire REST hook if user doesn't have "zapier" feature * Import Optional * Reword to "premium Zapier" * Make mypy happy * Fix test_delete_personal_api_key * Fix misclick * Fix and test /capture with personal API key * Make mypy happy * Remove extra_properties_json * Resolve migrations * Remove apt-utils * Optimize and test PAK user.is_active filtering * Replace DEBUG true with 1 * Remove unused instance_id * Improve typing * Fix deletion toast * Refactor CopyToClipboard and use it in PAKs * Use toast.success * Update migrations * Fix migration * Fix migrations * Complete merge Co-authored-by: Tim Glaser <tim@glsr.nl>
2020-08-26 10:34:57 +02:00
created_at = models.DateTimeField(auto_now_add=True)
plan = models.CharField(max_length=200)
valid_until = models.DateTimeField()
key = models.CharField(max_length=200)
2022-10-19 08:58:36 +02:00
# DEPRECATED: This is no longer used
max_users = models.IntegerField(default=None, null=True) # None = no restriction
# NOTE: Remember to update the Billing Service as well. Long-term it will be the source of truth.
2021-10-14 14:13:37 +02:00
SCALE_PLAN = "scale"
SCALE_FEATURES = [
AvailableFeature.ZAPIER,
AvailableFeature.ORGANIZATIONS_PROJECTS,
AvailableFeature.SOCIAL_SSO,
AvailableFeature.INGESTION_TAXONOMY,
AvailableFeature.PATHS_ADVANCED,
AvailableFeature.CORRELATION_ANALYSIS,
AvailableFeature.GROUP_ANALYTICS,
AvailableFeature.TAGGING,
AvailableFeature.BEHAVIORAL_COHORT_FILTERING,
AvailableFeature.WHITE_LABELLING,
AvailableFeature.SUBSCRIPTIONS,
AvailableFeature.APP_METRICS,
AvailableFeature.RECORDINGS_PLAYLISTS,
AvailableFeature.RECORDINGS_FILE_EXPORT,
2023-01-06 09:51:51 +01:00
AvailableFeature.RECORDINGS_PERFORMANCE,
2021-10-14 14:13:37 +02:00
]
ENTERPRISE_PLAN = "enterprise"
2024-04-19 14:19:10 +02:00
ENTERPRISE_FEATURES = [
*SCALE_FEATURES,
AvailableFeature.ADVANCED_PERMISSIONS,
AvailableFeature.PROJECT_BASED_PERMISSIONING,
2021-10-14 14:13:37 +02:00
AvailableFeature.SAML,
AvailableFeature.SSO_ENFORCEMENT,
feat: role based permissions (#12657) * initial role and role memberships setup * create role when org is created and role memberships when user joins * wip for merge * fix api tests for role * nest roles under organization route and test fixes * remove pdb set trace * fix types * remove creating default roles and role memberships for orgs and users * add permission levels to orgs and roles * bulk create role memberships * leave role membership as individual api request, handle bulk creation on the frontend instead * feature flag role access wip and migrations * fix flag role access tests * linter * isort * temp type ignore * add access level to plugin tests * test remove test migration safe * test license import error fix * delete old? org license test * nvm we need these tests * type ignore * reset license plans after test * add organization resource access model and remove access level field from regular organizations * feat: permission return on feature flag (#12826) * suggested permission return * change naming * add changes * pass bool * fix plugin tests * organization resource access tests and fixes * update can edit return with new org resource access model from feature flag * fix tests * add permissions to feature flag for editing * more tests * remove unnecessary spacing * fix test * add context for feature flag serializer tests * add back workflow test step * add organization to feature flag role access * fix(spike): why are tests failing (#12858) * was it because invalid id is provided? * allow django to touch the db * a less unexpected way of allowing access to the DB * Revert "add organization to feature flag role access" This reverts commit ef18b0ec8b0bca0dede6a8614eb94f5879f442a7. * address feedback and include organization safety checks in tests * test error fix * test role dupe name per org * remove third access level option * fix migration for it * more tests * fix test * feat: role based permissions UI (#12776) * add api * starter * role and member creation + deletion * working with all deletes * add block * working roles * permissions tab on org settings * org default setting * types * flag role assignment * working per flag permission * working with admin block * types * use restricted area component * wrap flag resource access in different url * restore migrations manifest * update url endpoints * pay gate mini org role settings * remove view and custom edit and remove resource access creation on org creation * add feature flag * address feedback * fix backend tests * remove broken permissions setting on new feature flags * export logic props interface Co-authored-by: Li Yi Yu <li@posthog.com> * type fixes Co-authored-by: Eric Duong <eeoneric@gmail.com> Co-authored-by: Paul D'Ambra <paul@posthog.com>
2022-11-24 02:36:29 +01:00
AvailableFeature.ROLE_BASED_ACCESS,
2021-10-14 14:13:37 +02:00
]
PLANS = {SCALE_PLAN: SCALE_FEATURES, ENTERPRISE_PLAN: ENTERPRISE_FEATURES}
# The higher the plan, the higher its sorting value - sync with front-end licenseLogic
PLAN_TO_SORTING_VALUE = {SCALE_PLAN: 10, ENTERPRISE_PLAN: 20}
@property
def available_features(self) -> list[AvailableFeature]:
return self.PLANS.get(self.plan, [])
@property
def is_v2_license(self) -> bool:
return self.key and len(self.key.split("::")) == 2
__repr__ = sane_repr("key", "plan", "valid_until")
def get_licensed_users_available() -> Optional[int]:
"""
Returns the number of user slots available that can be created based on the instance's current license.
Not relevant for cloud users.
`None` means unlimited users.
"""
license = License.objects.first_valid()
from posthog.models import OrganizationInvite
if license:
if license.max_users is None:
return None
users_left = license.max_users - get_user_model().objects.count() - OrganizationInvite.objects.count()
return max(users_left, 0)
return None
@receiver(post_save, sender=License)
def license_saved(sender, instance, created, raw, using, **kwargs):
sync_all_organization_available_product_features()