mirror of
https://github.com/Eugeny/tabby-web.git
synced 2026-08-17 06:46:05 +01:00
wip
This commit is contained in:
@@ -17,7 +17,7 @@ from social_django.models import UserSocialAuth
|
||||
from typing import List
|
||||
|
||||
from .consumers import GatewayAdminConnection
|
||||
from .sponsors import get_sponsor_usernames
|
||||
from .sponsors import check_is_sponsor, check_is_sponsor_cached
|
||||
from .models import Config, Gateway, User
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ class GatewaySerializer(ModelSerializer):
|
||||
|
||||
|
||||
class ConfigSerializer(ModelSerializer):
|
||||
name = fields.CharField(required=False)
|
||||
|
||||
class Meta:
|
||||
model = Config
|
||||
read_only_fields = ('user', 'created_at', 'modified_at')
|
||||
@@ -100,6 +102,7 @@ class AppVersionViewSet(ListModelMixin, GenericViewSet):
|
||||
class UserSerializer(ModelSerializer):
|
||||
id = fields.IntegerField()
|
||||
is_pro = fields.SerializerMethodField()
|
||||
is_sponsor = fields.SerializerMethodField()
|
||||
github_username = fields.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
@@ -110,16 +113,18 @@ class UserSerializer(ModelSerializer):
|
||||
'active_config',
|
||||
'custom_connection_gateway',
|
||||
'custom_connection_gateway_token',
|
||||
'config_sync_token',
|
||||
'is_pro',
|
||||
'is_sponsor',
|
||||
'github_username',
|
||||
)
|
||||
read_only_fields = ('id', 'username')
|
||||
|
||||
def get_is_pro(self, obj):
|
||||
username = self.get_github_username(obj)
|
||||
if not username:
|
||||
return False
|
||||
return username in get_sponsor_usernames()
|
||||
return check_is_sponsor_cached(obj) or obj.force_pro
|
||||
|
||||
def get_is_sponsor(self, obj):
|
||||
return check_is_sponsor_cached(obj)
|
||||
|
||||
def get_github_username(self, obj):
|
||||
social_auth = UserSocialAuth.objects.filter(user=obj, provider='github').first()
|
||||
|
||||
@@ -32,8 +32,8 @@ class Migration(migrations.Migration):
|
||||
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
|
||||
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
|
||||
('active_version', models.CharField(max_length=32, null=True)),
|
||||
('custom_connection_gateway', models.CharField(max_length=255, null=True)),
|
||||
('custom_connection_gateway_token', models.CharField(max_length=255, null=True)),
|
||||
('custom_connection_gateway', models.CharField(max_length=255, null=True, blank=True)),
|
||||
('custom_connection_gateway_token', models.CharField(max_length=255, null=True, blank=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('modified_at', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
|
||||
29
tabby/app/migrations/0004_sync_token.py
Normal file
29
tabby/app/migrations/0004_sync_token.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import secrets
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def run_forward(apps, schema_editor):
|
||||
for user in apps.get_model('app', 'User').objects.all():
|
||||
user.config_sync_token = secrets.token_hex(64)
|
||||
user.save()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('app', '0003_auto_20210711_1855'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='user',
|
||||
name='config_sync_token',
|
||||
field=models.CharField(blank=True, max_length=255, null=True),
|
||||
),
|
||||
migrations.RunPython(run_forward, lambda _, __: None),
|
||||
migrations.AlterField(
|
||||
model_name='user',
|
||||
name='config_sync_token',
|
||||
field=models.CharField(max_length=255),
|
||||
),
|
||||
]
|
||||
18
tabby/app/migrations/0005_user_force_pro.py
Normal file
18
tabby/app/migrations/0005_user_force_pro.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.3 on 2021-07-24 10:13
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('app', '0004_sync_token'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='user',
|
||||
name='force_pro',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
28
tabby/app/migrations/0006_config_name.py
Normal file
28
tabby/app/migrations/0006_config_name.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def run_forward(apps, schema_editor):
|
||||
for config in apps.get_model('app', 'Config').objects.all():
|
||||
config.name = f'Unnamed config ({config.created_at.date()})'
|
||||
config.save()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('app', '0005_user_force_pro'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='config',
|
||||
name='name',
|
||||
field=models.CharField(max_length=255, null=True),
|
||||
),
|
||||
migrations.RunPython(run_forward, lambda _, __: None),
|
||||
migrations.AlterField(
|
||||
model_name='config',
|
||||
name='name',
|
||||
field=models.CharField(max_length=255),
|
||||
),
|
||||
]
|
||||
@@ -1,26 +1,38 @@
|
||||
import secrets
|
||||
from datetime import date
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
from django.contrib.auth.signals import user_logged_in
|
||||
from django.dispatch import receiver
|
||||
from django.db.models.signals import post_save
|
||||
|
||||
|
||||
class Config(models.Model):
|
||||
user = models.ForeignKey('app.User', related_name='configs', on_delete=models.CASCADE)
|
||||
name = models.CharField(max_length=255)
|
||||
content = models.TextField(default='{}')
|
||||
last_used_with_version = models.CharField(max_length=32, null=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
modified_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.name:
|
||||
self.name = f'Unnamed config ({date.today()})'
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class User(AbstractUser):
|
||||
active_config = models.ForeignKey(Config, null=True, on_delete=models.SET_NULL, related_name='+')
|
||||
active_version = models.CharField(max_length=32, null=True)
|
||||
custom_connection_gateway = models.CharField(max_length=255, null=True, blank=True)
|
||||
custom_connection_gateway_token = models.CharField(max_length=255, null=True, blank=True)
|
||||
config_sync_token = models.CharField(max_length=255)
|
||||
force_pro = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
modified_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.config_sync_token:
|
||||
self.config_sync_token = secrets.token_hex(64)
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class Gateway(models.Model):
|
||||
host = models.CharField(max_length=255)
|
||||
|
||||
@@ -2,25 +2,34 @@ from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
from gql import Client, gql
|
||||
from gql.transport.requests import RequestsHTTPTransport
|
||||
from social_django.models import UserSocialAuth
|
||||
|
||||
from .models import User
|
||||
|
||||
|
||||
GQL_ENDPOINT = 'https://api.github.com/graphql'
|
||||
CACHE_KEY = 'cached-sponsors'
|
||||
CACHE_KEY = 'cached-sponsors:%s'
|
||||
|
||||
|
||||
def fetch_sponsor_usernames():
|
||||
def check_is_sponsor(user: User) -> bool:
|
||||
try:
|
||||
token = user.social_auth.get(provider='github').extra_data.get('access_token')
|
||||
except UserSocialAuth.DoesNotExist:
|
||||
return False
|
||||
|
||||
if not token:
|
||||
return False
|
||||
|
||||
client = Client(
|
||||
transport=RequestsHTTPTransport(
|
||||
url=GQL_ENDPOINT,
|
||||
use_json=True,
|
||||
headers={
|
||||
'Authorization': f'Bearer {settings.GITHUB_TOKEN}',
|
||||
'Authorization': f'Bearer {token}',
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
result = []
|
||||
|
||||
after = None
|
||||
|
||||
while True:
|
||||
@@ -31,21 +40,17 @@ def fetch_sponsor_usernames():
|
||||
query = '''
|
||||
query {
|
||||
user (login: "eugeny") {
|
||||
sponsorshipsAsMaintainer(%s, includePrivate: true) {
|
||||
pageInfo {
|
||||
startCursor
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
nodes {
|
||||
createdAt
|
||||
tier {
|
||||
monthlyPriceInDollars
|
||||
}
|
||||
sponsor{
|
||||
... on User {
|
||||
login
|
||||
}
|
||||
sponsorshipsAsSponsor(%s) {
|
||||
pageInfo {
|
||||
startCursor
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
totalRecurringMonthlyPriceInDollars
|
||||
nodes {
|
||||
sponsorable {
|
||||
... on Organization { login }
|
||||
... on User { login }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,18 +59,22 @@ def fetch_sponsor_usernames():
|
||||
''' % (params,)
|
||||
|
||||
response = client.execute(gql(query))
|
||||
after = response['user']['sponsorshipsAsMaintainer']['pageInfo']['endCursor']
|
||||
nodes = response['user']['sponsorshipsAsMaintainer']['nodes']
|
||||
info = response['user']['sponsorshipsAsSponsor']
|
||||
after = info['pageInfo']['endCursor']
|
||||
nodes = info['nodes']
|
||||
if not len(nodes):
|
||||
break
|
||||
for node in nodes:
|
||||
if node['tier']['monthlyPriceInDollars'] >= settings.GITHUB_SPONSORS_MIN_PAYMENT:
|
||||
result.append(node['sponsor']['login'])
|
||||
if node['sponsorable']['login'].lower() not in settings.GITHUB_ELIGIBLE_SPONSORSHIPS:
|
||||
continue
|
||||
if info['totalRecurringMonthlyPriceInDollars'] >= settings.GITHUB_SPONSORS_MIN_PAYMENT:
|
||||
return True
|
||||
|
||||
return result
|
||||
return False
|
||||
|
||||
|
||||
def get_sponsor_usernames():
|
||||
if not cache.get(CACHE_KEY):
|
||||
cache.set(CACHE_KEY, fetch_sponsor_usernames(), timeout=30)
|
||||
return cache.get(CACHE_KEY)
|
||||
def check_is_sponsor_cached(user: User) -> bool:
|
||||
cache_key = CACHE_KEY % user.id
|
||||
if not cache.get(cache_key):
|
||||
cache.set(cache_key, check_is_sponsor(user), timeout=30)
|
||||
return cache.get(cache_key)
|
||||
|
||||
@@ -1,11 +1,44 @@
|
||||
import logging
|
||||
from tabby.app.models import User
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import hashers, logout, login
|
||||
from pyga.requests import Tracker, Page, Session, Visitor
|
||||
|
||||
|
||||
class GAMiddleware:
|
||||
class BaseMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
|
||||
class TokenMiddleware(BaseMiddleware):
|
||||
def __call__(self, request):
|
||||
token_value = None
|
||||
if 'auth_token' in request.GET:
|
||||
token_value = request.GET['auth_token']
|
||||
if request.META.get('HTTP_AUTHORIZATION'):
|
||||
token_type, *credentials = request.META['HTTP_AUTHORIZATION'].split()
|
||||
if token_type == 'Bearer' and len(credentials):
|
||||
token_value = credentials[0]
|
||||
|
||||
user = User.objects.filter(config_sync_token=token_value).first()
|
||||
|
||||
if user:
|
||||
request.session.save = lambda *args, **kwargs: None
|
||||
setattr(user, 'backend', 'django.contrib.auth.backends.ModelBackend')
|
||||
login(request, user)
|
||||
setattr(request, '_dont_enforce_csrf_checks', True)
|
||||
|
||||
response = self.get_response(request)
|
||||
|
||||
if user:
|
||||
response.set_cookie = lambda *args, **kwargs: None
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class GAMiddleware(BaseMiddleware):
|
||||
def __init__(self, get_response):
|
||||
super().__init__(get_response)
|
||||
if settings.GA_ID:
|
||||
self.tracker = Tracker(settings.GA_ID, settings.GA_DOMAIN)
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ MIDDLEWARE = [
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
'tabby.middleware.TokenMiddleware',
|
||||
'tabby.middleware.GAMiddleware',
|
||||
]
|
||||
|
||||
@@ -179,6 +180,8 @@ LOGIN_REDIRECT_URL = '/app'
|
||||
APP_DIST_PATH = Path(os.getenv('APP_DIST_PATH', BASE_DIR / 'app-dist'))
|
||||
NPM_REGISTRY = os.getenv('NPM_REGISTRY', 'https://registry.npmjs.org').rstrip('/')
|
||||
|
||||
GITHUB_ELIGIBLE_SPONSORSHIPS = None
|
||||
|
||||
for key in [
|
||||
'SOCIAL_AUTH_GITHUB_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_SECRET',
|
||||
@@ -191,7 +194,7 @@ for key in [
|
||||
'CONNECTION_GATEWAY_AUTH_CA',
|
||||
'CONNECTION_GATEWAY_AUTH_CERTIFICATE',
|
||||
'CONNECTION_GATEWAY_AUTH_KEY',
|
||||
'GITHUB_SPONSORS_USER',
|
||||
'GITHUB_ELIGIBLE_SPONSORSHIPS',
|
||||
'GITHUB_SPONSORS_MIN_PAYMENT',
|
||||
'GITHUB_TOKEN',
|
||||
'ENABLE_LOGIN',
|
||||
@@ -221,3 +224,8 @@ for key in [
|
||||
v = globals()[key]
|
||||
if v and not os.path.exists(v):
|
||||
raise ValueError(f'{v} does not exist')
|
||||
|
||||
if GITHUB_ELIGIBLE_SPONSORSHIPS:
|
||||
GITHUB_ELIGIBLE_SPONSORSHIPS = GITHUB_ELIGIBLE_SPONSORSHIPS.split(',')
|
||||
else:
|
||||
GITHUB_ELIGIBLE_SPONSORSHIPS = []
|
||||
|
||||
Reference in New Issue
Block a user